### Build and install manpages Source: https://github.com/tweag/topiary/blob/main/docs/manpages/README.md Standard build and installation commands for Topiary manpages. ```console $ make $ make install ``` -------------------------------- ### Format JSON using Nix Source: https://github.com/tweag/topiary/blob/main/docs/book/src/cli/usage/index.md Example of formatting a JSON string using Topiary built and run via Nix. This is an alternative to using the installed CLI. ```bash echo '{"foo":"bar"}' | nix run . -- format --language json ``` -------------------------------- ### Install Topiary using Nix Environment (No Flakes) Source: https://github.com/tweag/topiary/blob/main/docs/book/src/getting-started/installation/package-managers.md Install Topiary using the traditional Nix environment command. Note that on NixOS, you might use 'nixos.topiary'. ```sh # Or, without flakes: nix-env -iA nixpkgs.topiary ``` -------------------------------- ### Bash Grammar Query Examples Source: https://github.com/tweag/topiary/blob/main/docs/book/src/reference/capture-names/general.md Examples of queries for the Bash grammar demonstrating how order affects the final formatted output. ```scheme ; Query A: Append semicolon ( (word) @append_delimiter . ";"? @do_nothing (#delimiter! ";") ) ; Query B: Surround with quotes ( "\""? @do_nothing . (word) @prepend_delimiter @append_delimiter . "\""? @do_nothing (#delimiter! "\"") ) ``` -------------------------------- ### Install Topiary from AUR with Yay Source: https://github.com/tweag/topiary/blob/main/docs/book/src/getting-started/installation/package-managers.md Install Topiary from the Arch User Repository (AUR) using the `yay` helper. Ensure `yay` is installed. ```sh yay -S topiary ``` -------------------------------- ### Original Visualize File Command (v0.2) Source: https://github.com/tweag/topiary/blob/main/docs/migration-0.2-0.3.md Example of the 'Before' command for visualizing a file using Topiary v0.2.3. ```bash topiary --visualise[=FORMAT] \ --input-files INPUT_FILE \ [--output-file OUTPUT_FILE | > OUTPUT_FILE] ``` -------------------------------- ### Implement a complete client application Source: https://context7.com/tweag/topiary/llms.txt Demonstrates a simplified setup using the topiary-config and topiary-queries crates to format JSON input. ```rust use topiary_config::Configuration; use topiary_core::{formatter, Language, Operation, TopiaryQuery}; #[tokio::main] async fn main() { // Input JSON with poor formatting let mut input = r#"{"name":"John Doe","age":43, "phones":["+44 1234567","+44 2345678"]}"#.as_bytes(); let mut output = Vec::new(); // Load default configuration (includes all built-in languages) let config = Configuration::default(); // Get language configuration for JSON let json_config = config.get_language("json").unwrap(); // Get the default query file for JSON let query = topiary_queries::json(); // Get the grammar (will be fetched/compiled if needed) let grammar = json_config.grammar().unwrap(); // Create Language struct let language = Language { name: "json".to_owned(), query: TopiaryQuery::new(&grammar, query).unwrap(), grammar, indent: None, // Uses default (2 spaces) }; // Format the input formatter( &mut input, &mut output, &language, Operation::Format { skip_idempotence: false, tolerate_parsing_errors: false, }, ) .unwrap(); let formatted = String::from_utf8(output).expect("valid utf-8"); println!("Formatted JSON:\n{}", formatted); // Output: // { // "name": "John Doe", // "age": 43, // "phones": ["+44 1234567", "+44 2345678"] // } } ``` -------------------------------- ### Install Topiary with Homebrew Source: https://github.com/tweag/topiary/blob/main/docs/book/src/getting-started/installation/package-managers.md Install Topiary using the Homebrew package manager on macOS or Linux. Ensure Homebrew is installed. ```sh brew install topiary ``` -------------------------------- ### Install manpages with custom directory Source: https://github.com/tweag/topiary/blob/main/docs/manpages/README.md Build and install manpages to a specific directory by overriding the MAN_DIR variable. ```console $ make $ sudo make install MAN_DIR=/usr/share/man ``` -------------------------------- ### Install mdbook-manmunge Source: https://github.com/tweag/topiary/blob/main/docs/manpages/README.md Install the mdbook-manmunge utility via Cargo. ```console $ cargo install mdbook-manmunge ``` -------------------------------- ### Original Standard Input/Output Visualization Command (v0.2) Source: https://github.com/tweag/topiary/blob/main/docs/migration-0.2-0.3.md Example of the 'Before' command for visualizing using standard input and output with Topiary v0.2.3. ```bash topiary --visualise[=FORMAT] \ (--language LANGUAGE [--query QUERY]) \ < INPUT_FILE \ [--output-file OUTPUT_FILE | > OUTPUT_FILE] ``` -------------------------------- ### Serve Topiary Book Locally Source: https://github.com/tweag/topiary/blob/main/docs/book/README.md Use this command to serve the Topiary Book locally for development. Ensure you are in the `docs/book` directory and have Nix installed. ```console cd docs/book nix develop mdbook serve ``` -------------------------------- ### JSON Formatting Example Source: https://github.com/tweag/topiary/blob/main/docs/book/src/reference/capture-names/vertical-spacing.md Demonstrates single-line and multi-line JSON formatting with @prepend_input_softline. ```json { "single-line": [1 ,2 ,3 ,4], "multi-line": [1 ,2 ,3 ,4] } ``` -------------------------------- ### Install Topiary using Nix Profile (Flakes) Source: https://github.com/tweag/topiary/blob/main/docs/book/src/getting-started/installation/package-managers.md Install Topiary using Nix flakes. This command adds Topiary to your user profile. ```sh # Using flakes: nix profile install nixpkgs#topiary ``` -------------------------------- ### Format JSON using Cargo Source: https://github.com/tweag/topiary/blob/main/docs/book/src/cli/usage/index.md Example of formatting a JSON string using Topiary built and run via Cargo. This is an alternative to using the installed CLI. ```bash echo '{"foo":"bar"}' | cargo run -- format --language json ``` -------------------------------- ### Install Topiary with OPAM Source: https://github.com/tweag/topiary/blob/main/docs/book/src/getting-started/installation/package-managers.md Install Topiary using the OPAM package manager, primarily for formatting OCaml code. Ensure OPAM is set up correctly. ```sh opam install topiary ``` -------------------------------- ### Original Formatting Command (v0.2) Source: https://github.com/tweag/topiary/blob/main/docs/migration-0.2-0.3.md Example of the 'Before' command for formatting files in place using Topiary v0.2.3. ```bash topiary [--skip-idempotence] \ [--tolerate-parsing-errors] \ --in-place \ --input-files INPUT_FILES... ``` -------------------------------- ### Original Standard Input/Output Formatting Command (v0.2) Source: https://github.com/tweag/topiary/blob/main/docs/migration-0.2-0.3.md Example of the 'Before' command for formatting using standard input and output with Topiary v0.2.3. ```bash topiary [--skip-idempotence] \ [--tolerate-parsing-errors] \ (--language LANGUAGE [--query QUERY]) \ (--input-files - | < INPUT_FILE) \ [--output-file -] ``` -------------------------------- ### Query Language Reference - Complete JSON Formatting Example Source: https://context7.com/tweag/topiary/llms.txt A complete query file example demonstrating common patterns for JSON formatting. ```APIDOC ## Query Language Reference - Complete JSON Formatting Query Example A complete query file demonstrating common patterns. ```scheme ; Mark strings as leaves - don't format their contents (string) @leaf ; Space after colons in key-value pairs ":" @append_space ; Objects: indent contents, add softlines for multi-line formatting (object . "{" @append_spaced_softline @append_indent_start (pair) "}" @prepend_spaced_softline @prepend_indent_end . ) ; Arrays: same treatment as objects (array . "[" @append_spaced_softline @append_indent_start (_value) "]" @prepend_spaced_softline @prepend_indent_end . ) ; Add softlines after commas in objects and arrays (object "," @append_spaced_softline) (array "," @append_spaced_softline) ``` ``` -------------------------------- ### Install mdbook-man dependency Source: https://github.com/tweag/topiary/blob/main/docs/manpages/README.md Install the required version of mdbook-man from the git repository. ```console $ cargo install --git https://github.com/vv9k/mdbook-man.git ``` -------------------------------- ### Install Topiary CLI with Cargo Source: https://github.com/tweag/topiary/blob/main/docs/book/src/getting-started/installation/package-managers.md Use this command to install the Topiary CLI using the Rust package manager, Cargo. Ensure Cargo is installed and configured. ```sh cargo install topiary-cli ``` -------------------------------- ### Original Output Configuration Command (v0.2) Source: https://github.com/tweag/topiary/blob/main/docs/migration-0.2-0.3.md Example of the 'Before' command for outputting computed configuration using Topiary v0.2.3. ```bash topiary --output-configuration ... ``` -------------------------------- ### Original Configuration Override Command (v0.2) Source: https://github.com/tweag/topiary/blob/main/docs/migration-0.2-0.3.md Example of the 'Before' command for overriding configuration using Topiary v0.2.3. ```bash topiary --configuration-override CONFIG_FILE ... ``` -------------------------------- ### Nickel Configuration File Source: https://context7.com/tweag/topiary/llms.txt Examples of configuring language definitions in `languages.ncl` files using Nickel. ```APIDOC ## Nickel Configuration File Configuration is done via `languages.ncl` files using the Nickel configuration language. ### Basic language definition ```nickel { languages = { json = { extensions = ["json"], } } } ``` ### Language with custom indentation ```nickel { languages = { rust = { extensions = ["rs"], indent = " ", # 4 spaces } } } ``` ### Language with Git grammar source ```nickel { languages = { nickel = { extensions = ["ncl"], grammar.source.git = { git = "https://github.com/nickel-lang/tree-sitter-nickel", rev = "43433d8477b24cd13acaac20a66deda49b7e2547", # Required for Nix builds nixHash = "sha256-9Ei0uy+eGK9oiH7y2KIhB1E88SRzGnZinqECT3kYTVE=", }, } } } ``` ### Language with pre-compiled grammar ```nickel { languages = { custom_lang = { extensions = ["custom"], grammar.source.path = "/path/to/compiled/grammar.so", } } } ``` ### Override built-in configuration ```nickel { languages = { bash | force = { extensions = ["sh", "bash", "zsh"], indent = " ", # Override to 2 spaces } } } ``` ``` -------------------------------- ### Configure Indentation Start Source: https://github.com/tweag/topiary/blob/main/docs/book/src/reference/capture-names/indentation.md Triggers an indentation increase before or after matched nodes. Ensure all indentation starts and ends are balanced to avoid warnings. ```scheme ; Start an indented block after these [ "begin" "else" "then" "{" ] @append_indent_start ``` -------------------------------- ### Original Format File to New File Command (v0.2) Source: https://github.com/tweag/topiary/blob/main/docs/migration-0.2-0.3.md Example of the 'Before' command for formatting a file to a new file using Topiary v0.2.3. ```bash topiary [--skip-idempotence] \ [--tolerate-parsing-errors] \ (--language LANGUAGE | --query QUERY) \ --input-files INPUT_FILE \ --output-file OUTPUT_FILE ``` -------------------------------- ### Example JSON Input Source: https://github.com/tweag/topiary/blob/main/docs/book/src/reference/capture-names/vertical-spacing.md This JSON demonstrates hand-formatted structures to exhibit contexts for different line break capture operations. ```json { "single-line": [1, 2, 3, 4], "multi-line": [ 1, 2, 3 , 4 ] } ``` -------------------------------- ### OCaml Code Example Source: https://github.com/tweag/topiary/blob/main/docs/book/src/reference/capture-names/scopes.md A simple OCaml tuple expression used to demonstrate CST structure. ```ocaml (1,2, 3) ``` -------------------------------- ### Complete JSON Formatting Query Example Source: https://context7.com/tweag/topiary/llms.txt A comprehensive query file demonstrating common patterns for formatting JSON, including handling strings, colons, objects, and arrays. ```scheme ; Mark strings as leaves - don't format their contents (string) @leaf ; Space after colons in key-value pairs ":" @append_space ; Objects: indent contents, add softlines for multi-line formatting (object . "{" @append_spaced_softline @append_indent_start (pair) "}" @prepend_spaced_softline @prepend_indent_end . ) ; Arrays: same treatment as objects (array . "[" @append_spaced_softline @append_indent_start (_value) "]" @prepend_spaced_softline @prepend_indent_end . ) ; Add softlines after commas in objects and arrays (object "," @append_spaced_softline) (array "," @append_spaced_softline) ``` -------------------------------- ### Define Nickel language configuration Source: https://github.com/tweag/topiary/blob/main/docs/book/src/cli/configuration.md Example of defining a language entry with mandatory file extensions. ```nickel nickel = { extensions = ["ncl"], }, ``` -------------------------------- ### Example CST debug output Source: https://github.com/tweag/topiary/blob/main/docs/book/src/guides/suggested-workflow.md Sample output showing the structure of CST nodes for debugging query development. ```text [DEBUG atom_collection] CST node: {Node constructed_type (39, 15) - (39, 42)} - Named: true [DEBUG atom_collection] CST node: {Node type_constructor_path (39, 15) - (39, 35)} - Named: true [DEBUG atom_collection] CST node: {Node type_constructor (39, 15) - (39, 35)} - Named: true [DEBUG atom_collection] CST node: {Node type_constructor_path (39, 36) - (39, 42)} - Named: true [DEBUG atom_collection] CST node: {Node type_constructor (39, 36) - (39, 42)} - Named: true ``` -------------------------------- ### Tree-sitter query examples Source: https://github.com/tweag/topiary/blob/main/docs/book/src/guides/suggested-workflow.md Various query patterns for applying formatting rules to specific syntax tree nodes. ```scheme (type_constructor_path) @append_space ``` ```scheme ( (type_constructor_path) @append_space . (type_constructor_path) ) ``` ```scheme (constructed_type (_) @append_space . (_) ) ``` -------------------------------- ### Example Nix Build Error with Hash Mismatch Source: https://github.com/tweag/topiary/blob/main/docs/book/src/cli/configuration.md Illustrates a common error message when a Nix build fails due to a hash mismatch in a Topiary grammar derivation. ```log evaluation warning: Language `nickel`: no nixHash provided - using dummy value error: hash mismatch in fixed-output derivation '/nix/store/jgny7ll7plh7rfdnvdpgcb82kd51aiyx-tree-sitter-nickel-43433d8.drv': specified: sha256-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= got: sha256-9Ei0uy+eGK9oiH7y2KIhB1E88SRzGnZinqECT3kYTVE= error: 1 dependencies of derivation '/nix/store/0q20rk8l4g0n5fzr0w45agxx0j9qy65v-nickel-grammar-43433d8477b24cd13acaac20a66deda49b7e2547.drv' failed to build error: 1 dependencies of derivation '/nix/store/s5phxykjyzqay7gc33hc6f8kw4ndba25-languages-prefetched.json.drv' failed to build error: 1 dependencies of derivation '/nix/store/5w15p3b3xfw5nd6mxz58ln09v10kvf8v-languages-prefetched.ncl.drv' failed to build error: 1 dependencies of derivation '/nix/store/7zzyha67jw09kc37valp28bp5h6i7dka-topiary-0.6.0.drv' failed to build ``` -------------------------------- ### Anchor Usage in Queries Source: https://github.com/tweag/topiary/blob/main/docs/book/src/reference/capture-names/general.md Examples showing how to use anchors to restrict matches to specific parent nodes or structures. ```scheme ( (list_entry) @append_space . ) ``` ```scheme (list (list_entry) @append_space . ) ``` ```scheme (_ (list_entry) @append_space . ) ``` -------------------------------- ### Format JSON using Topiary CLI Source: https://github.com/tweag/topiary/blob/main/docs/book/src/cli/usage/index.md Example of formatting a JSON string using the `topiary format` command. Ensure the language is specified. ```bash echo '{"foo":"bar"}' | topiary format --language json ``` -------------------------------- ### Original Logging Configuration (v0.2) Source: https://github.com/tweag/topiary/blob/main/docs/migration-0.2-0.3.md Example of setting logging verbosity using the `RUST_LOG` environment variable in Topiary v0.2.3. ```bash RUST_LOG=warn topiary ... ``` -------------------------------- ### Topiary @prepend_spaced_softline Example Source: https://github.com/tweag/topiary/blob/main/docs/book/src/reference/capture-names/vertical-spacing.md Shows the output of @prepend_spaced_softline: adds a space before delimiters in single-line context and a line break in multi-line context. ```json { "single-line": [1 ,2 ,3 ,4], "multi-line": [1 ,2 ,3 ,4] } ``` -------------------------------- ### Run Topiary Docker Container for Formatting Source: https://github.com/tweag/topiary/blob/main/docs/book/src/getting-started/installation/package-managers.md Execute the Topiary CLI within a Docker container to format JSON input. This example pipes JSON data to the container for formatting. ```sh docker run --rm -i ghcr.io/topiary/topiary format -l json <<< '{"foo":123}' ``` -------------------------------- ### Topiary @prepend_empty_softline Example Source: https://github.com/tweag/topiary/blob/main/docs/book/src/reference/capture-names/vertical-spacing.md Demonstrates @prepend_empty_softline: consumes whitespace in single-line context and adds a line break before delimiters in multi-line context. ```json { "single-line": [1,2,3,4], "multi-line": [1 ,2 ,3 ,4] } ``` -------------------------------- ### Build Topiary with Prefetched Grammars Source: https://context7.com/tweag/topiary/llms.txt Optimize Topiary startup time by using pre-compiled grammars within a Nix configuration. ```nix { inputs.topiary.url = "github:tweag/topiary"; outputs = { self, nixpkgs, topiary, ... }: let system = "x86_64-linux"; topiaryLib = topiary.lib.${system}; in { packages.${system} = { # Topiary with default prefetched config topiary-prefetched = topiaryLib.wrapWithConfig topiary.packages.${system}.default topiaryLib.defaultConfigPrefetched; # Custom configuration with prefetched grammars topiary-custom = topiaryLib.wrapWithConfigFile topiary.packages.${system}.default (topiaryLib.prefetchLanguagesFile ./my-languages.ncl); }; }; } ``` -------------------------------- ### Output Tree-sitter parse tree as JSON with Topiary Source: https://context7.com/tweag/topiary/llms.txt Use the `--format json` flag with `topiary visualise` to get the parse tree in JSON format, suitable for programmatic analysis. ```bash # Output as JSON for programmatic analysis topiary visualise --format json input.json ``` -------------------------------- ### Integrate Topiary into git hooks with Nix Source: https://github.com/tweag/topiary/blob/main/docs/book/src/getting-started/installation/using-nix.md Add Topiary as a formatter in your project's pre-commit hooks using the `git-hooks.nix` integration. This example shows how to enable Topiary alongside other hooks. ```nix pre-commit-check = git-hooks-nix.run { hooks = { nixfmt.enable = true; ## keep your normal hooks ... ## Add the following: topiary-latest = topiary.lib.${system}.gitHook // { enable = true; }; }; }; ``` -------------------------------- ### Visualize Using Standard Input/Output (v0.3) Source: https://github.com/tweag/topiary/blob/main/docs/migration-0.2-0.3.md Use `topiary vis` with IO redirection to visualize content from standard input. Output can be redirected to a file. ```bash topiary vis [--format FORMAT] \ (--language LANGUAGE [--query QUERY]) \ < INPUT_FILE \ [> OUTPUT_FILE] ``` -------------------------------- ### Create test sample files Source: https://github.com/tweag/topiary/blob/main/docs/book/src/guides/adding-a-new-language.md Define input and expected output files for the I/O tester. ```sh echo 'void main ();' > topiary-cli/tests/samples/input/clang.c echo 'voidmain();' > topiary-cli/tests/samples/expected/clang.c ``` -------------------------------- ### Create query file Source: https://github.com/tweag/topiary/blob/main/docs/book/src/guides/adding-a-new-language.md Initialize the query file for the new language. ```sh touch topiary-queries/queries/clang.scm ``` -------------------------------- ### Build Topiary CLI with Nix (Grammars from Nixpkgs) Source: https://github.com/tweag/topiary/blob/main/docs/book/src/getting-started/installation/building-from-source.md Build the Topiary CLI using the flake's Topiary package, which sources grammars from nixpkgs. This is an alternative Nix build method. ```bash nix build .#topiary-cli-nix ``` -------------------------------- ### Display Topiary Configuration Sources Source: https://github.com/tweag/topiary/blob/main/docs/book/src/cli/configuration.md Use this command to list all detected configuration sources, including their paths and whether languages.ncl files or queries directories are present. ```bash $ topiary config show-sources ╭───────────┬──────────────────────────────────────────────────────┬───────────────┬─────────╮ │ source │ path │ languages.ncl │ queries │ ├───────────┼──────────────────────────────────────────────────────┼───────────────┼─────────┤ │ workspace │ /Users/USER_NAME/Documents/rust/topiary/.topiary │ ✗ │ ✗ │ ├───────────┼──────────────────────────────────────────────────────┼───────────────┼─────────┤ │ unix-home │ /Users/USER_NAME/.config/topiary │ ✓ │ ✓ │ ├───────────┼──────────────────────────────────────────────────────┼───────────────┼─────────┤ │ OS │ /Users/USER_NAME/Library/Application Support/topiary │ ✗ │ ✗ │ ├───────────┼──────────────────────────────────────────────────────┼───────────────┼─────────┤ │ built-in │ │ ✓ │ ✓ │ ╰───────────┴──────────────────────────────────────────────────────┴───────────────┴─────────╯ ``` -------------------------------- ### Build Topiary with Nix Source: https://github.com/tweag/topiary/blob/main/docs/book/src/getting-started/installation/building-from-source.md Use this command to build Topiary when Nix is enabled. Ensure you have flakes and nix-command enabled. ```bash nix build ``` -------------------------------- ### Anchor Interposition Example Source: https://github.com/tweag/topiary/blob/main/docs/book/src/reference/capture-names/general.md Demonstrates how anchors skip over anonymous nodes in a Bash statement. ```bash if this; then that; fi ``` ```scheme (if_statement (_) ; will match "this" . (_) ; will match "that" ) ``` -------------------------------- ### Format Using Standard Input/Output (v0.3) Source: https://github.com/tweag/topiary/blob/main/docs/migration-0.2-0.3.md Use IO redirection with `topiary fmt` to read from standard input and write to standard output. This replaces the previous `--input-files -` and `--output-file -` options. ```bash topiary fmt [--skip-idempotence] \ [--tolerate-parsing-errors] \ (--language LANGUAGE [--query QUERY]) \ < INPUT_FILE ``` -------------------------------- ### Build manpages with Nix Source: https://github.com/tweag/topiary/blob/main/docs/manpages/README.md Build the manpages derivation using the Nix package manager. ```console $ nix build .#topiary-manpages ``` -------------------------------- ### Topiary @prepend_hardline Example Source: https://github.com/tweag/topiary/blob/main/docs/book/src/reference/capture-names/vertical-spacing.md Illustrates the output when using @prepend_hardline on array delimiters, inserting a line break before each. ```json { "single-line": [1 ,2 ,3 ,4], "multi-line": [1 ,2 ,3 ,4] } ``` -------------------------------- ### Standard input redirection Source: https://github.com/tweag/topiary/blob/main/docs/book/src/cli/usage/format.md Demonstrates the correct way to pipe input into Topiary, as process substitution is not supported. ```sh # This won't work topiary format <(some_command) # Do this instead some_command | topiary format --language LANGUAGE ``` -------------------------------- ### Topiary @append_hardline Example Source: https://github.com/tweag/topiary/blob/main/docs/book/src/reference/capture-names/vertical-spacing.md Demonstrates the output when using @append_hardline on array delimiters, inserting a line break after each. ```json { "single-line": [1, 2, 3, 4], "multi-line": [1, 2, 3, 4] } ``` -------------------------------- ### Defining Custom Scopes Source: https://github.com/tweag/topiary/blob/main/docs/book/src/reference/capture-names/scopes.md Example of using capture names and the #scope_id! predicate to define a scope spanning parentheses. ```scheme (parenthesized_expression "(" @append_begin_scope ")" @prepend_end_scope (#scope_id! "tuple") ) ``` -------------------------------- ### Playground script usage instructions Source: https://github.com/tweag/topiary/blob/main/docs/book/src/playground/tty.md Provides the command-line syntax and parameter definitions for the playground script. ```text Usage: playground LANGUAGE [QUERY_FILE] [INPUT_SOURCE] LANGUAGE can be one of the supported languages (e.g., "ocaml", "rust", etc.). The packaged formatting queries for this language can be overridden by specifying a QUERY_FILE. The INPUT_SOURCE is optional. If not specified, it defaults to trying to find the bundled integration test input file for the given language. ``` -------------------------------- ### Visualize File (v0.3) Source: https://github.com/tweag/topiary/blob/main/docs/migration-0.2-0.3.md Use the `topiary vis` command to visualize a file. The format can be specified with `--format FORMAT`. Output can be redirected to a file. ```bash topiary vis [--format FORMAT] \ INPUT_FILE \ [> OUTPUT_FILE] ``` -------------------------------- ### Topiary @append_spaced_softline Example Source: https://github.com/tweag/topiary/blob/main/docs/book/src/reference/capture-names/vertical-spacing.md Illustrates @append_spaced_softline: adds a space after delimiters in single-line context and a line break in multi-line context. ```json { "single-line": [1, 2, 3, 4], "multi-line": [1, 2, 3, 4] } ``` -------------------------------- ### Format Files In Place (v0.3) Source: https://github.com/tweag/topiary/blob/main/docs/migration-0.2-0.3.md Use the `topiary fmt` command to format files in place. This replaces the previous `topiary --in-place` functionality. ```bash topiary fmt [--skip-idempotence] \ [--tolerate-parsing-errors] \ INPUT_FILES... ``` -------------------------------- ### Show Topiary configuration sources Source: https://context7.com/tweag/topiary/llms.txt The `topiary config show-sources` command displays information about all configuration sources Topiary is using, including their paths and whether language configuration files are present. ```bash # Show all configuration sources and detected files topiary config show-sources ``` -------------------------------- ### Insert Empty Softline Before Dots in Multi-line Constructs Source: https://github.com/tweag/topiary/blob/main/docs/book/src/reference/capture-names/vertical-spacing.md Uses @prepend_empty_softline to ensure dots in multi-line constructs start on new lines. ```scheme (_ "." @prepend_empty_softline ) ``` -------------------------------- ### Prefetching Topiary Grammars Source: https://github.com/tweag/topiary/blob/main/docs/book/src/cli/usage/prefetch.md Use the prefetch command to download and compile grammars. If no language is specified, all configured languages are processed. ```bash Prefetch languages in the configuration Usage: topiary prefetch [OPTIONS] [LANGUAGE] Arguments: [LANGUAGE] Fetch specified language (if not provided, all languages are prefetched) Options: -f, --force Re-fetch existing grammars if they already exist -C, --configuration Configuration file [env: TOPIARY_CONFIG_FILE] -M, --merge-configuration Enable merging for configuration files -v, --verbose... Logging verbosity (increased per occurrence) -h, --help Print help ``` -------------------------------- ### Topiary CLI Help Output Source: https://github.com/tweag/topiary/blob/main/docs/book/src/cli/usage/index.md Displays the main help message for the Topiary CLI, listing available commands and global options. Use `topiary --help` to view this. ```bash CLI app for Topiary, the universal code formatter. Usage: topiary [OPTIONS] Commands: format Format inputs visualise Visualise the input's Tree-sitter parse tree config Print the current configuration prefetch Prefetch languages in the configuration coverage Checks how much of the tree-sitter query is used check-grammar Check if an input parses to the respective Tree-sitter grammar completion Generate shell completion script help Print this message or the help of the given subcommand(s) Options: -C, --configuration Configuration file [env: TOPIARY_CONFIG_FILE] -M, --merge-configuration Enable merging for configuration files -v, --verbose... Logging verbosity (increased per occurrence) -h, --help Print help -V, --version Print version ``` -------------------------------- ### Topiary @append_empty_softline Example Source: https://github.com/tweag/topiary/blob/main/docs/book/src/reference/capture-names/vertical-spacing.md Shows the effect of @append_empty_softline: consumes whitespace in single-line context and adds a line break after delimiters in multi-line context. ```json { "single-line": [1,2,3,4], "multi-line": [1, 2, 3, 4] } ``` -------------------------------- ### Examine Computed Configuration (v0.3) Source: https://github.com/tweag/topiary/blob/main/docs/migration-0.2-0.3.md Use the `topiary cfg` command to examine the computed configuration in TOML format. This replaces the `--output-configuration` argument. ```bash topiary cfg ``` -------------------------------- ### Capture Placement Syntax Source: https://github.com/tweag/topiary/blob/main/docs/book/src/reference/capture-names/general.md Demonstrates the correct postfix syntax for applying captures to nodes. ```scheme (infix_operator) @prepend_space ``` ```scheme @append_space (infix_operator) ``` -------------------------------- ### Prefetch all configured Tree-sitter grammars with Topiary Source: https://context7.com/tweag/topiary/llms.txt Run `topiary prefetch` without arguments to download and compile all grammars defined in the current configuration. This can speed up initial formatting or enable offline usage. ```bash # Prefetch all configured languages topiary prefetch ``` -------------------------------- ### Query Language: Indentation Captures Source: https://context7.com/tweag/topiary/llms.txt Control indentation levels for code blocks using indentation start, end, multi-line, and no-indent captures. ```scheme ; Start indentation after opening braces [ "begin" "{" "[" ] @append_indent_start ``` ```scheme ; End indentation before closing braces [ "end" "}" "]" ] @prepend_indent_end ``` ```scheme ; Indent all lines of a multi-line node (not just first) (comment) @multi_line_indent_all ``` ```scheme ; Suppress indentation for specific nodes (line_number_directive) @single_line_no_indent ``` -------------------------------- ### Use a custom configuration file with Topiary Source: https://context7.com/tweag/topiary/llms.txt Specify a custom configuration file using the `--configuration` flag to override default settings or load language definitions from a specific location. ```bash # Use custom configuration file topiary format --configuration ./my-config/languages.ncl src/ ``` -------------------------------- ### Topiary @append_input_softline Example Source: https://github.com/tweag/topiary/blob/main/docs/book/src/reference/capture-names/vertical-spacing.md Demonstrates @append_input_softline: adds a space after delimiters in single-line context, and a line break in multi-line context only where input had a line break. ```json { "single-line": [1, 2, 3, 4], "multi-line": [1, 2, 3, 4] } ``` -------------------------------- ### Display Topiary coverage help information Source: https://github.com/tweag/topiary/blob/main/docs/book/src/cli/usage/coverage.md View the command-line interface options and arguments for the coverage subcommand. ```text Checks how much of the tree-sitter query is used Usage: topiary coverage [OPTIONS] <--language |FILE> Arguments: [FILE] Input file (omit to read from stdin) Language detection and query selection is automatic, mapped from file extensions defined in the Topiary configuration. Options: -l, --language Topiary language identifier (when formatting stdin) -q, --query Topiary query file override (when formatting stdin) -C, --configuration Configuration file [env: TOPIARY_CONFIG_FILE] -M, --merge-configuration Enable merging for configuration files -v, --verbose... Logging verbosity (increased per occurrence) -h, --help Print help (see a summary with '-h') ``` -------------------------------- ### Apply Uppercase to SQL Keywords Source: https://github.com/tweag/topiary/blob/main/docs/book/src/reference/capture-names/modification.md This snippet shows how to apply the @upper_case modifier to SQL keywords, specifically 'WHERE' in this example. Exercise caution in case-sensitive languages. ```scheme ; Make keyword "WHERE" uppercase (keyword_where) @upper_case ``` -------------------------------- ### Tree-sitter query for for-loops with if-statements Source: https://github.com/tweag/topiary/blob/main/docs/book/src/getting-started/on-tree-sitter.md This query identifies 'for' loops that have an 'if_statement' as their first child. It serves as a basic example of Tree-sitter's query syntax. ```scheme (for_loop . (if_statement) ) ``` -------------------------------- ### Format File to New File (v0.3) Source: https://github.com/tweag/topiary/blob/main/docs/migration-0.2-0.3.md Use IO redirection with `topiary fmt` to format a file and write the output to a new file. This replaces the previous `--output-file` argument. ```bash topiary fmt [--skip-idempotence] \ [--tolerate-parsing-errors] \ (--language LANGUAGE [--query QUERY]) \ < INPUT_FILE \ > OUTPUT_FILE ``` -------------------------------- ### Test language formatting Source: https://github.com/tweag/topiary/blob/main/docs/book/src/guides/adding-a-new-language.md Verify that Topiary recognizes the new language using the CLI. ```sh $ echo 'void main();' | cargo run -- format -s --language clang voidmain(); ``` -------------------------------- ### Enter Topiary Nix Devshell Source: https://github.com/tweag/topiary/blob/main/docs/book/src/getting-started/installation/building-from-source.md Enter the Topiary devshell provided by the flake to set up required environment variables and fetch dependencies for building with Cargo. ```bash nix develop ``` -------------------------------- ### Add Topiary to Home Manager Packages Source: https://github.com/tweag/topiary/blob/main/docs/book/src/getting-started/installation/package-managers.md Manage Topiary as a package within your Home Manager configuration by adding it to home.packages in home.nix. ```nix home.packages = with pkgs; [ topiary ]; ``` -------------------------------- ### Configure Topiary as a Git Hook Source: https://context7.com/tweag/topiary/llms.txt Integrate Topiary into a Nix project using git-hooks.nix to enforce formatting on commit. ```nix { inputs = { topiary.url = "github:tweag/topiary"; git-hooks.url = "github:cachix/git-hooks.nix"; }; outputs = { self, nixpkgs, topiary, git-hooks, ... }: let system = "x86_64-linux"; pkgs = nixpkgs.legacyPackages.${system}; in { checks.${system}.pre-commit-check = git-hooks.lib.${system}.run { src = ./.; hooks = { # Use default Topiary hook (all languages) topiary = topiary.lib.${system}.gitHook; }; }; # Or with custom configuration checks.${system}.custom-hook = git-hooks.lib.${system}.run { src = ./.; hooks = { topiary = topiary.lib.${system}.gitHookFor { # Only format specific languages includeLanguages = ["json" "nickel" "toml"]; # Or exclude languages # excludeLanguages = ["rust"]; }; }; }; devShells.${system}.default = pkgs.mkShell { inherit (self.checks.${system}.pre-commit-check) shellHook; }; }; } ``` -------------------------------- ### Tree-sitter query using @prepend_hardline capture name Source: https://github.com/tweag/topiary/blob/main/docs/book/src/getting-started/on-tree-sitter.md This example shows how the '@prepend_hardline' capture name can be used in Tree-sitter queries to enforce specific formatting, such as placing an 'if' statement on a new line when it's the first child of a 'for' loop. ```scheme (for_loop . (if_statement) @prepend_hardline ) ``` -------------------------------- ### Default Configurations Source: https://github.com/tweag/topiary/blob/main/docs/book/src/reference/nix.md Provides default Topiary configurations as Nix values and files, including prefetched versions. ```APIDOC ## `lib.defaultConfig` ### Description The default configuration of Topiary -- that is the content of `topiary-config/languages.ncl` -- but as a Nix value. ### Type ``` defaultConfig : TopiaryConfig ``` ## `lib.defaultConfigPrefetched` ### Description Same as `defaultConfig`, but where all the language grammars point to the Nix store path of a prefetched and precompiled version of the grammar. This is `prefetchLanguages defaultConfig`. ### Type ``` defaultConfigPrefetched ``` ## `lib.defaultConfigFile` ### Description Same as `defaultConfig` but as a Nickel File. ### Type ``` defaultConfigFile : File ``` ## `lib.defaultConfigFilePrefetched` ### Description Same as `defaultConfigPrefetched` but as a JSON file, consumable by Nickel. ### Type ``` defaultConfigFilePrefetched : File ``` ``` -------------------------------- ### Visualise Command Usage Source: https://github.com/tweag/topiary/blob/main/docs/book/src/cli/usage/visualise.md Displays the command-line interface options and arguments for the visualise subcommand. ```text Visualise the input's Tree-sitter parse tree Visualise generates a graph representation of the parse tree that can be rendered by external visualisation tools, such as Graphviz. By default, the output is in the DOT format. Usage: topiary visualise [OPTIONS] <--language |FILE> Arguments: [FILE] Input file (omit to read from stdin) Language detection and query selection is automatic, mapped from file extensions defined in the Topiary configuration. Options: -f, --format Visualisation format Possible values: - dot: GraphViz DOT serialisation - json: JSON serialisation [default: dot] -l, --language Topiary language identifier (when formatting stdin) -q, --query Topiary query file override (when formatting stdin) -C, --configuration Configuration file [env: TOPIARY_CONFIG_FILE] -M, --merge-configuration Enable merging for configuration files -v, --verbose... Logging verbosity (increased per occurrence) -h, --help Print help (see a summary with '-h') ``` -------------------------------- ### Format command usage Source: https://github.com/tweag/topiary/blob/main/docs/book/src/cli/usage/format.md Displays the command-line interface options and arguments for the format subcommand. ```text Usage: topiary format [OPTIONS] <--language |FILES> Arguments: [FILES]... Input files and directories (omit to read from stdin) Language detection and query selection is automatic, mapped from file extensions defined in the Topiary configuration. Options: -t, --tolerate-parsing-errors Consume as much as possible in the presence of parsing errors -s, --skip-idempotence Do not check that formatting twice gives the same output -l, --language Topiary language identifier (when formatting stdin) -q, --query Topiary query file override (when formatting stdin) -L, --follow-symlinks Follow symlinks (when formatting files) -C, --configuration Configuration file [env: TOPIARY_CONFIG_FILE] -M, --merge-configuration Enable merging for configuration files -v, --verbose... Logging verbosity (increased per occurrence) -h, --help Print help (see a summary with '-h') ``` -------------------------------- ### Prefetch a specific language grammar with Topiary Source: https://context7.com/tweag/topiary/llms.txt Use `topiary prefetch ` to download and compile the grammar for a specific language, useful for targeted updates or ensuring a particular grammar is available. ```bash # Prefetch a specific language topiary prefetch json ``` -------------------------------- ### Build Topiary with Cargo Source: https://github.com/tweag/topiary/blob/main/docs/book/src/getting-started/installation/building-from-source.md Build Topiary using standard Rust tools after ensuring `pkg-config` and `openssl` are available and required environment variables are set. This command is used outside of the Nix devshell. ```bash cargo build ``` -------------------------------- ### Inspect dependency topology Source: https://github.com/tweag/topiary/blob/main/MAINTAINERS.md Use cargo tree to visualize the dependency graph and identify package relationships. ```bash cargo tree --invert ``` -------------------------------- ### Visualize Tree-sitter parse tree from stdin with Topiary Source: https://context7.com/tweag/topiary/llms.txt The `topiary visualise` command can process input from standard input, requiring the `--language` to be specified if not inferred. ```bash # Visualise from stdin echo 'let x = 1 in x + 1' | topiary visualise --language ocaml --format dot ``` -------------------------------- ### Format a single file in place with Topiary Source: https://context7.com/tweag/topiary/llms.txt Use the `topiary format` command to format a single file. Language is detected from the file extension. ```bash # Format a single file in place topiary format src/config.json ``` -------------------------------- ### Fetch Git Repository Hash using nix-prefetch-git Source: https://github.com/tweag/topiary/blob/main/docs/book/src/cli/configuration.md Command to obtain the Nix hash for a Git repository, used for reproducible builds with Topiary and Nix. ```sh nix run nixpkgs#nix-prefetch-git -- https://github.com/bytecodealliance/tree-sitter-wit 230984dfaf803a0ff8f77da5034361a62c326577 ``` -------------------------------- ### Configuration Wrapping Source: https://github.com/tweag/topiary/blob/main/docs/book/src/reference/nix.md Functions to wrap Topiary derivations with specific configurations. ```APIDOC ## `lib.wrapWithConfig` ### Description Given a derivation providing `/bin/topiary` and a Topiary configuration ``, produce an executable running `topiary -C `. Note that this is different from building Topiary with a different default configuration: the resulting binary will not accept an additional `-C` argument. ### Type ``` wrapWithConfig : Derivation -> TopiaryConfig -> Derivation ``` ## `lib.wrapWithConfigFile` ### Description Same as `wrapWithConfig` but with the configuration as a Nickel file. ### Type ``` wrapWithConfigFile : Derivation -> File -> Derivation ``` ``` -------------------------------- ### Force re-fetch of existing grammars with Topiary Source: https://context7.com/tweag/topiary/llms.txt The `--force` flag with `topiary prefetch` will re-download and re-compile grammars even if they are already present, useful for updating to the latest grammar versions. ```bash # Force re-fetch existing grammars topiary prefetch --force ocaml ``` -------------------------------- ### Run language tests Source: https://github.com/tweag/topiary/blob/main/docs/book/src/guides/adding-a-new-language.md Execute the test suite for the newly added language. ```sh cargo test --no-default-features -F clang -p topiary-cli --test sample-tester ``` -------------------------------- ### Format multiple files with Topiary Source: https://context7.com/tweag/topiary/llms.txt The `topiary format` command can accept multiple file paths or glob patterns to format several files at once. ```bash # Format multiple files topiary format src/*.json config/*.toml ``` -------------------------------- ### Specify Git Grammar Source with Nix Hash for Topiary Source: https://github.com/tweag/topiary/blob/main/docs/book/src/cli/configuration.md Configure Topiary to fetch a grammar from Git and include a Nix hash for reproducible builds. This is required for Nix integration. ```nickel nickel = { extensions = ["ncl"], grammar.source.git = { git = "https://github.com/nickel-lang/tree-sitter-nickel", rev = "43433d8477b24cd13acaac20a66deda49b7e2547", nixHash = "sha256-9Ei0uy+eGK9oiH7y2KIhB1E88SRzGnZinqECT3kYTVE=", }, }, ``` -------------------------------- ### Add Topiary to Path with Nix Shell (No Flakes) Source: https://github.com/tweag/topiary/blob/main/docs/book/src/getting-started/installation/package-managers.md Temporarily add Topiary to your PATH using the standard Nix shell command. This makes Topiary available in the current shell session without flakes. ```sh # Or, without flakes: nix-shell -p topiary ```