### Working with Files Examples Source: https://github.com/ksylvan/markdown-tree-parser/blob/main/README.md Examples demonstrating file reading, parsing, section extraction, and writing. ```APIDOC ## Working with Files ```javascript import fs from 'fs/promises'; // Read and process a file const content = await fs.readFile('README.md', 'utf-8'); const tree = await parser.parse(content); // Extract all sections and save to files const sections = parser.extractAllSections(tree, 2); for (let i = 0; i < sections.length; i++) { const section = sections[i]; const filename = `section-${i + 1}.md`; const markdown = await parser.stringify(section.tree); await fs.writeFile(filename, markdown); } ``` ``` -------------------------------- ### Setup and Development Commands (Bash) Source: https://github.com/ksylvan/markdown-tree-parser/blob/main/README.md Provides essential bash commands for setting up the development environment, running tests, and performing common development tasks for the markdown-tree-parser project. It assumes Node.js and npm are installed. ```bash # Clone the repository git clone https://github.com/ksylvan/markdown-tree-parser.git cd markdown-tree-parser # Install dependencies npm install # Run tests npm test # Run linting npm run lint # Format code npm run format # Test CLI functionality npm run test:cli ``` -------------------------------- ### Search and Manipulation Examples Source: https://github.com/ksylvan/markdown-tree-parser/blob/main/README.md Examples showcasing how to search and manipulate Markdown content using the parser. ```APIDOC ## Search and Manipulation ```javascript // CSS-like selectors const headings = parser.selectAll(tree, 'heading[depth=2]'); const links = parser.selectAll(tree, 'link'); const codeBlocks = parser.selectAll(tree, 'code'); // Custom search const customNode = parser.findNode(tree, (node) => { return node.type === 'heading' && parser.getHeadingText(node).includes('API'); }); // Transform content parser.transform(tree, (node) => { if (node.type === 'heading' && node.depth === 1) { node.depth = 2; // Convert h1 to h2 } }); // Get document statistics const stats = parser.getStats(tree); console.log( `Document has ${stats.wordCount} words and ${stats.headings.total} headings` ); // Generate table of contents const toc = parser.generateTableOfContents(tree, 3); console.log(toc); ``` ``` -------------------------------- ### Install Library Locally Source: https://github.com/ksylvan/markdown-tree-parser/blob/main/README.md Installs the markdown-tree-parser as a local dependency in your project for library usage. This command should be run within your project's root directory. ```bash npm install @kayvan/markdown-tree-parser ``` -------------------------------- ### Install CLI Tool Globally Source: https://github.com/ksylvan/markdown-tree-parser/blob/main/README.md Installs the markdown-tree-parser CLI tool globally on your system, making the 'md-tree' command available for use in your terminal. Supports npm, pnpm, and yarn. ```bash # Using npm npm install -g @kayvan/markdown-tree-parser # Using pnpm (may require approval for build scripts) pnpm install -g @kayvan/markdown-tree-parser pnpm approve-builds -g # If prompted # Using yarn yarn global add @kayvan/markdown-tree-parser ``` -------------------------------- ### Testing Commands (Bash) Source: https://github.com/ksylvan/markdown-tree-parser/blob/main/README.md Lists the bash commands used for running various tests and examples within the markdown-tree-parser project. These commands are typically executed from the project's root directory. ```bash # Run tests npm test # Test CLI npm run test:cli # Run examples npm run example ``` -------------------------------- ### Convenience Functions for Markdown Parsing (JavaScript) Source: https://context7.com/ksylvan/markdown-tree-parser/llms.txt Provides examples of using convenience functions like `createParser`, `extractSection`, `getHeadings`, and `generateTOC` for common markdown processing tasks without explicit parser instantiation. These functions offer a simpler API for specific operations. ```javascript import { createParser, extractSection, getHeadings, generateTOC } from '@kayvan/markdown-tree-parser'; const markdown = ` # Quick Guide ## Setup Installation steps. ## Usage Usage instructions. ## Examples Code examples. `; // Create parser with custom options const customParser = createParser({ bullet: '-', emphasis: '_' }); // Quick section extraction const setupSection = await extractSection(markdown, 'Setup'); console.log(setupSection); // Quick section extraction with options const usageSection = await extractSection(markdown, 'Usage', { bullet: '-' }); console.log(usageSection); // Quick headings extraction const headings = await getHeadings(markdown); console.log(`Found ${headings.length} headings`); headings.forEach(h => { console.log(`${h.level}: ${h.text}`); }); // Quick TOC generation const toc = await generateTOC(markdown, 2); console.log(toc); // Returns null for non-existent sections const notFound = await extractSection(markdown, 'NonExistent'); console.log(notFound); ``` -------------------------------- ### Search and Manipulate Markdown Tree (JavaScript) Source: https://github.com/ksylvan/markdown-tree-parser/blob/main/README.md Demonstrates how to use the parser to select nodes with CSS-like selectors, find specific nodes with custom conditions, transform the AST, get document statistics, and generate a table of contents. It requires the 'markdown-tree-parser' library. ```javascript const headings = parser.selectAll(tree, 'heading[depth=2]'); const links = parser.selectAll(tree, 'link'); const codeBlocks = parser.selectAll(tree, 'code'); const customNode = parser.findNode(tree, (node) => { return node.type === 'heading' && parser.getHeadingText(node).includes('API'); }); parser.transform(tree, (node) => { if (node.type === 'heading' && node.depth === 1) { node.depth = 2; } }); const stats = parser.getStats(tree); console.log( `Document has ${stats.wordCount} words and ${stats.headings.total} headings` ); const toc = parser.generateTableOfContents(tree, 3); console.log(toc); ``` -------------------------------- ### CLI: Get Markdown Document Statistics Source: https://github.com/ksylvan/markdown-tree-parser/blob/main/README.md Calculates and displays various statistics about a markdown document, such as word count, heading counts, and other relevant metrics. ```bash md-tree stats README.md ``` -------------------------------- ### Parse Markdown and Get Headings List Source: https://context7.com/ksylvan/markdown-tree-parser/llms.txt Parses markdown content into an Abstract Syntax Tree (AST) and retrieves a list of all headings found within the document. It can then iterate through these headings to display their levels and text. ```javascript import { MarkdownTreeParser } from '@kayvan/markdown-tree-parser'; const parser = new MarkdownTreeParser(); const markdown = `# Project Guide\n\n## Introduction\n\n## Getting Started\n\n### Installation\n\n### Configuration\n\n## Advanced Topics\n\n### Performance\n\n## Conclusion\n`; const tree = await parser.parse(markdown); // Get all headings const headings = parser.getHeadingsList(tree); console.log(`Total headings: ${headings.length}`); // Display structure headings.forEach(h => { const indent = ' '.repeat(h.level - 1); console.log(`${indent}Level ${h.level}: ${h.text}`); }); // Filter by level const level2Headings = headings.filter(h => h.level === 2); console.log('\nLevel 2 headings:'); level2Headings.forEach(h => console.log(`- ${h.text}`)); ``` -------------------------------- ### Get Document Statistics Source: https://context7.com/ksylvan/markdown-tree-parser/llms.txt Parses markdown content and extracts comprehensive statistics about the document's structure. This includes word count, paragraph count, heading distribution by level, and counts for code blocks, lists, links, and images. ```javascript import { MarkdownTreeParser } from '@kayvan/markdown-tree-parser'; const parser = new MarkdownTreeParser(); const markdown = `# Documentation\n\n## Overview\nThis is a comprehensive guide with detailed information.\n## Features\n- Feature one\n- Feature two\n- Feature three\n### Code Example\n```javascript\nconst example = true;\nconsole.log('Hello world');\n```\n## Links\nCheck [our website](https://example.com) for more info.\nVisit [GitHub](https://github.com) too.\n![Logo](logo.png)\n## Conclusion\nThank you for reading this detailed documentation.\n`; const tree = await parser.parse(markdown); // Get comprehensive statistics const stats = parser.getStats(tree); console.log('Document Statistics:'); console.log(`Word count: ${stats.wordCount}`); console.log(`Paragraphs: ${stats.paragraphs}`); console.log(`Total headings: ${stats.headings.total}`); console.log(`Code blocks: ${stats.codeBlocks}`); console.log(`Lists: ${stats.lists}`); console.log(`Links: ${stats.links}`); console.log(`Images: ${stats.images}`); // Breakdown by heading level console.log('\nHeadings by level:'); for (const [level, count] of Object.entries(stats.headings.byLevel)) { console.log(` Level ${level}: ${count}`); } ``` -------------------------------- ### Creating a New Parser Instance (JavaScript) Source: https://github.com/ksylvan/markdown-tree-parser/blob/main/README.md Demonstrates how to instantiate the MarkdownTreeParser class in JavaScript. It shows the basic constructor usage with optional configuration options. ```javascript new MarkdownTreeParser((options = {})); ``` -------------------------------- ### MarkdownTreeParser Constructor Source: https://context7.com/ksylvan/markdown-tree-parser/llms.txt Initialize a new MarkdownTreeParser instance. You can optionally provide configuration options to customize the output markdown formatting, such as bullet characters, emphasis styles, and strong text styles. ```APIDOC ## MarkdownTreeParser Constructor ### Description Initialize a new parser instance with optional configuration for markdown output formatting. ### Method `constructor([options])` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body **options** (object) - Optional - Configuration object for markdown output. - **bullet** (string) - Optional - Character to use for list bullets (e.g., '-', '*'). Defaults to '*'. - **emphasis** (string) - Optional - Character to use for emphasis (e.g., '_', '*'). Defaults to '*'. - **strong** (string) - Optional - Character to use for strong text (e.g., '__', '**'). Defaults to '**'. ### Request Example ```javascript import { MarkdownTreeParser } from '@kayvan/markdown-tree-parser'; // Basic parser with default options const parser = new MarkdownTreeParser(); // Custom parser with formatting options const customParser = new MarkdownTreeParser({ bullet: '-', // Use '-' for list items instead of '*' emphasis: '_', // Use '_' for italic text strong: '__' // Use '__' for bold text }); ``` ### Response #### Success Response (200) Returns an instance of MarkdownTreeParser. #### Response Example ```json { "instance": "MarkdownTreeParser" } ``` ``` -------------------------------- ### CLI: Show Help Information Source: https://github.com/ksylvan/markdown-tree-parser/blob/main/README.md Displays the help message for the markdown-tree-parser CLI tool, listing all available commands and options. ```bash md-tree help ``` -------------------------------- ### CSS-Like Selectors Source: https://github.com/ksylvan/markdown-tree-parser/blob/main/README.md Demonstrates the usage of CSS-like selectors for querying the Markdown AST. ```APIDOC ## CSS-Like Selectors The library supports powerful CSS-like selectors for searching: ```javascript // Element selectors parser.selectAll(tree, 'heading'); // All headings parser.selectAll(tree, 'paragraph'); // All paragraphs parser.selectAll(tree, 'link'); // All links // Attribute selectors parser.selectAll(tree, 'heading[depth=1]'); // H1 headings parser.selectAll(tree, 'heading[depth=2]'); // H2 headings parser.selectAll(tree, 'link[url*="github"]'); // Links containing "github" // Pseudo selectors parser.selectAll(tree, ':first-child'); // First child elements parser.selectAll(tree, ':last-child'); // Last child elements ``` ``` -------------------------------- ### CLI: List Markdown Headings (Bash) Source: https://context7.com/ksylvan/markdown-tree-parser/llms.txt Shows how to use the `md-tree list` command to display headings from a markdown file. Supports plain text output for hierarchical viewing and JSON format for machine readability. ```bash # List headings in text format md-tree list README.md # List headings in JSON format md-tree list README.md --format json ``` -------------------------------- ### CLI: Show Markdown Document Structure (Bash) Source: https://context7.com/ksylvan/markdown-tree-parser/llms.txt Illustrates the `md-tree tree` command, which visualizes the hierarchical structure of a markdown document as a tree, providing an overview of the document's organization. ```bash # Show document tree md-tree tree README.md ``` -------------------------------- ### Initialize MarkdownTreeParser in JavaScript Source: https://context7.com/ksylvan/markdown-tree-parser/llms.txt Initializes a new MarkdownTreeParser instance. Allows for custom formatting options for list bullets, emphasis, and strong text during markdown stringification. The parser instance is then ready to parse markdown strings. ```javascript import { MarkdownTreeParser } from '@kayvan/markdown-tree-parser'; // Basic parser with default options const parser = new MarkdownTreeParser(); // Custom parser with formatting options const customParser = new MarkdownTreeParser({ bullet: '-', // Use '-' for list items instead of '*' emphasis: '_', // Use '_' for italic text strong: '__' // Use '__' for bold text }); // The parser is now ready to parse markdown const markdown = '# Hello World\n\nThis is a test.'; const tree = await parser.parse(markdown); ``` -------------------------------- ### Transform AST with Visitor Pattern Source: https://context7.com/ksylvan/markdown-tree-parser/llms.txt Applies custom transformations to the markdown Abstract Syntax Tree (AST) using a visitor function. This allows for targeted modification or analysis of specific nodes within the tree. ```javascript import { MarkdownTreeParser } from '@kayvan/markdown-tree-parser'; const parser = new MarkdownTreeParser(); const markdown = `# Main Title\n\n## Section One\nContent here.\n\n### Subsection\nMore content.\n`; const tree = await parser.parse(markdown); // Example visitor function (not fully implemented in snippet) const visitor = { heading: (node) => { console.log(`Visiting heading: ${node.text}`); // Modify node or perform actions } }; // Apply the visitor to the tree (actual implementation depends on parser) // parser.transform(tree, visitor); ``` -------------------------------- ### Convert Emphasis to Strong with JavaScript Source: https://context7.com/ksylvan/markdown-tree-parser/llms.txt Shows how to parse markdown, specifically targeting 'emphasis' nodes and transforming them into 'strong' nodes. This is useful for changing text formatting programmatically. ```javascript const emphasisMarkdown = 'This is *important* and *critical*.'; const emphasisTree = await parser.parse(emphasisMarkdown); parser.transform(emphasisTree, (node) => { if (node.type === 'emphasis') { node.type = 'strong'; } }); const strongResult = await parser.stringify(emphasisTree); console.log(strongResult); ``` -------------------------------- ### CLI: Display Markdown Document Structure Source: https://github.com/ksylvan/markdown-tree-parser/blob/main/README.md Generates and displays a tree-like structure representing the headings and organization of a markdown document. Useful for understanding the document's hierarchy. ```bash md-tree tree README.md ``` -------------------------------- ### Working with Markdown Files (JavaScript) Source: https://github.com/ksylvan/markdown-tree-parser/blob/main/README.md Illustrates reading a Markdown file, parsing its content into an AST, extracting all sections based on heading levels, and writing each section to a separate file. This snippet depends on Node.js's 'fs/promises' module and the 'markdown-tree-parser' library. ```javascript import fs from 'fs/promises'; const content = await fs.readFile('README.md', 'utf-8'); const tree = await parser.parse(content); const sections = parser.extractAllSections(tree, 2); for (let i = 0; i < sections.length; i++) { const section = sections[i]; const filename = `section-${i + 1}.md`; const markdown = await parser.stringify(section.tree); await fs.writeFile(filename, markdown); } ``` -------------------------------- ### Convenience Function for TOC Generation (JavaScript) Source: https://github.com/ksylvan/markdown-tree-parser/blob/main/README.md Illustrates the usage of a convenience function for generating a table of contents directly from a Markdown string. This function abstracts away the need to manually parse and stringify the AST. ```javascript generateTOC(markdown, maxLevel, options); ``` -------------------------------- ### Convenience Functions API Source: https://github.com/ksylvan/markdown-tree-parser/blob/main/README.md Provides standalone functions for common Markdown processing tasks. ```APIDOC ## Convenience Functions API - `createParser(options)` - Create new parser instance - `extractSection(markdown, sectionName, options)` - Quick section extraction - `getHeadings(markdown, options)` - Quick heading extraction - `generateTOC(markdown, maxLevel, options)` - Quick TOC generation ``` -------------------------------- ### stringify() - Convert AST to Markdown Source: https://context7.com/ksylvan/markdown-tree-parser/llms.txt Convert an Abstract Syntax Tree (AST) back into its markdown text representation. This is useful after programmatically modifying the AST. ```APIDOC ## stringify() ### Description Convert an Abstract Syntax Tree back into markdown text format. ### Method `stringify(astNode, [options])` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body **astNode** (object) - Required - The AST node or tree to stringify. **options** (object) - Optional - Configuration options for stringifying. These options are merged with the parser's initial configuration. - **bullet** (string) - Character to use for list bullets. - **emphasis** (string) - Character to use for emphasis. - **strong** (string) - Character to use for strong text. ### Request Example ```javascript import { MarkdownTreeParser } from '@kayvan/markdown-tree-parser'; const parser = new MarkdownTreeParser(); const markdown = '# Title\n\nContent here.'; const tree = await parser.parse(markdown); // Make modifications to the tree (example: we'll just use it as-is) const result = await parser.stringify(tree); console.log(result); // Output: // # Title // // Content here. // With custom formatting const customParser = new MarkdownTreeParser({ bullet: '-', emphasis: '_' }); const listMarkdown = '* Item 1\n* Item 2\n\nText with *emphasis*.'; const listTree = await customParser.parse(listMarkdown); const customResult = await customParser.stringify(listTree); console.log(customResult); // Output uses custom formatting: // - Item 1 // - Item 2 // // Text with _emphasis_. ``` ### Response #### Success Response (200) - **markdownString** (string) - The markdown text generated from the AST. #### Response Example ```markdown # Title Content here. ``` ``` -------------------------------- ### Split Markdown Document into Sections Source: https://context7.com/ksylvan/markdown-tree-parser/llms.txt Splits a markdown document into separate files based on level-2 heading sections, creating an index file. Requires the input markdown file path and an output directory path. ```bash # Explode document into directory md-tree explode README.md ./exploded ``` -------------------------------- ### CLI: List Markdown Headings Source: https://github.com/ksylvan/markdown-tree-parser/blob/main/README.md Lists all headings found in a specified markdown file. Can output the results in JSON format for easier programmatic processing. ```bash md-tree list README.md md-tree list README.md --format json ``` -------------------------------- ### Reassemble Markdown Document from Sections Source: https://context7.com/ksylvan/markdown-tree-parser/llms.txt Reassembles a markdown document from a directory of split files, using an index.md file. Requires the directory path containing the split files and the output markdown file path. ```bash # Assemble document from directory md-tree assemble ./exploded reassembled.md ``` -------------------------------- ### Verify Markdown Document Links Source: https://context7.com/ksylvan/markdown-tree-parser/llms.txt Checks the reachability of all links within a markdown document. Supports recursive checking for linked markdown files and skipping non-HTTP/HTTPS links. Requires the markdown file path and an optional --recursive flag. ```bash # Check links in a single file md-tree check-links README.md # Recursively check links in linked markdown files md-tree check-links README.md --recursive # Short form md-tree check-links README.md -r ``` -------------------------------- ### CLI: Extract All Sections at a Level Source: https://github.com/ksylvan/markdown-tree-parser/blob/main/README.md Extracts all sections that are at a specified heading level from a markdown file. Each extracted section can optionally be saved to a separate file. ```bash # Extract all level-2 sections md-tree extract-all README.md 2 # Extract to separate files md-tree extract-all README.md 2 --output ./sections ``` -------------------------------- ### Transform Markdown Headings with JavaScript Source: https://context7.com/ksylvan/markdown-tree-parser/llms.txt Demonstrates how to parse markdown, transform heading levels (h1 to h2, h2 to h3), and stringify the result using the markdown-tree-parser library. This allows for programmatic modification of markdown document structure. ```javascript const markdown = ` # Main Title ## Section One Content here. #### Subsection More content. ## Section Two Final content. `; const tree = await parser.parse(markdown); // Transform all h1 to h2 parser.transform(tree, (node) => { if (node.type === 'heading' && node.depth === 1) { node.depth = 2; } }); // Transform all h2 to h3 parser.transform(tree, (node) => { if (node.type === 'heading' && node.depth === 2) { node.depth = 3; } }); const transformed = await parser.stringify(tree); console.log(transformed); ``` -------------------------------- ### Convert AST to Markdown in JavaScript Source: https://context7.com/ksylvan/markdown-tree-parser/llms.txt Converts an Abstract Syntax Tree (AST) back into a markdown text format. Supports custom formatting options defined during parser initialization for elements like list bullets and emphasis. If no modifications are made to the tree, the output will be identical to the input markdown. ```javascript import { MarkdownTreeParser } from '@kayvan/markdown-tree-parser'; const parser = new MarkdownTreeParser(); const markdown = '# Title\n\nContent here.'; const tree = await parser.parse(markdown); // Make modifications to the tree (example: we'll just use it as-is) const result = await parser.stringify(tree); console.log(result); // Output: // # Title // // Content here. // With custom formatting const customParser = new MarkdownTreeParser({ bullet: '-', emphasis: '_' }); const listMarkdown = '* Item 1\n* Item 2\n\nText with *emphasis*.'; const listTree = await customParser.parse(listMarkdown); const customResult = await customParser.stringify(listTree); console.log(customResult); // Output uses custom formatting: // - Item 1 // - Item 2 // // Text with _emphasis_. ``` -------------------------------- ### Library: Advanced Parsing and Section Handling Source: https://github.com/ksylvan/markdown-tree-parser/blob/main/README.md Showcases advanced features of the library, including creating a parser with custom options, extracting all sections at a specific level, and using convenience functions like 'extractSection'. ```javascript import { MarkdownTreeParser, createParser, extractSection, } from 'markdown-tree-parser'; // Create parser with custom options const parser = createParser({ bullet: '-', // Use '-' for lists emphasis: '_', // Use '_' for emphasis strong: '__', // Use '__' for strong }); // Extract all sections at level 2 const tree = await parser.parse(markdown); const sections = parser.extractAllSections(tree, 2); sections.forEach(async (section, index) => { const heading = parser.getHeadingText(section.heading); const content = await parser.stringify(section.tree); console.log(`Section ${index + 1}: ${heading}`); console.log(content); }); // Use convenience functions const sectionMarkdown = await extractSection(markdown, 'Installation'); ``` -------------------------------- ### Search AST Nodes with CSS-like Selectors (JavaScript) Source: https://context7.com/ksylvan/markdown-tree-parser/llms.txt Searches for nodes within the markdown Abstract Syntax Tree (AST) using CSS-like selector syntax. The `selectAll` method returns all matching nodes, while `select` returns the first match. This enables targeted retrieval of elements like headings, links, or code blocks based on their type and attributes. It requires the markdown-tree-parser library. ```javascript import { MarkdownTreeParser } from '@kayvan/markdown-tree-parser'; const parser = new MarkdownTreeParser(); const markdown = ` # Title ## Introduction Learn about [markdown](https://example.com). ### Details More information here. ## Examples Code examples: ```javascript console.log('Hello'); ``` Check [this link](https://github.com) for more. `; const tree = await parser.parse(markdown); // Find all level-2 headings const h2Headings = parser.selectAll(tree, 'heading[depth=2]'); console.log(`Found ${h2Headings.length} h2 headings`); h2Headings.forEach(h => { console.log(`- ${parser.getHeadingText(h)}`); }); // Output: // Found 2 h2 headings // - Introduction // - Examples // Find all links const links = parser.selectAll(tree, 'link'); links.forEach(link => { console.log(`Link: ${link.url}`); }); // Output: // Link: https://example.com // Link: https://github.com // Find all code blocks const codeBlocks = parser.selectAll(tree, 'code'); console.log(`Found ${codeBlocks.length} code blocks`); console.log(`Language: ${codeBlocks[0].lang}`); console.log(`Code: ${codeBlocks[0].value}`); // Output: // Found 1 code blocks // Language: javascript // Code: console.log('Hello'); // Find first matching node const firstH2 = parser.select(tree, 'heading[depth=2]'); console.log(parser.getHeadingText(firstH2)); // Introduction // Find paragraphs const paragraphs = parser.selectAll(tree, 'paragraph'); console.log(`Found ${paragraphs.length} paragraphs`); ``` -------------------------------- ### parse() - Parse Markdown to AST Source: https://context7.com/ksylvan/markdown-tree-parser/llms.txt Convert markdown text into an Abstract Syntax Tree (AST) representation, allowing for programmatic manipulation and analysis of the markdown content. ```APIDOC ## parse() ### Description Convert markdown text into an Abstract Syntax Tree for programmatic manipulation. ### Method `parse(markdownString)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body **markdownString** (string) - Required - The markdown text to parse. ### Request Example ```javascript import { MarkdownTreeParser } from '@kayvan/markdown-tree-parser'; const parser = new MarkdownTreeParser(); const markdown = ` # Project Documentation ## Getting Started This section covers installation and setup. ### Requirements - Node.js 18+ - npm or yarn ## API Reference Complete API documentation. `; // Parse the markdown into an AST const tree = await parser.parse(markdown); // The tree is now a structured object you can manipulate console.log(tree.type); // 'root' console.log(tree.children.length); // Number of top-level nodes ``` ### Response #### Success Response (200) - **tree** (object) - The Abstract Syntax Tree representation of the markdown. #### Response Example ```json { "type": "root", "children": [ { "type": "heading", "depth": 1, "children": [ { "type": "text", "value": "Project Documentation" } ] } // ... other nodes ] } ``` ``` -------------------------------- ### Generate Markdown Document Statistics Source: https://context7.com/ksylvan/markdown-tree-parser/llms.txt Provides comprehensive statistics for a given markdown document. Outputs metrics such as word count, paragraph count, heading distribution, code blocks, lists, links, and images. Requires the markdown file path. ```bash # Show statistics md-tree stats README.md ``` -------------------------------- ### CLI: Search Markdown with CSS Selectors Source: https://github.com/ksylvan/markdown-tree-parser/blob/main/README.md Searches within a markdown file using CSS-like selectors to find specific elements, such as headings of a certain depth or all links. This allows for precise content retrieval. ```bash # Find all level-2 headings md-tree search README.md "heading[depth=2]" # Find all links md-tree search README.md "link" ``` -------------------------------- ### CLI: Extract All Markdown Sections (Bash) Source: https://context7.com/ksylvan/markdown-tree-parser/llms.txt Explains the usage of `md-tree extract-all` to split a markdown file into multiple files, one for each section at a specified heading level. Sections can be output to stdout or individual files. ```bash # Extract all level-2 sections to stdout md-tree extract-all README.md 2 # Extract to separate files md-tree extract-all README.md 2 --output ./sections # Extract level-3 sections md-tree extract-all README.md 3 --output ./subsections ``` -------------------------------- ### Library: Basic Markdown Parsing and Extraction Source: https://github.com/ksylvan/markdown-tree-parser/blob/main/README.md Demonstrates basic usage of the MarkdownTreeParser library in JavaScript. Parses markdown content into an AST, extracts a specific section by heading, and stringifies the extracted section back into markdown. ```javascript import { MarkdownTreeParser } from 'markdown-tree-parser'; const parser = new MarkdownTreeParser(); // Parse markdown into AST const markdown = ` # My Document Some content here. ## Section 1 Content for section 1. ## Section 2 Content for section 2. `; const tree = await parser.parse(markdown); // Extract a specific section const section = parser.extractSection(tree, 'Section 1'); const sectionMarkdown = await parser.stringify(section); console.log(sectionMarkdown); // Output: // ## Section 1 // Content for section 1. ``` -------------------------------- ### Search Markdown Nodes with Selectors Source: https://context7.com/ksylvan/markdown-tree-parser/llms.txt Searches for nodes within a markdown file using CSS-like selectors. Supports outputting results in JSON format. Requires the markdown file path and a selector string as input. ```bash # Find all level-2 headings md-tree search README.md "heading[depth=2]" # Find all links md-tree search README.md "link" # Find all code blocks md-tree search README.md "code" # Output in JSON format md-tree search README.md "link" --format json ``` -------------------------------- ### CLI: Generate Table of Contents Source: https://github.com/ksylvan/markdown-tree-parser/blob/main/README.md Generates a table of contents for a markdown document, with options to control the maximum heading level included in the TOC. ```bash md-tree toc README.md --max-level 3 ``` -------------------------------- ### MarkdownTreeParser API Reference Source: https://github.com/ksylvan/markdown-tree-parser/blob/main/README.md Details the methods available on the MarkdownTreeParser class for processing Markdown. ```APIDOC ## MarkdownTreeParser API Reference ### Constructor ```javascript new MarkdownTreeParser((options = {})); ``` ### Methods - `parse(markdown)` - Parse markdown into AST - `stringify(tree)` - Convert AST back to markdown - `extractSection(tree, headingText, level?)` - Extract specific section - `extractAllSections(tree, level)` - Extract all sections at level - `select(tree, selector)` - Find first node matching CSS selector - `selectAll(tree, selector)` - Find all nodes matching CSS selector - `findNode(tree, condition)` - Find node with custom condition - `getHeadingText(headingNode)` - Get text content of heading - `getHeadingsList(tree)` - Get all headings with metadata - `getStats(tree)` - Get document statistics - `generateTableOfContents(tree, maxLevel)` - Generate TOC - `transform(tree, visitor)` - Transform tree with visitor function ``` -------------------------------- ### CLI: Check Markdown Links Source: https://github.com/ksylvan/markdown-tree-parser/blob/main/README.md Checks the validity of links within a markdown document. Can perform a recursive check to follow links and ensure they are accessible. ```bash md-tree check-links README.md md-tree check-links README.md --recursive ``` -------------------------------- ### Parse Markdown to AST in JavaScript Source: https://context7.com/ksylvan/markdown-tree-parser/llms.txt Converts a markdown string into an Abstract Syntax Tree (AST) using the MarkdownTreeParser. The resulting tree object can be programmatically manipulated, providing access to the document's structure via its 'type' and 'children' properties. ```javascript import { MarkdownTreeParser } from '@kayvan/markdown-tree-parser'; const parser = new MarkdownTreeParser(); const markdown = ` # Project Documentation ## Getting Started This section covers installation and setup. ### Requirements - Node.js 18+ - npm or yarn ## API Reference Complete API documentation. `; // Parse the markdown into an AST const tree = await parser.parse(markdown); // The tree is now a structured object you can manipulate console.log(tree.type); // 'root' console.log(tree.children.length); // Number of top-level nodes ``` -------------------------------- ### Markdown Tree Parser Selectors (JavaScript) Source: https://github.com/ksylvan/markdown-tree-parser/blob/main/README.md Showcases the use of CSS-like selectors with the markdown-tree-parser library to find specific nodes within a Markdown AST. It covers element selectors, attribute selectors, and pseudo-selectors for targeted node retrieval. ```javascript // Element selectors parser.selectAll(tree, 'heading'); // All headings parser.selectAll(tree, 'paragraph'); // All paragraphs parser.selectAll(tree, 'link'); // All links // Attribute selectors parser.selectAll(tree, 'heading[depth=1]'); // H1 headings parser.selectAll(tree, 'heading[depth=2]'); // H2 headings parser.selectAll(tree, 'link[url*="github"]'); // Links containing "github" // Pseudo selectors parser.selectAll(tree, ':first-child'); // First child elements parser.selectAll(tree, ':last-child'); // Last child elements ``` -------------------------------- ### Extract Flat List of Headings (JavaScript) Source: https://context7.com/ksylvan/markdown-tree-parser/llms.txt Retrieves a flat list of all headings present in the markdown AST. Each item in the list includes the heading's level and its text content. This method is useful for generating a table of contents or indexing document structure. It requires the markdown-tree-parser library. ```javascript import { MarkdownTreeParser } from '@kayvan/markdown-tree-parser'; const parser = new MarkdownTreeParser(); const markdown = ` # Project Guide ## Introduction Welcome to the project. ## Getting Started ### Installation Install the package. ### Configuration Configure settings. ## Advanced Topics ### Performance Optimization tips. `; const tree = await parser.parse(markdown); const headings = parser.getHeadingsList(tree); headings.forEach(h => { console.log(`- ${h.text} (Level ${h.level})`); }); // Output: // - Project Guide (Level 1) // - Introduction (Level 2) // - Getting Started (Level 2) // - Installation (Level 3) // - Configuration (Level 3) // - Advanced Topics (Level 2) // - Performance (Level 3) ``` -------------------------------- ### CLI: Extract Specific Markdown Section (Bash) Source: https://context7.com/ksylvan/markdown-tree-parser/llms.txt Demonstrates the `md-tree extract` command for isolating and outputting a specific section from a markdown file. It can output to standard output or a specified file, and allows filtering by heading level. ```bash # Extract to stdout md-tree extract README.md "Installation" # Extract to file md-tree extract README.md "Installation" --output ./sections # Extract specific level md-tree extract README.md "API" --level 2 ``` -------------------------------- ### CLI: Extract Specific Markdown Section Source: https://github.com/ksylvan/markdown-tree-parser/blob/main/README.md Extracts a specific section from a markdown file based on its heading. The extracted section can be saved to a file using the --output flag. ```bash # Extract one section md-tree extract README.md "Installation" # Extract to a file md-tree extract README.md "Installation" --output ./sections ``` -------------------------------- ### Extract Heading Text with JavaScript Source: https://context7.com/ksylvan/markdown-tree-parser/llms.txt Demonstrates using the `getHeadingText` function to extract the plain text content from a markdown heading node. This is useful for analyzing or processing heading information independently of its markdown formatting. ```javascript import { MarkdownTreeParser } from '@kayvan/markdown-tree-parser'; const parser = new MarkdownTreeParser(); const markdown = ` # Simple Heading ## Heading with **bold** and *italic* ### Heading with [link](https://example.com) `; const tree = await parser.parse(markdown); const headings = parser.selectAll(tree, 'heading'); headings.forEach(heading => { const text = parser.getHeadingText(heading); const level = heading.depth; console.log(`Level ${level}: "${text}"`); }); ``` -------------------------------- ### Find Nodes with Custom Search Conditions (JavaScript) Source: https://context7.com/ksylvan/markdown-tree-parser/llms.txt Finds markdown AST nodes using custom search functions or object matching. The `findNode` method iterates through the tree, applying a provided condition (a function or an object) to each node to find a match. This allows for flexible searching based on node type, text content, depth, or any other node property. It requires the markdown-tree-parser library. ```javascript import { MarkdownTreeParser } from '@kayvan/markdown-tree-parser'; const parser = new MarkdownTreeParser(); const markdown = ` # API Documentation ## Authentication Learn about API authentication. ## Endpoints ### GET /users Retrieve user list. ### POST /users Create a new user. ## Rate Limiting Understand rate limits. `; const tree = await parser.parse(markdown); // Find node with custom function const apiHeading = parser.findNode(tree, (node) => { return node.type === 'heading' && parser.getHeadingText(node).includes('API'); }); if (apiHeading) { console.log(`Found: ${parser.getHeadingText(apiHeading)}`); console.log(`Level: ${apiHeading.depth}`); } // Output: // Found: API Documentation // Level: 1 // Find heading with "POST" in text const postHeading = parser.findNode(tree, (node) => { return node.type === 'heading' && parser.getHeadingText(node).includes('POST'); }); console.log(parser.getHeadingText(postHeading)); // POST /users // Find by node type string const firstCode = parser.findNode(tree, 'code'); console.log(firstCode); // null (no code blocks in this example) // Find by object match const heading3 = parser.findNode(tree, { type: 'heading', depth: 3 }); console.log(parser.getHeadingText(heading3)); // GET /users ``` -------------------------------- ### Generate Table of Contents Source: https://context7.com/ksylvan/markdown-tree-parser/llms.txt Generates a markdown-formatted table of contents from a parsed markdown AST. The depth of the TOC can be controlled by specifying a maximum heading level. ```javascript import { MarkdownTreeParser } from '@kayvan/markdown-tree-parser'; const parser = new MarkdownTreeParser(); const markdown = `# User Guide\n\n## Installation\n\n### Requirements\nSystem requirements.\n\n### Download\nGet the software.\n\n### Setup\nInitial configuration.\n\n## Usage\n\n### Basic Operations\nCommon tasks.\n\n### Advanced Features\nPower user features.\n\n## Troubleshooting\n\n### Common Issues\nFrequent problems.\n\n### FAQ\nFrequently asked questions.\n`; const tree = await parser.parse(markdown); // Generate TOC with max level 3 const toc = parser.generateTableOfContents(tree, 3); console.log(toc); // Generate shallow TOC (max level 2) const shallowToc = parser.generateTableOfContents(tree, 2); console.log(shallowToc); // Empty string if no headings const emptyMarkdown = 'Just text, no headings.'; const emptyTree = await parser.parse(emptyMarkdown); const emptyToc = parser.generateTableOfContents(emptyTree, 3); console.log(emptyToc); // '' ``` -------------------------------- ### Extract All Sections by Level (JavaScript) Source: https://context7.com/ksylvan/markdown-tree-parser/llms.txt Extracts all markdown sections at a specified heading level from a parsed markdown tree. It returns each section as a separate tree structure. This function is useful for processing or saving individual sections of a document. It requires the markdown-tree-parser library and optionally fs for file operations. ```javascript import { MarkdownTreeParser } from '@kayvan/markdown-tree-parser'; import fs from 'fs/promises'; const parser = new MarkdownTreeParser(); const markdown = ` # Main Title ## Features Feature list here. ### Performance Fast and efficient. ### Reliability Rock solid. ## Installation Installation instructions. ## Usage Usage examples. ### Basic Usage Simple examples. ### Advanced Usage Complex examples. `; const tree = await parser.parse(markdown); // Extract all level-2 sections const sections = parser.extractAllSections(tree, 2); console.log(`Found ${sections.length} sections`); // Output: Found 3 sections // Iterate through sections for (const section of sections) { console.log(`Section: ${section.headingText}`); const markdown = await parser.stringify(section.tree); console.log(markdown); console.log('---\n'); } // Output: // Section: Features // ## Features // Feature list here. // ... // Section: Installation // ## Installation // ... // Section: Usage // ## Usage // ... // Save each section to a file for (let i = 0; i < sections.length; i++) { const section = sections[i]; const filename = `section-${i + 1}.md`; const content = await parser.stringify(section.tree); await fs.writeFile(filename, content); } ``` -------------------------------- ### extractSection() - Extract Specific Section Source: https://context7.com/ksylvan/markdown-tree-parser/llms.txt Extract a specific section from a markdown AST based on its heading text. This function includes the heading itself and all subsequent content until the next heading of the same level or higher. ```APIDOC ## extractSection() ### Description Extract a specific section by heading text, including all content until the next same-level heading. ### Method `extractSection(astNode, headingText, [level])` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body **astNode** (object) - Required - The root AST node of the markdown document. **headingText** (string) - Required - The exact text of the heading to extract. **level** (number) - Optional - The specific heading level (e.g., 1 for '#', 2 for '##') to match. If not provided, matches any level. ### Request Example ```javascript import { MarkdownTreeParser } from '@kayvan/markdown-tree-parser'; const parser = new MarkdownTreeParser(); const markdown = ` # Documentation ## Installation Run npm install to get started. ### Linux Installation Special steps for Linux. ### Windows Installation Special steps for Windows. ## Configuration Configure the application. ## Usage How to use the tool. `; const tree = await parser.parse(markdown); // Extract the Installation section (includes all subsections) const installSection = parser.extractSection(tree, 'Installation'); const installMarkdown = await parser.stringify(installSection); console.log(installMarkdown); // Output: // ## Installation // Run npm install to get started. // // ### Linux Installation // Special steps for Linux. // // ### Windows Installation // Special steps for Windows. // Extract a specific level heading const configSection = parser.extractSection(tree, 'Configuration', 2); const configMarkdown = await parser.stringify(configSection); console.log(configMarkdown); // Output: // ## Configuration // Configure the application. // Returns null if section not found const notFound = parser.extractSection(tree, 'NonExistent'); console.log(notFound); // null ``` ### Response #### Success Response (200) - **sectionAst** (object | null) - The AST node representing the extracted section, or null if the section was not found. #### Response Example ```json { "type": "element", "tagName": "h2", "properties": {}, "children": [ { "type": "text", "value": "Installation" } ], "position": { ... } } ``` ``` -------------------------------- ### Extract Specific Section from Markdown AST in JavaScript Source: https://context7.com/ksylvan/markdown-tree-parser/llms.txt Extracts a specific section from a markdown AST based on its heading text. It includes all content within that section, including subsections, until the next heading of the same level. The function can also optionally target a specific heading level. Returns null if the specified section is not found. ```javascript import { MarkdownTreeParser } from '@kayvan/markdown-tree-parser'; const parser = new MarkdownTreeParser(); const markdown = ` # Documentation ## Installation Run npm install to get started. ### Linux Installation Special steps for Linux. ### Windows Installation Special steps for Windows. ## Configuration Configure the application. ## Usage How to use the tool. `; const tree = await parser.parse(markdown); // Extract the Installation section (includes all subsections) const installSection = parser.extractSection(tree, 'Installation'); const installMarkdown = await parser.stringify(installSection); console.log(installMarkdown); // Output: // ## Installation // Run npm install to get started. // // ### Linux Installation // Special steps for Linux. // // ### Windows Installation // Special steps for Windows. // Extract a specific level heading const configSection = parser.extractSection(tree, 'Configuration', 2); const configMarkdown = await parser.stringify(configSection); console.log(configMarkdown); // Output: // ## Configuration // Configure the application. // Returns null if section not found const notFound = parser.extractSection(tree, 'NonExistent'); console.log(notFound); // null ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.