### MQ REPL Mode Examples Source: https://context7.com/harehare/mq/llms.txt Shows how to start and use the interactive REPL mode for testing MQ queries and transformations. ```bash # Start REPL session mq repl # Example REPL session: # mq> .h # # Heading 1 # ## Heading 2 # mq> .code.lang # ["python", "javascript", "rust"] # mq> map([1,2,3], fn(x): x * 2;) # [2, 4, 6] ``` -------------------------------- ### Install Development Dependencies with ASDF Source: https://github.com/harehare/mq/blob/main/docs/books/src/start/development.md Installs development dependencies using ASDF, a tool version manager. This is an alternative method for setting up the project's required tools. ```sh asdf install ``` -------------------------------- ### Install mq CLI using curl Source: https://github.com/harehare/mq/blob/main/docs/books/src/start/install.md Installs the latest mq binary by downloading and executing an installation script. It adds the mq binary to ~/.mq/bin/ and updates the system's PATH. ```bash curl -sSL https://mqlang.org/install.sh | bash # Install the debugger curl -sSL https://mqlang.org/install.sh | bash -s -- --with-debug ``` -------------------------------- ### Install mq-lsp using pre-built binaries Source: https://github.com/harehare/mq/blob/main/docs/books/src/start/install.md Downloads and installs pre-built mq-lsp binaries for different operating systems and architectures directly from GitHub releases. Requires manual execution and making the binary executable. ```bash # macOS (Apple Silicon) curl -L https://github.com/harehare/mq/releases/download/v0.5.11/mq-lsp-aarch64-apple-darwin -o /usr/local/bin/mq-lsp && chmod +x /usr/local/bin/mq-lsp # Linux x86_64 curl -L https://github.com/harehare/mq/releases/download/v0.5.11/mq-lsp-x86_64-unknown-linux-gnu -o /usr/local/bin/mq-lsp && chmod +x /usr/local/bin/mq-lsp # Linux arm64 curl -L https://github.com/harehare/mq/releases/download/v0.5.11/mq-lsp-aarch64-unknown-linux-gnu -o /usr/local/bin/mq-lsp && chmod +x /usr/local/bin/mq-lsp # Windows (PowerShell) Invoke-WebRequest -Uri https://github.com/harehare/mq/releases/download/v0.5.11/mq-lsp-x86_64-pc-windows-msvc.exe -OutFile "$env:USERPROFILE\bin\mq-lsp.exe" ``` -------------------------------- ### Install mq CLI using pre-built binaries Source: https://github.com/harehare/mq/blob/main/docs/books/src/start/install.md Downloads and installs pre-built mq binaries for different operating systems and architectures directly from GitHub releases. Requires manual execution and making the binary executable. ```bash # macOS (Apple Silicon) curl -L https://github.com/harehare/mq/releases/download/v0.5.11/mq-aarch64-apple-darwin -o /usr/local/bin/mq && chmod +x /usr/local/bin/mq # Linux x86_64 curl -L https://github.com/harehare/mq/releases/download/v0.5.11/mq-x86_64-unknown-linux-gnu -o /usr/local/bin/mq && chmod +x /usr/local/bin/mq # Linux arm64 curl -L https://github.com/harehare/mq/releases/download/v0.5.11/mq-aarch64-unknown-linux-gnu -o /usr/local/bin/mq && chmod +x /usr/local/bin/mq # Windows (PowerShell) Invoke-WebRequest -Uri https://github.com/harehare/mq/releases/download/v0.5.11/mq-x86_64-pc-windows-msvc.exe -OutFile "$env:USERPROFILE\bin\mq.exe" ``` -------------------------------- ### Install mq using binstall Source: https://github.com/harehare/mq/blob/main/README.md Installs a specific version of the mq-run binary using the binstall package manager. This is a faster installation method if binstall is configured. ```sh cargo binstall mq-run@0.5.11 ``` -------------------------------- ### Install mq using curl script Source: https://github.com/harehare/mq/blob/main/README.md This command downloads and executes an installation script to install the mq command-line tool. It fetches the latest binary for the current platform, installs it to `~/.mq/bin/`, and updates the shell profile to include mq in the PATH. ```bash curl -sSL https://mqlang.org/install.sh | bash ``` -------------------------------- ### Install mq-lsp using curl Source: https://github.com/harehare/mq/blob/main/docs/books/src/start/install.md Installs the mq Language Server (mq-lsp) by downloading and executing an installation script. This provides IDE features like code completion and diagnostics for mq files. ```bash curl -sSL https://mqlang.org/install_lsp.sh | bash ``` -------------------------------- ### Install mq-lsp using binstall Source: https://github.com/harehare/mq/blob/main/README.md Installs a specific version of the mq Language Server using the binstall package manager. This is a faster installation method if binstall is configured. ```sh cargo binstall mq-lsp@0.5.11 ``` -------------------------------- ### Install MQ Debugger via Shell Script Source: https://github.com/harehare/mq/blob/main/docs/books/src/start/debugger.md Installs the MQ debugger by downloading and executing an installation script. This method is quick and suitable for most users. Ensure you have `curl` installed. ```bash curl -sSL https://mqlang.org/install.sh | bash -s -- --with-debug ``` -------------------------------- ### Install Development Dependencies with Cargo Source: https://github.com/harehare/mq/blob/main/docs/books/src/start/development.md Installs the 'just' command runner and 'wasm-pack' for WebAssembly support using Cargo, Rust's package manager. This command ensures necessary tools are available for development. ```sh cargo install just wasm-pack ``` -------------------------------- ### Install mq-lsp from crates.io (Cargo) Source: https://github.com/harehare/mq/blob/main/README.md Installs the mq Language Server from the official Rust crates.io registry using Cargo. This requires Rust and Cargo to be installed. ```sh cargo install mq-lsp ``` -------------------------------- ### Install mq-lsp using Cargo Source: https://github.com/harehare/mq/blob/main/docs/books/src/start/install.md Installs the mq Language Server (mq-lsp) using the Rust package manager, Cargo. Supports installation from crates.io, GitHub (specific versions or latest development). ```bash # Install from crates.io car go install mq-lsp # Install from Github cargo install --git https://github.com/harehare/mq.git mq-lsp --tag v0.5.11 # Latest Development Version cargo install --git https://github.com/harehare/mq.git mq-lsp # Install using binstall car go binstall mq-lsp@0.5.11 ``` -------------------------------- ### MQ Debugger Installation and Usage Source: https://context7.com/harehare/mq/llms.txt Provides instructions for installing and using the MQ debugger to step through execution and inspect program state. ```bash # Install debugger cargo install --git https://github.com/harehare/mq.git mq-run --bin mq-dbg # Run with debugger mq-dbg -f your-script.mq input.md # Debugger commands: # step (s) - Step into next expression # next (n) - Step over current expression # continue (c) - Continue to next breakpoint # breakpoint 15 - Set breakpoint at line 15 # info (i) - Display current environment # backtrace (bt) - Print call stack # quit (q) - Exit debugger ``` -------------------------------- ### Install mq TUI Source: https://github.com/harehare/mq/blob/main/docs/books/src/start/tui.md This snippet shows the command to install the mq TUI using a curl script. It fetches the installation script from a GitHub repository and executes it with bash. ```bash curl -fsSL https://raw.githubusercontent.com/harehare/mq-tui/main/bin/install.sh | bash ``` -------------------------------- ### Install mq using Cargo (GitHub) Source: https://github.com/harehare/mq/blob/main/README.md This command installs the `mq-run` executable directly from the mq GitHub repository using Cargo. It allows you to install a specific tagged version, in this case, v0.5.11. ```rust cargo install --git https://github.com/harehare/mq.git mq-run --tag v0.5.11 ``` -------------------------------- ### Install mq CLI using Homebrew Source: https://github.com/harehare/mq/blob/main/docs/books/src/start/install.md Installs the mq command-line tool using the Homebrew package manager, available for both macOS and Linux systems. This is a convenient way to manage installations and updates. ```bash # Using Homebrew (macOS and Linux) $ brew install harehare/tap/mq ``` -------------------------------- ### Install mq CLI using Cargo Source: https://github.com/harehare/mq/blob/main/docs/books/src/start/install.md Installs the mq command-line tool using the Rust package manager, Cargo. Supports installation from crates.io, GitHub (specific versions or latest development), and with debugger features. ```bash # Install from crates.io car go install mq-run # Install from Github cargo install --git https://github.com/harehare/mq.git mq-run --tag v0.5.11 # Latest Development Version cargo install --git https://github.com/harehare/mq.git mq-run --bin mq # Install the debugger cargo install --git https://github.com/harehare/mq.git mq-run --bin mq-dbg --features="debugger" # Install using binstall car go binstall mq-run@0.5.11 ``` -------------------------------- ### Install mq Python package Source: https://github.com/harehare/mq/blob/main/docs/books/src/start/install.md Installs the 'markdown-query' Python package, which provides mq functionality within Python applications. This is done using pip, the standard Python package installer. ```sh # Install from PyPI $ pip install markdown-query ``` -------------------------------- ### Install mq-lsp from Github (Cargo) Source: https://github.com/harehare/mq/blob/main/README.md Installs a specific tagged version of the mq Language Server from the GitHub repository using Cargo. This requires Rust and Cargo. ```sh cargo install --git https://github.com/harehare/mq.git mq-lsp --tag v0.5.11 ``` -------------------------------- ### Create and view sample mq file with bat Source: https://github.com/harehare/mq/blob/main/docs/books/src/start/syntax-highlighting.md This snippet shows how to create a sample mq file using 'cat' and then view it with syntax highlighting using 'bat'. It includes a simple mq program example. ```sh cat > example.mq << 'EOF' \ # This is a comment def greet(name): s"Hello, ${name}!" end .h | .text | greet("World") EOF bat example.mq ``` -------------------------------- ### Install mq npm package Source: https://github.com/harehare/mq/blob/main/docs/books/src/start/install.md Installs the 'mq-web' npm package, enabling the use of mq within Node.js and web projects. This is installed using npm, the Node Package Manager. ```sh $ npm i mq-web ``` -------------------------------- ### Setup mq Syntax Highlighting for bat Source: https://github.com/harehare/mq/blob/main/docs/books/src/start/syntax-highlighting.md These commands set up syntax highlighting for mq files in the 'bat' utility. It involves creating a directory, downloading the syntax file, and rebuilding the cache. ```sh mkdir -p "$(bat --config-dir)/syntaxes" curl -o "$(bat --config-dir)/syntaxes/mq.sublime-syntax" \ https://raw.githubusercontent.com/harehare/mq/main/assets/mq.sublime-syntax bat cache --build ``` -------------------------------- ### Install mq using Cargo (crates.io) Source: https://github.com/harehare/mq/blob/main/README.md This command installs the `mq-run` executable from the crates.io registry using Cargo, Rust's package manager. It ensures you have the latest stable version available on crates.io. ```rust cargo install mq-run ``` -------------------------------- ### Python Doc-Comment Example Source: https://github.com/harehare/mq/blob/main/docs/books/src/reference/comments.md Demonstrates a doc-comment in Python. Comments starting with '#' are treated as documentation comments, similar to jq. ```python # doc-comment let value = add(2, 3); ``` -------------------------------- ### Install mq Latest Development Version (Cargo) Source: https://github.com/harehare/mq/blob/main/README.md Installs the latest development version of the mq-run binary from the official GitHub repository using Cargo. This method requires Rust and Cargo to be installed. ```sh cargo install --git https://github.com/harehare/mq.git mq-run --bin mq ``` -------------------------------- ### Use mq in GitHub Actions Source: https://github.com/harehare/mq/blob/main/docs/books/src/start/install.md Integrates mq into GitHub Actions workflows using the 'setup-mq' action. This allows running mq commands within CI/CD pipelines. ```yaml steps: - uses: actions/checkout@v4 - uses: harehare/setup-mq@v1 - run: mq '.code' README.md ``` -------------------------------- ### MQ Basic Usage Examples Source: https://github.com/harehare/mq/blob/main/README.md Demonstrates fundamental ways to use the MQ CLI for data extraction and filtering from Markdown files. Examples include extracting headings, code blocks, links, and table cells. ```sh # Extract all headings from a document mq '.h' README.md # Extract code blocks containing "name" mq '.code | select(contains("name"))' example.md # Extract code values from code blocks mq -A 'pluck(.code.value)' example.md # Extract language names from code blocks mq '.code.lang' documentation.md # Extract URLs from all links mq '.link.url' README.md # Filter table cells containing "name" mq '.[][] | select(contains("name"))' data.md # Select lists or headers containing "name" mq 'select(.[] || .h) | select(contains("name"))' docs.md # Exclude JavaScript code blocks mq '.code | select(.code.lang != "js")' examples.md # Convert CSV to markdown table mq 'include "csv" | csv_parse(true) | csv_to_markdown_table()' example.csv ``` -------------------------------- ### Install MQ Debugger via Cargo Source: https://github.com/harehare/mq/blob/main/docs/books/src/start/debugger.md Installs the MQ debugger by building it from the source repository using Cargo. This method requires Rust and Cargo to be installed. It specifically builds the `mq-dbg` binary. ```bash cargo install --git https://github.com/harehare/mq.git mq-run --bin mq-dbg ``` -------------------------------- ### Install mq-lsp Latest Development Version (Cargo) Source: https://github.com/harehare/mq/blob/main/README.md Installs the latest development version of the mq Language Server from the GitHub repository using Cargo. This requires Rust and Cargo. ```sh cargo install --git https://github.com/harehare/mq.git mq-lsp ``` -------------------------------- ### Install markdown-query Python Package Source: https://github.com/harehare/mq/blob/main/README.md Installs the 'markdown-query' Python package from PyPI, which provides access to mq's functionality within Python applications. This requires pip to be installed. ```sh # Install from PyPI pip install markdown-query ``` -------------------------------- ### Run mq using Docker Source: https://github.com/harehare/mq/blob/main/docs/books/src/start/install.md Executes the mq command-line tool within a Docker container. This method isolates the mq environment and is useful for testing or environments where direct installation is not desired. ```bash $ docker run --rm ghcr.io/harehare/mq:0.5.11 ``` -------------------------------- ### Basic Rust Program Output Source: https://github.com/harehare/mq/blob/main/assets/demo.md A simple 'Hello, world!' program written in Rust, demonstrating basic syntax. This serves as a foundational example for Rust code. ```rust fn main() { println!("Hello, mq!"); } ``` -------------------------------- ### Install mqcr using Homebrew Source: https://github.com/harehare/mq/blob/main/docs/books/src/start/crawler.md Installs the mqcr binary using the Homebrew package manager on macOS and Linux systems. This is the recommended method for easy installation and updates. ```shell # Using Homebrew (macOS and Linux) $ brew install harehare/tap/mqcr ``` -------------------------------- ### Install mq Debugger (Cargo) Source: https://github.com/harehare/mq/blob/main/README.md Installs the mq-run binary with debugger support enabled from the GitHub repository using Cargo. This requires Rust and Cargo, and enables the 'debugger' feature. ```sh cargo install --git https://github.com/harehare/mq.git mq-run --bin mq-dbg --features="debugger" ``` -------------------------------- ### mqcr Examples: Basic Crawling, Custom Delay, and mq-lang Query Source: https://github.com/harehare/mq/blob/main/docs/books/src/start/crawler.md Demonstrates common usage patterns for the mqcr web crawler. Examples include basic crawling to standard output, saving content to a directory with a custom crawl delay, and processing crawled content with an mq-lang query. ```bash # Basic crawling to stdout mqcr https://example.com ``` ```bash # Save to directory with custom delay mqcr -o ./output -c 2 https://example.com ``` ```bash # Process with mq-lang query mqcr -m '.h | select(contains("News"))' https://example.com ``` -------------------------------- ### MQ Advanced Usage Examples Source: https://github.com/harehare/mq/blob/main/README.md Illustrates more complex operations using the MQ CLI, such as chaining commands, string interpolation, merging files, and converting HTML to Markdown. These examples showcase the power of MQ for sophisticated data manipulation. ```sh # Generate a table of contents from headings mq '.h | let link = to_link("#" + to_text(self), to_text(self), "") | let level = .h.level | if (!is_none(level)): to_md_list(link, level)' docs/books/**/*.md # String interpolation mq 'let name = "Alice" | let age = 30 | s"Hello, my name is ${name} and I am ${age} years old." # Merge multiple files with separators mq -S 's"\n${__FILE__}\n"' 'identity()' docs/books/**/**.md # Extract all code blocks from an HTML file mq '.code' example.html # Convert HTML to Markdown and filter headers mq 'select(.h1 || .h2)' example.html # Extract specific cell from a Markdown table mq '.[1][2] | to_text()' data.md ``` -------------------------------- ### Install MQ Debugger via Homebrew Source: https://github.com/harehare/mq/blob/main/docs/books/src/start/debugger.md Installs the MQ debugger using the Homebrew package manager. This is a convenient option for macOS and Linux users who manage their packages with Homebrew. Ensure you have Homebrew installed. ```bash brew install harehare/tap/mq-dbg ``` -------------------------------- ### Clone Harehare MQ Repository Source: https://github.com/harehare/mq/blob/main/docs/books/src/start/development.md Clones the Harehare MQ project repository from GitHub and navigates into the project directory. This is the initial step for setting up the development environment. ```sh git clone https://github.com/harehare/mq.git cd mq ``` -------------------------------- ### Extract Context for LLM Prompts using MQ CLI Source: https://github.com/harehare/mq/blob/main/docs/books/src/start/example.md Extract specific sections from documents to create focused context for LLM inputs. This example selects sections with headings or code and limits the output to the first 10. ```javascript select(.h || .code) | self[:10] ``` -------------------------------- ### Generate Documentation Index with MQ CLI Source: https://github.com/harehare/mq/blob/main/docs/books/src/start/example.md Create a documentation index by extracting headings and formatting them as markdown links. This script determines the heading level for indentation and generates anchors from the heading text. ```javascript .h | let level = .h.level | let text = to_text(self) | let indent = repeat(" ", level - 1) | let anchor = downcase(replace(text, " ", "-")) | if (!is_empty(text)): s"${indent}- [${text}](#${anchor})" ``` -------------------------------- ### Find Code Examples by Language with MQ Source: https://context7.com/harehare/mq/llms.txt Filters Markdown files to find code blocks of a specific language, in this case, Python. ```bash mq '.code | select(.code.lang == "python")' tutorials/*.md ``` -------------------------------- ### Run Formatter and Linter Source: https://github.com/harehare/mq/blob/main/docs/books/src/start/development.md Executes the code formatter and linter for the Harehare MQ project. This helps maintain consistent code style and identify potential issues. ```sh just lint ``` -------------------------------- ### Run Harehare MQ CLI Source: https://github.com/harehare/mq/blob/main/docs/books/src/start/development.md Executes the Harehare MQ command-line interface (CLI) with specified arguments. This command is useful for testing CLI functionality during development. ```sh just run '.code' ``` -------------------------------- ### mq String Interpolation Example with Variables Source: https://github.com/harehare/mq/blob/main/docs/books/src/reference/string_interpolation.md Provides a practical example of using string interpolation in mq to construct a greeting message. It embeds two variables, 'name' and 'age', into a string literal. The output is a formatted string. ```mq let name = "Alice" | let age = 30 | s"Hello, my name is ${name} and I am ${age} years old." # => Output: "Hello, my name is Alice and I am 30 years old." ``` -------------------------------- ### Extract Specific Sections in MQ Source: https://github.com/harehare/mq/blob/main/docs/books/src/reference/section_functions.md This usage pattern demonstrates how to extract the content of a specific section, such as 'Installation'. It involves splitting the document into sections, filtering by title, selecting the first matching section, and then extracting its content. ```mq include "section" # Get all content from "Installation" section | h2() | split(2) | title_contains("Installation") | nth(0) | content() ``` -------------------------------- ### Build Harehare MQ in Release Mode Source: https://github.com/harehare/mq/blob/main/docs/books/src/start/development.md Compiles the Harehare MQ project in release mode, optimizing for performance. This is typically done before deployment or for performance testing. ```sh just build ``` -------------------------------- ### Advanced Macro Usage: Nesting and Function Parameters in mq Source: https://github.com/harehare/mq/blob/main/docs/books/src/reference/macros.md Illustrates advanced macro techniques, including nesting macro calls and accepting functions as parameters. These examples showcase the flexibility of macros for complex code generation scenarios. ```mq macro double(x): x + x macro quadruple(x): double(double(x)) | quadruple(3) # Returns 12 macro apply_twice(f, x) do f(f(x)) end def inc(n): n + 1; | apply_twice(inc, 5) # Returns 7 ``` -------------------------------- ### MQ Conditional Logic Examples (Python) Source: https://github.com/harehare/mq/blob/main/docs/books/src/reference/conditionals.md Demonstrates the usage of AND, OR, and NOT conditional functions in MQ using Python syntax. These functions are essential for building complex logic flows. ```python # Basic comparisons and(true, true, true) true && true && true # => true or(true, false, true) true || false || true # => true not(false) !false # => true ``` -------------------------------- ### List Available mq Functions Source: https://github.com/harehare/mq/blob/main/docs/books/src/start/mcp.md Tool to retrieve a list of all available mq functions. The output is a JSON object detailing function names, their descriptions, parameters, and usage examples. ```javascript available_functions() ``` -------------------------------- ### MQ with Markitdown Integration Source: https://github.com/harehare/mq/blob/main/README.md Shows how to integrate MQ with the Markitdown tool for enhanced Markdown processing. Examples include extracting code blocks and tables from Markdown content processed by Markitdown. ```sh # Extract code blocks from markdown markitdown https://github.com/harehare/mq | mq '.code' # Extract table from markdown markitdown test.xlsx | mq '.[][]' ``` -------------------------------- ### Generate XML Sitemap from Markdown Files Source: https://github.com/harehare/mq/blob/main/docs/books/src/start/example.md Generates an XML sitemap entry for a given Markdown file, converting its path to an HTML equivalent and constructing a URL entry. This is typically used in conjunction with a command-line tool to process multiple files. ```scala def sitemap(item, base_url): let path = replace(to_text(item), ".md", ".html") | let loc = base_url + path | s" ${loc} 1.0 " end ``` -------------------------------- ### Run MQ Script with Debugger Source: https://github.com/harehare/mq/blob/main/docs/books/src/start/debugger.md Executes an MQ script using the `mq-dbg` binary, enabling the debugger. This command takes the script file and input data as arguments. The debugger will start upon execution. ```bash mq-dbg -f your-script.mq input.md ``` -------------------------------- ### Practical Example: Describing Data Types Source: https://github.com/harehare/mq/blob/main/docs/books/src/reference/pattern_matching.md A practical function `describe` that uses pattern matching to provide a textual description for various data types, including none, booleans, numbers (differentiating by magnitude), strings, arrays, and dictionaries. ```ruby def describe(value): match (value): | :none: "nothing" | :bool: "true or false" | x if (gt(x, 100)): "big number" | :number: "small number" | "": "empty string" | :string: "text" | []: "empty list" | [x]: s"list with one item: ${x}" | [_, ..rest]: "list with multiple items" | {}: "empty object" | _: "dictionary" end end ``` -------------------------------- ### View mq file with bat syntax highlighting Source: https://github.com/harehare/mq/blob/main/docs/books/src/start/syntax-highlighting.md Demonstrates how to use the 'bat' command to display an mq file with syntax highlighting enabled. This assumes the syntax highlighting has been previously set up. ```sh bat query.mq ``` -------------------------------- ### Document Statistics with MQ CLI Source: https://github.com/harehare/mq/blob/main/docs/books/src/start/example.md Generate statistics about document content, such as the count of headers, paragraphs, code blocks, and links. This command uses a complex expression to aggregate these counts. ```bash $ mq -A 'let headers = count_by(fn(x): x | select(.h);) | let paragraphs = count_by(fn(x): x | select(.text);) | let code_blocks = count_by(fn(x): x | select(.code);) | let links = count_by(fn(x): x | select(.link);) | s"Headers: ${headers}, Paragraphs: ${paragraphs}, Code: ${code_blocks}, Links: ${links}"' docs/books/**/**.md ``` -------------------------------- ### Process Files in Parallel with MQ CLI Source: https://github.com/harehare/mq/blob/main/docs/books/src/start/example.md Efficiently process a large number of files concurrently using the MQ CLI. This command utilizes the -P flag to specify the number of parallel processes. ```bash $ mq -P 5 '.h1' docs/**/*.md ``` -------------------------------- ### Configure mq MCP Server for VS Code Source: https://github.com/harehare/mq/blob/main/docs/books/src/start/mcp.md Configuration for the mq MCP server within VS Code settings. This setup defines the server type, command, and arguments required for the MCP server to function within the editor. ```json { "mcp": { "servers": { "mq-mcp": { "type": "stdio", "command": "/path/to/mq", "args": ["mcp"] } } } } ``` -------------------------------- ### Merge Multiple Markdown Files with Separators Source: https://github.com/harehare/mq/blob/main/docs/books/src/start/example.md Combines multiple Markdown files into a single output, inserting a specified separator (including the file path) between the content of each file. This is useful for concatenating documentation from various sources. ```bash $ mq -S 's"\n${__FILE__}\n"' 'identity()' docs/**/*.md ``` -------------------------------- ### MQ CLI Usage and Commands Source: https://github.com/harehare/mq/blob/main/README.md Details the general usage of the MQ CLI, including available commands like 'repl', 'fmt', 'docs', 'check', and 'help'. It also lists various command-line options for input/output formats, file handling, and module loading. ```sh Usage: mq [OPTIONS] [QUERY OR FILE] [FILES]... [COMMAND] Commands: repl Start a REPL session for interactive query execution fmt Format mq files based on specified formatting options docs Show functions documentation for the query check Check syntax errors in mq files help Print this message or the help of the given subcommand(s) Arguments: [QUERY OR FILE] [FILES]... Options: -A, --aggregate Aggregate all input files/content into a single array -f, --from-file load filter from the file -I, --input-format Set input format [possible values: markdown, mdx, html, text, null, raw] -L, --directory Search modules from the directory -M, --module-names Load additional modules from specified files --args Sets string that can be referenced at runtime --rawfile Sets file contents that can be referenced at runtime --stream Enable streaming mode for processing large files line by line --json --csv Include the built-in CSV module --fuzzy Include the built-in Fuzzy module --yaml Include the built-in YAML module --toml Include the built-in TOML module --xml Include the built-in XML module --test Include the built-in test module -F, --output-format Set output format [default: markdown] [possible values: markdown, html, text, json, none] -U, --update Update the input markdown (aliases: -i, --in-place, --inplace) --unbuffered Unbuffered output --list-style Set the list style for markdown output [default: dash] [possible values: dash, plus, star] --link-title-style Set the link title surround style for markdown output [default: double] [possible values: double, single, paren] --link-url-style Set the link URL surround style for markdown links [default: none] [possible values: none, angle] -S, --separator Specify a query to insert between files as a separator -o, --output Output to the specified file --list List all available subcommands (built-in and external) -P Number of files to process before switching to parallel processing [default: 10] -h, --help Print help -V, --version Print version ``` -------------------------------- ### mq CLI Basic Usage and Options Source: https://context7.com/harehare/mq/llms.txt Demonstrates fundamental mq command-line operations, including basic queries, language-specific code extraction, parallel processing, output formatting, in-place updates, loading queries from files, aggregating files, and interactive REPL usage. ```bash # Basic query on a markdown file mq '.h' README.md # Extract code blocks with specific language mq '.code "rust"' example.md # Process multiple files with parallel execution mq -P 5 '.h1' docs/**/*.md # Output as JSON format mq -F json '.link.url' README.md # Update file in-place mq -U 'select(!.code)' document.md # Load query from file mq -f query.mq input.md # Aggregate multiple files into single array mq -A 'pluck(.code.value)' *.md # Start interactive REPL session mq repl # Format mq files mq fmt --check file.mq # Check syntax errors mq check query.mq ``` -------------------------------- ### Data Structure Access: Attr, Get, Get Or, Entries Source: https://github.com/harehare/mq/blob/main/docs/books/src/reference/builtin_functions.md Functions for accessing data within structures. `attr` retrieves an attribute from a markdown node. `get` retrieves a value from a dictionary by key. `get_or` retrieves a value with a default. `entries` returns key-value pairs from a dictionary. ```HareHare MQ attr(markdown, attribute) get(obj, key) get_or(dict, key, default) entries(dict) ``` -------------------------------- ### Extract Substring (String) Source: https://github.com/harehare/mq/blob/main/docs/books/src/reference/builtin_functions.md Extracts a portion of a string given a start and end index. It takes the string, start index, and end index as input. ```javascript function slice(string, start, end) { // Implementation details... } ``` -------------------------------- ### MQ Playground: Run Query with Markdown Input (JavaScript) Source: https://github.com/harehare/mq/blob/main/docs/index.html This JavaScript code snippet demonstrates how to run an MQ query using markdown input in a web playground. It handles user input, sends a POST request to a specified API endpoint, and displays the query results or any errors. Dependencies include standard browser APIs like `fetch` and DOM manipulation. ```javascript const queryInput = document.getElementById("queryInput"); const inputMarkdown = document.getElementById("inputMarkdown"); const output = document.getElementById("output"); const defaultQuery = ".h1 | to_text()"; const defaultMarkdown = `# Example Title This is a paragraph. ## Subtitle Another paragraph here. # Another Example More content.`; queryInput.value = defaultQuery; inputMarkdown.value = defaultMarkdown; let isRunning = false; async function runQuery() { if (isRunning) return; const query = queryInput.value.trim(); const input = inputMarkdown.value.trim(); if (!query || !input) { output.textContent = "Error: Please provide both query and input markdown."; output.className = "demo-output demo-error"; return; } output.textContent = "Running query... Waiting for a response from the Web API."; output.className = "demo-output demo-loading"; isRunning = true; try { const response = await fetch("{{API_URL}}", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ query, input, }), }); if (!response.ok) { const errorText = await response.text(); throw new Error(`HTTP ${response.status}: ${errorText || response.statusText}`); } const result = await response.json(); output.textContent = result.results?.join("\n") || "(empty result)"; output.className = "demo-output"; } catch (error) { output.textContent = `Error: ${error.message}`; output.className = "demo-output demo-error"; } finally { isRunning = false; } } // Auto-resize query input function resizeQueryInput() { queryInput.style.height = "auto"; queryInput.style.height = queryInput.scrollHeight + "px"; } queryInput.addEventListener("input", resizeQueryInput); // Run query on Enter key queryInput.addEventListener("keydown", function (e) { if (e.key === "Enter" && !e.shiftKey && !e.ctrlKey && !e.metaKey) { e.preventDefault(); e.stopPropagation(); runQuery(); } }); inputMarkdown.addEventListener("keydown", function (e) { if (e.key === "Enter" && (e.ctrlKey || e.metaKey)) { e.preventDefault(); e.stopPropagation(); runQuery(); } }); // Initialize query input height resizeQueryInput(); ``` -------------------------------- ### Anonymous Function with Default Parameters Examples in jq Source: https://github.com/harehare/mq/blob/main/docs/books/src/reference/fn.md Provides examples of using anonymous functions with default parameters in jq. It demonstrates how to utilize the default value and how to override it by providing an explicit argument. ```jq # Anonymous function with default parameter let multiply = fn(x, factor=2): x * factor; # Using default value multiply(10) # Multiplies each value by 2 (default factor) # Overriding default value multiply(10, 3) # Multiplies each value by 10 # Using in callbacks [1, 2] | map(fn(x, prefix="Item: "): prefix + to_text(x);) ``` -------------------------------- ### Array Slice Access in MQ Source: https://github.com/harehare/mq/blob/main/docs/books/src/reference/types_and_values.md Illustrates how to extract subarrays using slice notation `arr[start:end]`. The `start` index is inclusive, and the `end` index is exclusive. Out-of-bounds indices are clamped to the valid range. ```mq let arr = [1, 2, 3, 4, 5] arr[1:4] # Returns [2, 3, 4] (elements from index 1 to 3) arr[0:3] # Returns [1, 2, 3] (first three elements) arr[2:5] # Returns [3, 4, 5] (elements from index 2 to end) arr[0:2] # Returns [1, 2] arr[3:10] # Returns [4, 5] (end index clamped to array length) arr[2:2] # Returns [] (empty slice when start equals end) ``` -------------------------------- ### Use mq in GitHub Actions Source: https://github.com/harehare/mq/blob/main/README.md Integrates the mq tool into GitHub Actions workflows using the 'setup-mq' action. This allows running mq commands within CI/CD pipelines. ```yaml steps: - uses: actions/checkout@v5 - uses: harehare/setup-mq@v1 - run: mq '.code' README.md ``` -------------------------------- ### Build mq Project Documentation Source: https://github.com/harehare/mq/blob/main/CONTRIBUTING.md Builds the project documentation for mq using the 'just docs' command. This command generates documentation from doc comments and markdown files. ```bash just docs ``` -------------------------------- ### Run mq TUI Source: https://github.com/harehare/mq/blob/main/docs/books/src/start/tui.md This snippet demonstrates how to launch the mq TUI to query a specific Markdown file. The 'mq tui' command is followed by the path to the Markdown file. ```bash $ mq tui file.md ``` -------------------------------- ### Get Value Type (Utility) Source: https://github.com/harehare/mq/blob/main/docs/books/src/reference/builtin_functions.md Returns the data type of the given value as a string. It takes any value as input. ```javascript function type(value) { // Implementation details... } ``` -------------------------------- ### Abstract Syntax Tree (AST) Operations: Get Args Source: https://github.com/harehare/mq/blob/main/docs/books/src/reference/builtin_functions.md Retrieves the arguments of an Abstract Syntax Tree (AST) node. ```HareHare MQ get_args(node) ``` -------------------------------- ### Check String Starts With Substring (String) Source: https://github.com/harehare/mq/blob/main/docs/books/src/reference/builtin_functions.md Determines if a string begins with a specified substring. It takes the string and the substring to check as input. ```javascript function starts_with(string, substring) { // Implementation details... } ``` -------------------------------- ### Get Markdown Node Name (Markdown) Source: https://github.com/harehare/mq/blob/main/docs/books/src/reference/builtin_functions.md Returns the type or name of a given markdown node. It takes a markdown node object as input. ```javascript function to_md_name(markdown) { // Implementation details... } ``` -------------------------------- ### Substring Index in String (MQ) Source: https://github.com/harehare/mq/blob/main/docs/books/src/reference/builtin_functions.md Finds the starting index of the first occurrence of a substring within a given string. Returns -1 if the substring is not found. ```MQ index(string, substring) ``` -------------------------------- ### Count Nodes by Type Source: https://github.com/harehare/mq/blob/main/docs/books/src/reference/nodes.md This example illustrates how to count the total number of nodes in the document. It applies the 'len()' function to the 'nodes' array. ```mq nodes | len() ``` -------------------------------- ### Create and Use Custom MQ Subcommand (Bash) Source: https://github.com/harehare/mq/blob/main/README.md Demonstrates how to create a custom executable script for an MQ subcommand and make it executable. The script is then invoked using the 'mq' command, showing how arguments are passed. ```bash #!/bin/bash echo "Hello from mq-hello!" echo "Arguments: $@" ``` ```bash chmod +x ~/.mq/bin/mq-hello ``` ```bash mq hello world ``` -------------------------------- ### Get Section Header Level Source: https://github.com/harehare/mq/blob/main/docs/books/src/reference/section_functions.md Determines and returns the header level (an integer from 1 to 6) of a given section. If the input is not a valid section, it returns 0. ```mq import "section" # Get the level of each section | nodes | section::split(2) | map(section::level) ``` -------------------------------- ### Map Over Arrays in MQ Source: https://github.com/harehare/mq/blob/main/docs/books/src/start/example.md Applies a transformation function to each element of an array, returning a new array with the transformed elements. This is a common functional programming pattern. ```mq map([1, 2, 3, 4, 5], fn(x): x + 1;) ``` -------------------------------- ### Run mq Test Suite Source: https://github.com/harehare/mq/blob/main/CONTRIBUTING.md Executes the full test suite for the mq project using the 'just test' command. This should be run before submitting any changes. ```bash just test ``` -------------------------------- ### Anonymous Function Examples in jq Source: https://github.com/harehare/mq/blob/main/docs/books/src/reference/fn.md Illustrates practical uses of anonymous functions in jq, such as mapping values and sorting arrays using inline functions as callbacks. ```jq # Basic Anonymous Function nodes | map(fn(x): add(x, "1");) # Using Anonymous Functions as Callbacks nodes | .[] | sort_by(fn(x): to_text(x);) ``` -------------------------------- ### Build and Test mq Project Source: https://github.com/harehare/mq/blob/main/CONTRIBUTING.md Builds the mq project using Cargo and runs the test suite using the 'just' command runner. Ensures the development environment is set up correctly. ```bash cargo build just test ``` -------------------------------- ### MQ Modules and Imports Source: https://context7.com/harehare/mq/llms.txt Explains how to organize code using modules in MQ. It covers defining modules, using functions with qualified access, importing external module files, and including functions directly into the namespace. Built-in modules can also be included via CLI flags. ```MQ # Define a module module math: def add(a, b): a + b; def sub(a, b): a - b; def mul(a, b): a * b; end # Use module functions with qualified access | math::add(5, 3) # => 8 | math::mul(4, 2) # => 8 # Import external module file (math.mq) import "math" | math::add(10, 5) # => 15 # Include functions directly (no namespace prefix) include "math" | add(2, 3) # => 5 | sub(10, 4) # => 6 # Built-in module includes via CLI flags mq --csv 'csv_parse(true) | csv_to_markdown_table()' data.csv mq --yaml 'yaml_parse() | get("config")' settings.yaml mq --json 'json_parse() | get("users")' data.json ``` -------------------------------- ### Clone mq Repository Source: https://github.com/harehare/mq/blob/main/CONTRIBUTING.md Clones the mq repository from GitHub to your local machine and navigates into the project directory. This is the first step after forking the repository. ```bash git clone https://github.com/YOUR_USERNAME/mq.git cd mq ``` -------------------------------- ### Filter Arrays in MQ Source: https://github.com/harehare/mq/blob/main/docs/books/src/start/example.md Selects elements from an array that satisfy a given condition, returning a new array containing only the matching elements. This is useful for data filtering. ```mq filter([5, 15, 8, 20, 3], fn(x): x > 10;) ``` -------------------------------- ### Attribute Access with MQ Source: https://context7.com/harehare/mq/llms.txt Demonstrates basic attribute access using the MQ tool to extract specific data points from markdown files. It shows how to retrieve URLs, code languages, heading depths, and image alt text. ```bash mq '.link.url' doc.md # Get link URLs mq '.code.lang' doc.md # Get code block languages mq '.h.depth' doc.md # Get heading levels mq 'attr(.image, "alt")' doc.md # Get image alt text ``` -------------------------------- ### Extract Specific List Item in Markdown Source: https://github.com/harehare/mq/blob/main/docs/books/src/start/example.md Selects a specific list item from a Markdown document using its index. This allows for targeted extraction of list elements. ```mq .[1] ``` -------------------------------- ### Select All Headings in Markdown Source: https://github.com/harehare/mq/blob/main/docs/books/src/start/example.md Extracts all heading elements (h1, h2, h3, etc.) from a Markdown document. This is useful for understanding document structure or for further processing of headings. ```mq .h ``` -------------------------------- ### Basic Comparisons in Python Source: https://github.com/harehare/mq/blob/main/docs/books/src/reference/comparisons.md Demonstrates standard comparison operators (equality, inequality, greater than, less than, etc.) and logical operations (AND, OR, NOT) using Python syntax. These comparisons can be used for simple checks or within complex conditional logic. ```python # Basic comparisons 1 == 1 # => true 2 > 1 # => true "a" <= "b" # => true # String comparisons "hello" == "hello" # => true "xyz" > "abc" # => true # Numeric comparisons 5.5 >= 5.0 # => true -1 < 0 # => true # Logical operations and(true, false) # => false or(true, false) # => true not(false) # => true # Complex conditions and(x > 0, x < 10) # => true if 0 < x < 10 ``` -------------------------------- ### Find All Headings Source: https://github.com/harehare/mq/blob/main/docs/books/src/reference/nodes.md This example demonstrates how to filter the 'nodes' array to find all nodes that represent headings. It utilizes the '.h' selector to identify heading nodes. ```mq nodes | select(.h) ``` -------------------------------- ### Safe JSON Parsing with MQ Source: https://context7.com/harehare/mq/llms.txt Demonstrates how to safely parse JSON using MQ, with a fallback for invalid JSON. ```bash mq 'try: json_parse() catch: {"error": "invalid json"}' input.txt ``` -------------------------------- ### Fold (Reduce) Arrays in MQ Source: https://github.com/harehare/mq/blob/main/docs/books/src/start/example.md Combines all elements of an array into a single value by applying a reduction function. It takes an initial accumulator value and iteratively updates it with each element. ```mq fold([1, 2, 3, 4], 0, fn(acc, x): acc + x;) ``` -------------------------------- ### Extract URLs from Documentation with MQ Source: https://context7.com/harehare/mq/llms.txt Demonstrates how to extract all URLs from Markdown files using MQ. ```bash mq '.link.url' docs/**/*.md ``` -------------------------------- ### Exclude Code Blocks from Markdown Source: https://github.com/harehare/mq/blob/main/docs/books/src/start/example.md Filters out all code blocks from a Markdown document, retaining only the prose content. This is helpful for processing text without including code snippets. ```mq select(!.code) ```