### Astro File Example Source: https://github.com/withastro/prettier-plugin-astro/blob/main/_autodocs/configuration.md An example Astro file demonstrating frontmatter and template markup. ```astro --- const message="Hello" const items=["a","b","c"] ---

{message}

``` -------------------------------- ### Install Prettier and Astro Plugin with npm Source: https://github.com/withastro/prettier-plugin-astro/blob/main/README.md Install Prettier and the prettier-plugin-astro using npm. This is a common starting point for setting up code formatting. ```shell npm i --save-dev prettier prettier-plugin-astro ``` -------------------------------- ### Quick Start: Formatting Astro Code Source: https://github.com/withastro/prettier-plugin-astro/blob/main/_autodocs/api-summary.md Demonstrates how to use the plugin to format Astro code with Prettier. Ensure Prettier and the plugin are installed. ```typescript import astroPlugin from 'prettier-plugin-astro'; const formatted = await prettier.format(code, { parser: 'astro', plugins: [astroPlugin], }); ``` -------------------------------- ### Prettier Configuration Example with Astro Options Source: https://github.com/withastro/prettier-plugin-astro/blob/main/README.md Example of a .prettierrc.cjs file demonstrating how to set Astro-specific formatting options. This includes disabling shorthand attributes and skipping frontmatter formatting. ```javascript { astroAllowShorthand: false; astroSkipFrontmatter: false; } ``` -------------------------------- ### Configuration Example: astroAllowShorthand Source: https://github.com/withastro/prettier-plugin-astro/blob/main/_autodocs/api-summary.md Illustrates the effect of the `astroAllowShorthand` option. Set to `true` to enable attribute shorthand syntax. ```astro // With astroAllowShorthand: false (default) // With astroAllowShorthand: true ``` -------------------------------- ### Install Prettier and Astro Plugin with pnpm Source: https://github.com/withastro/prettier-plugin-astro/blob/main/README.md Install Prettier and the prettier-plugin-astro using pnpm. This snippet is an alternative installation method for different package managers. ```shell pnpm add --save-dev prettier prettier-plugin-astro ``` -------------------------------- ### Example 1: Element Node Keys Source: https://github.com/withastro/prettier-plugin-astro/blob/main/_autodocs/api-reference/get-visitor-keys.md Demonstrates the output of getVisitorKeys for an 'element' AST node, showing which properties are identified as visitable. ```typescript // Input node: HTML element const elementNode = { type: 'element', name: 'div', attributes: [...], // array of attribute objects children: [...], // array of child nodes position: {...}, // position metadata - EXCLUDED selfClosing: false, }; const keys = getVisitorKeys(elementNode); // Returns: ['attributes', 'children'] // 'position' and 'type' are excluded // 'name' and 'selfClosing' are primitives so excluded ``` -------------------------------- ### Biome Configuration for Formatting and Linting Source: https://github.com/withastro/prettier-plugin-astro/blob/main/_autodocs/configuration.md Example Biome configuration file (biome.json) to enable formatting and linting. ```json // biome.json { "format": { "enabled": true }, "linter": { "enabled": true } } ``` -------------------------------- ### AST Generation from Astro Source Source: https://github.com/withastro/prettier-plugin-astro/blob/main/_autodocs/architecture.md Illustrates how @astrojs/compiler transforms Astro source code into a structured AST, showing a component example. ```text Source: '' ↓ @astrojs/compiler.parse() ↓ AST Structure: { type: 'root', children: [{ type: 'component', name: 'Component', attributes: [{ type: 'attribute', kind: 'shorthand', name: 'name' }], children: [] }] ``` -------------------------------- ### Static HTML as an Astro Component Source: https://github.com/withastro/prettier-plugin-astro/blob/main/test/fixtures/markdown/embedded-in-markdown/output.md Demonstrates that a simple HTML structure is a valid Astro component. No special setup is required. ```astro

Hello world!

``` -------------------------------- ### Usage Example with Plugin Options Source: https://github.com/withastro/prettier-plugin-astro/blob/main/_autodocs/types.md Demonstrates how to apply Astro plugin options when formatting code with Prettier. Ensure the 'astro' parser and 'prettier-plugin-astro' are specified. ```typescript const options: Partial = { astroAllowShorthand: true, astroSkipFrontmatter: false, }; const formatted = await prettier.format(code, { parser: 'astro', plugins: ['prettier-plugin-astro'], ...options, }); ``` -------------------------------- ### Prettier Configuration for Astro Files Source: https://github.com/withastro/prettier-plugin-astro/blob/main/_autodocs/api-reference/index.md Example configuration for Prettier using '.prettierrc.mjs' to enable the Astro plugin and specify the parser for '.astro' files. ```javascript // .prettierrc.mjs export default { plugins: ['prettier-plugin-astro'], overrides: [ { files: '*.astro', options: { parser: 'astro', }, }, ], }; ``` -------------------------------- ### Prettier Format Request Example Source: https://github.com/withastro/prettier-plugin-astro/blob/main/_autodocs/architecture.md Initiates the formatting process with Prettier, specifying the Astro parser and plugin, along with custom options. ```typescript await prettier.format(source, { parser: 'astro', plugins: ['prettier-plugin-astro'], astroAllowShorthand: false, // ... other options }) ``` -------------------------------- ### Example 3: Root Node Keys Source: https://github.com/withastro/prettier-plugin-astro/blob/main/_autodocs/api-reference/get-visitor-keys.md Illustrates the output of getVisitorKeys for a 'root' AST node, highlighting the 'children' property as the primary visitable key. ```typescript // Input node: document root const rootNode = { type: 'root', children: [ { type: 'element', ... }, { type: 'text', ... }, { type: 'comment', ... }, ], position: {...}, }; const keys = getVisitorKeys(rootNode); // Returns: ['children'] // 'children' is non-empty array of objects // 'position' and 'type' are excluded ``` -------------------------------- ### Format an Astro File with Prettier Source: https://github.com/withastro/prettier-plugin-astro/blob/main/_autodocs/README.md Demonstrates how to programmatically format an Astro file using Prettier and the prettier-plugin-astro. Ensure the plugin is installed and imported. ```typescript import prettier from 'prettier'; import astroPlugin from 'prettier-plugin-astro'; const code = `

Hello

`; const formatted = await prettier.format(code, { parser: 'astro', plugins: [astroPlugin], }); ``` -------------------------------- ### Use prettier-plugin-astro CLI Source: https://github.com/withastro/prettier-plugin-astro/blob/main/_autodocs/README.md Provides examples of using the Prettier CLI to format Astro files. Demonstrates formatting all Astro files, applying custom options like `--astro-allow-shorthand`, and checking files without writing changes. ```bash # Format all Astro files prettier --write "src/**/*.astro" # With custom options prettier --write "src/**/*.astro" --astro-allow-shorthand true # Check without writing prettier --check "src/**/*.astro" ``` -------------------------------- ### Usage Example for Prettier Formatting Source: https://github.com/withastro/prettier-plugin-astro/blob/main/_autodocs/api-reference/index.md Demonstrates how to use the prettier-plugin-astro to format an Astro file by specifying the 'astro' parser and including the plugin in the Prettier configuration. ```typescript import prettier from 'prettier'; import astroPlugin from 'prettier-plugin-astro'; // Format an Astro file const formatted = await prettier.format('
{message}
', { parser: 'astro', plugins: [astroPlugin], }); ``` -------------------------------- ### Utility Function: shouldHugStart Source: https://github.com/withastro/prettier-plugin-astro/blob/main/_autodocs/api-summary.md Determines if formatting should 'hug' the start of a node, meaning no extra space before it. Considers node type and options. ```typescript shouldHugStart(node, opts) ``` -------------------------------- ### Prettier Configuration with Overrides for Multiple File Types Source: https://github.com/withastro/prettier-plugin-astro/blob/main/_autodocs/configuration.md An example Prettier configuration file (.prettierrc.mjs) demonstrating how to use overrides to apply different settings for Astro, TypeScript, and JSON files. ```javascript // .prettierrc.mjs export default { semi: true, singleQuote: false, overrides: [ { files: '*.astro', options: { parser: 'astro', plugins: ['prettier-plugin-astro'], astroAllowShorthand: true, astroSkipFrontmatter: false, }, }, { files: ['*.ts', '*.tsx'], options: { parser: 'typescript', semi: true, }, }, { files: '*.json', options: { parser: 'json', }, }, ], }; ``` -------------------------------- ### Format Astro Code with Prettier Source: https://github.com/withastro/prettier-plugin-astro/blob/main/_autodocs/api-reference/index.md Example of how to use Prettier to format Astro code. Ensure the 'astro' parser and the 'prettier-plugin-astro' are configured. ```typescript import prettier from 'prettier'; import astroPlugin from 'prettier-plugin-astro'; const code = ``; const result = await prettier.format(code, { parser: 'astro', plugins: [astroPlugin], printWidth: 80, }); ``` -------------------------------- ### Usage Example for Languages Export Source: https://github.com/withastro/prettier-plugin-astro/blob/main/_autodocs/api-reference/index.md Demonstrates how to access the language configuration details, such as the language name and file extensions, from the exported 'languages' array. ```typescript import { languages } from 'prettier-plugin-astro'; // This is automatically registered when the plugin is loaded console.log(languages[0].name); // 'astro' console.log(languages[0].extensions); // ['.astro'] ``` -------------------------------- ### Prose Wrap Always Example Source: https://github.com/withastro/prettier-plugin-astro/blob/main/test/fixtures/options/option-prose-wrap-always/output.md This example demonstrates how prose content is handled when the 'proseWrap' option is set to 'always'. It ensures that all text within prose blocks is wrapped to maintain consistent line lengths. ```markdown Lorem ipsum dolor sit amet consectetur adipisicing elit. At dignissimos quasi saepe odit sed repellendus voluptatum sunt, quia dolorem quam quos aliquid dolorum, iste suscipit nisi aliquam. Illum eius velit distinctio corporis recusandae, animi odit quis cupiditate non culpa voluptatem, officiis magnam quod aperiam perferendis obcaecati temporibus, iure natus hic? ``` -------------------------------- ### Import and Use Astro Components Source: https://github.com/withastro/prettier-plugin-astro/blob/main/test/fixtures/markdown/embedded-in-markdown/input.md Import Astro components in the frontmatter script and use them like HTML elements in the template. Component names must start with an uppercase letter. ```astro --- // Import your components in your component script... import SomeComponent from './SomeComponent.astro'; ---
``` -------------------------------- ### Example 4: Attribute Node Keys Source: https://github.com/withastro/prettier-plugin-astro/blob/main/_autodocs/api-reference/get-visitor-keys.md Demonstrates the result of getVisitorKeys for an 'attribute' AST node, which returns an empty array as its properties are primitives. ```typescript // Input node: element attribute const attributeNode = { type: 'attribute', kind: 'quoted', name: 'class', value: 'btn btn-primary', position: {...}, }; const keys = getVisitorKeys(attributeNode); // Returns: [] // 'kind', 'name', and 'value' are all primitives // 'position' and 'type' are excluded ``` -------------------------------- ### Import and Use Astro Components Source: https://github.com/withastro/prettier-plugin-astro/blob/main/test/fixtures/markdown/embedded-in-markdown/output.md Import Astro components in the frontmatter script and use them like HTML elements in the template. Component names must start with an uppercase letter. ```astro --- // Import your components in your component script... import SomeComponent from "./SomeComponent.astro"; ---
``` -------------------------------- ### Prettier Configuration for Astro (.prettierrc.json) Source: https://github.com/withastro/prettier-plugin-astro/blob/main/_autodocs/api-summary.md Configure Prettier for Astro projects using a .prettierrc.json file. This example sets the plugin and custom Astro options. ```json { "plugins": ["prettier-plugin-astro"], "astroAllowShorthand": true, "astroSkipFrontmatter": false, "printWidth": 100 } ``` -------------------------------- ### Example 2: Text Node Keys Source: https://github.com/withastro/prettier-plugin-astro/blob/main/_autodocs/api-reference/get-visitor-keys.md Shows the result of getVisitorKeys for a 'text' AST node, which typically returns an empty array as it has no visitable children. ```typescript // Input node: text content const textNode = { type: 'text', value: 'Hello World', position: {...}, }; const keys = getVisitorKeys(textNode); // Returns: [] // 'value' is a primitive string, excluded // 'position' and 'type' are excluded ``` -------------------------------- ### Example of Skipping Frontmatter Source: https://github.com/withastro/prettier-plugin-astro/blob/main/_autodocs/api-summary.md When `astroSkipFrontmatter` is set to `true`, the JavaScript code within the frontmatter block is not formatted by Prettier. ```astro --- // With astroSkipFrontmatter: true, this is NOT formatted const x="value" --- ``` -------------------------------- ### Recommended Prettier Configuration for Astro Source: https://github.com/withastro/prettier-plugin-astro/blob/main/README.md Configure Prettier to use the 'astro' parser for *.astro files. This recommended setup ensures optimal compatibility and correct parsing of Astro syntax. ```javascript // .prettierrc.mjs /** @type {import("prettier").Config} */ export default { plugins: ['prettier-plugin-astro'], overrides: [ { files: '*.astro', options: { parser: 'astro', }, }, ], }; ``` -------------------------------- ### Check if Element Hugs Start Source: https://github.com/withastro/prettier-plugin-astro/blob/main/_autodocs/api-reference/utils.md Determines if an element's opening tag should hug its first child, meaning no space after '>'. This is true for non-block elements with children where the first child doesn't start with whitespace. ```typescript export function shouldHugStart(node: anyNode, opts: ParserOptions): boolean ``` ```typescript if (shouldHugStart(node, opts)) { // Format as: content } else { // Format as: \n content } ``` -------------------------------- ### Frontmatter Script in Astro Component Source: https://github.com/withastro/prettier-plugin-astro/blob/main/test/fixtures/markdown/embedded-in-markdown/input.md Provides an example of a frontmatter script using JavaScript (or TypeScript) within an Astro component. This code runs at build-time. ```astro --- // Anything inside the `---` code fence is your component script. // This JavaScript code runs at build-time. // See below to learn more about what you can do. console.log('This runs at build-time, is visible in the CLI output'); // Tip: TypeScript is also supported out-of-the-box! const thisWorks: number = 42; ---

Hello world!

``` -------------------------------- ### Doc Generation Example Source: https://github.com/withastro/prettier-plugin-astro/blob/main/_autodocs/architecture.md Demonstrates the structure of Prettier's Doc objects returned by the print() function for an HTML element, showcasing grouping, indentation, and line breaking directives. ```typescript // Doc types used: group([...]) // Grouping for line breaking decisions indent([...]) // Increase indentation softline // Space or newline hardline // Always newline line // Always space or newline fill([...]) // Intelligent line breaking join(separator, [...]) # Join with separator dedent([...]) # Decrease indentation literalline # Raw newline from source Example: print(element) returns: group([ '', indent([softline, children]), '' ]) ``` -------------------------------- ### Frontmatter Script in an Astro Component Source: https://github.com/withastro/prettier-plugin-astro/blob/main/test/fixtures/markdown/embedded-in-markdown/output.md Provides an example of a frontmatter script within an Astro component. This JavaScript/TypeScript code runs at build-time and is not sent to the browser. ```astro --- // Anything inside the `---` code fence is your component script. // This JavaScript code runs at build-time. // See below to learn more about what you can do. console.log("This runs at build-time, is visible in the CLI output"); // Tip: TypeScript is also supported out-of-the-box! const thisWorks: number = 42; ---

Hello world!

``` -------------------------------- ### isTextNodeStartingWithLinebreak Source: https://github.com/withastro/prettier-plugin-astro/blob/main/_autodocs/api-reference/utils.md Type guard function that checks if a given TextNode starts with one or more newline characters. The number of newlines can be specified. ```APIDOC ## isTextNodeStartingWithLinebreak ### Description Checks if a text node starts with a linebreak. ### Parameters - `node` (TextNode) - Node to check - `nrLines` (number, default: 1) - Number of linebreaks ### Returns boolean - True if the text node starts with the specified number of linebreaks. ``` -------------------------------- ### Astro Code Formatting with Custom Options Source: https://github.com/withastro/prettier-plugin-astro/blob/main/_autodocs/api-summary.md Format Astro code with custom Prettier options. This example shows how to enable shorthand syntax and control frontmatter skipping, along with standard Prettier options like printWidth and tabWidth. ```typescript const formatted = await prettier.format(code, { parser: 'astro', plugins: ['prettier-plugin-astro'], astroAllowShorthand: true, astroSkipFrontmatter: false, printWidth: 100, tabWidth: 2, }); ``` -------------------------------- ### Enable Debugging for Prettier Parse Errors Source: https://github.com/withastro/prettier-plugin-astro/blob/main/_autodocs/configuration.md Run Prettier with the PRETTIER_DEBUG=1 environment variable to get more detailed debugging information when parse errors occur. This is useful for troubleshooting. ```bash PRETTIER_DEBUG=1 prettier --write "src/**/*.astro" ``` -------------------------------- ### Absolute URL for Asset in Astro Source: https://github.com/withastro/prettier-plugin-astro/blob/main/test/fixtures/markdown/embedded-in-markdown/output.md To correctly reference an asset like an image, use an absolute URL starting from the public directory. This ensures the asset is resolved correctly in the final build, referencing `public/thumbnail.png` which becomes `/thumbnail.png`. ```astro ``` -------------------------------- ### Configuration Flow Source: https://github.com/withastro/prettier-plugin-astro/blob/main/_autodocs/architecture.md Illustrates the sequence of how user configurations are merged with defaults and passed to the print function for formatting. ```text Configuration flow: User config (file/CLI/API) ↓ Merged with defaults from src/options.ts ↓ Passed to print() as ParserOptions (opts parameter) ↓ Each function checks opts for relevant settings: print() checks: ├─ opts.singleAttributePerLine ├─ opts.bracketSameLine ├─ opts.htmlWhitespaceSensitivity └─ opts.jsxSingleQuote embed() checks: ├─ opts.astroAllowShorthand ├─ opts.astroSkipFrontmatter ├─ opts.tabWidth ├─ opts.useTabs └─ opts.endOfLine Utils check: └─ opts.htmlWhitespaceSensitivity ``` -------------------------------- ### Check if Text Node Starts with Linebreak Source: https://github.com/withastro/prettier-plugin-astro/blob/main/_autodocs/api-reference/utils.md Checks if a TextNode starts with a specified number of linebreaks. The default is one linebreak. ```typescript export function isTextNodeStartingWithLinebreak(node: TextNode, nrLines = 1): node is TextNode ``` -------------------------------- ### Check if Text Node Starts with Whitespace Source: https://github.com/withastro/prettier-plugin-astro/blob/main/_autodocs/api-reference/utils.md Checks if a given node is a TextNode and if it begins with any whitespace characters. ```typescript export function isTextNodeStartingWithWhitespace(node: Node): node is TextNode ``` -------------------------------- ### Utility Function: isTextNodeStartingWithLinebreak Source: https://github.com/withastro/prettier-plugin-astro/blob/main/_autodocs/api-summary.md Determines if a text node starts with a line break. Useful for controlling vertical spacing. ```typescript isTextNodeStartingWithLinebreak(node, nrLines) ``` -------------------------------- ### Utility Function: getNextNode Source: https://github.com/withastro/prettier-plugin-astro/blob/main/_autodocs/api-summary.md Gets the next sibling node in the AST. Returns null if no next sibling exists. ```typescript getNextNode(path) ``` -------------------------------- ### Enable astroAllowShorthand via CLI Source: https://github.com/withastro/prettier-plugin-astro/blob/main/_autodocs/configuration.md Format Astro files with attribute shorthand enabled using the CLI. ```bash # Format with shorthand enabled prettier --write "src/**/*.astro" --astro-allow-shorthand true ``` -------------------------------- ### Check if Text Starts with Linebreak Source: https://github.com/withastro/prettier-plugin-astro/blob/main/_autodocs/api-reference/utils.md Determines if a string begins with one or more newline characters. Supports checking for a specific number of newlines. ```typescript export function startsWithLinebreak(text: string, nrLines = 1): boolean ``` -------------------------------- ### Prettier Configuration with Standard Options and Astro Plugin Source: https://github.com/withastro/prettier-plugin-astro/blob/main/_autodocs/configuration.md A comprehensive Prettier configuration file (.prettierrc.mjs) including standard Prettier options and Astro-specific settings. ```javascript // .prettierrc.mjs export default { printWidth: 100, tabWidth: 2, useTabs: false, semi: true, singleQuote: false, trailingComma: 'all', bracketSpacing: true, bracketSameLine: false, arrowParens: 'always', endOfLine: 'lf', singleAttributePerLine: false, // Astro plugin plugins: ['prettier-plugin-astro'], astroAllowShorthand: false, astroSkipFrontmatter: false, }; ``` -------------------------------- ### Incorrect URL Resolution for Assets Source: https://github.com/withastro/prettier-plugin-astro/blob/main/test/fixtures/markdown/embedded-in-markdown/input.md Astro does not automatically transform HTML references for relative asset paths. This example shows an incorrect approach. ```astro ``` -------------------------------- ### Configure Prettier with Overrides Source: https://github.com/withastro/prettier-plugin-astro/blob/main/_autodocs/README.md Illustrates how to use Prettier's overrides to apply specific configurations to Astro files. This is useful for setting the parser and plugin for .astro files while using different configurations for other file types. ```javascript export default { overrides: [ { files: '*.astro', options: { parser: 'astro', plugins: ['prettier-plugin-astro'], }, }, { files: '*.ts', options: { parser: 'typescript', }, }, ], }; ``` -------------------------------- ### Configure Prettier with .prettierrc.mjs Source: https://github.com/withastro/prettier-plugin-astro/blob/main/_autodocs/README.md Shows how to configure prettier-plugin-astro in a .prettierrc.mjs file. This includes specifying the plugin and setting common Prettier options along with plugin-specific ones. ```javascript export default { plugins: ['prettier-plugin-astro'], printWidth: 100, tabWidth: 2, astroAllowShorthand: false, astroSkipFrontmatter: false, }; ``` -------------------------------- ### Get Sibling Nodes Source: https://github.com/withastro/prettier-plugin-astro/blob/main/_autodocs/api-reference/utils.md Returns all sibling nodes, which are the children of the current node's parent. Returns an empty array if the node has no parent. ```typescript export function getSiblings(path: AstPath): anyNode[] ``` -------------------------------- ### Recommended Prettier Configuration for Astro Source: https://github.com/withastro/prettier-plugin-astro/blob/main/_autodocs/configuration.md A recommended Prettier configuration file (.prettierrc.mjs) for Astro projects, balancing common preferences and Astro-specific defaults. ```javascript // .prettierrc.mjs export default { plugins: ['prettier-plugin-astro'], printWidth: 100, tabWidth: 2, useTabs: false, semi: true, singleQuote: false, quoteProps: 'as-needed', jsxSingleQuote: false, trailingComma: 'all', bracketSpacing: true, bracketSameLine: false, arrowParens: 'always', endOfLine: 'lf', singleAttributePerLine: false, astroAllowShorthand: false, astroSkipFrontmatter: false, }; ``` -------------------------------- ### Importing Prettier Plugin Astro Source: https://github.com/withastro/prettier-plugin-astro/blob/main/_autodocs/api-summary.md Demonstrates how to import the main Astro Prettier plugin and its associated types, utilities, and constants for use in custom configurations or tooling. ```typescript // Main plugin exports import astroPlugin from 'prettier-plugin-astro'; // Type definitions (if needed) import type { PluginOptions, RootNode, ElementNode, ComponentNode, // ... other types } from '@astrojs/compiler/types'; // Utilities (rarely needed) import { isTextNode, isBlockElement, getUnencodedText, // ... other utilities } from 'prettier-plugin-astro/src/printer/utils'; // Constants (rarely needed) import { blockElements, selfClosingTags, } from 'prettier-plugin-astro/src/printer/elements'; import { openingBracketReplace, closingBracketReplace, atSignReplace, dotReplace, interrogationReplace, } from 'prettier-plugin-astro/src/printer/utils'; ``` -------------------------------- ### shouldHugStart Source: https://github.com/withastro/prettier-plugin-astro/blob/main/_autodocs/api-reference/utils.md Determines if an element's opening tag should hug its first child, meaning no space after the opening bracket. ```APIDOC ## shouldHugStart ### Description Determines if an element's opening tag should hug its first child (no space after `>`). ### Parameters - `node` (anyNode) — Node to check - `opts` (ParserOptions) — Formatting options ### Returns boolean **Returns true if:** - Node is NOT a block element AND - Node has children AND - First child doesn't start with whitespace ### Usage Example: ```typescript if (shouldHugStart(node, opts)) { // Format as: content } else { // Format as: \n content } ``` ``` -------------------------------- ### Get Unencoded Text from Node Source: https://github.com/withastro/prettier-plugin-astro/blob/main/_autodocs/api-reference/utils.md Retrieves the raw text content from a text or comment node. Useful for accessing the exact string value of these nodes. ```typescript export function getUnencodedText(node: TextNode | CommentNode): string ``` ```typescript const text = getUnencodedText(node); const trimmed = text.trim(); ``` -------------------------------- ### Hugging Whitespace Logic Source: https://github.com/withastro/prettier-plugin-astro/blob/main/_autodocs/architecture.md Explains the `shouldHugStart` and `shouldHugEnd` functions that control whether whitespace is added directly after a closing tag (>) or before an opening tag ( shouldHugEnd() → No space before content Hug start=false, end=false:
content
Hug start=true, end=false: content Hug start=false, end=true:
content
``` -------------------------------- ### Dependency Graph Source: https://github.com/withastro/prettier-plugin-astro/blob/main/_autodocs/architecture.md Lists the external, internal type, and runtime dependencies required for the plugin to function. ```text External Dependencies: ├─ @astrojs/compiler ^2.9.1 (parsing) ├─ prettier ^3.5.3 (core) └─ sass-formatter ^0.7.6 (SASS formatting) Internal Type Dependencies: ├─ @astrojs/compiler/types (node types) ├─ prettier (types) (Doc, Parser, Printer, etc.) └─ sass-formatter (types) (SassFormatterConfig) Runtime Dependencies: ├─ node:buffer (Buffer for binary operations) └─ Standard library (String methods, etc.) ``` -------------------------------- ### Skip frontmatter formatting via CLI Source: https://github.com/withastro/prettier-plugin-astro/blob/main/_autodocs/configuration.md Format Astro files while skipping frontmatter formatting using the CLI. ```bash # Format Astro files, skipping frontmatter prettier --write "src/**/*.astro" --astro-skip-frontmatter true ``` -------------------------------- ### Enable astroAllowShorthand in .prettierrc.cjs Source: https://github.com/withastro/prettier-plugin-astro/blob/main/_autodocs/configuration.md Configure the plugin to enable attribute shorthand syntax in .prettierrc.cjs files using API overrides. ```javascript // .prettierrc.cjs - using API override module.exports = { plugins: ['prettier-plugin-astro'], astroAllowShorthand: true, }; ``` -------------------------------- ### Format Astro Code with Cursor Position Source: https://github.com/withastro/prettier-plugin-astro/blob/main/_autodocs/api-summary.md Format Astro code and get the result with a specific cursor offset. This is helpful for IDE integrations to format code around the cursor. ```typescript const result = await prettier.formatWithCursor(code, { parser: 'astro', plugins: ['prettier-plugin-astro'], cursorOffset: 42, }); ``` -------------------------------- ### Astro File Formatting with Default Frontmatter Handling Source: https://github.com/withastro/prettier-plugin-astro/blob/main/_autodocs/configuration.md Shows an Astro file formatted with 'astroSkipFrontmatter' set to false (default), preserving frontmatter. ```astro --- const message = "Hello"; const items = ["a", "b", "c"]; ---

{message}

``` -------------------------------- ### Enable astroSkipFrontmatter in .prettierrc.mjs Source: https://github.com/withastro/prettier-plugin-astro/blob/main/_autodocs/configuration.md Configure the plugin to skip frontmatter formatting in .prettierrc.mjs files. ```javascript // .prettierrc.mjs export default { plugins: ['prettier-plugin-astro'], astroSkipFrontmatter: true, }; ``` -------------------------------- ### Get Next Sibling Node Source: https://github.com/withastro/prettier-plugin-astro/blob/main/_autodocs/api-reference/utils.md Returns the next sibling node in the AST. Returns null if the current node is the last sibling. It finds the current node's position by matching `position.start`. ```typescript export function getNextNode(path: AstPath): anyNode | null ``` ```typescript const next = getNextNode(path); if (next && isTagLikeNode(next)) { // Add line break before next tag } ``` -------------------------------- ### Static HTML in Astro Component Source: https://github.com/withastro/prettier-plugin-astro/blob/main/test/fixtures/markdown/embedded-in-markdown/input.md Demonstrates that plain HTML is a valid Astro component. This can be used for static content within an Astro project. ```astro

Hello world!

``` -------------------------------- ### Get Text Content from Node Source: https://github.com/withastro/prettier-plugin-astro/blob/main/_autodocs/README.md Utility function to extract the unencoded text content from a text node in the Astro AST. This is useful when you need to process or display the raw text without HTML entities. ```typescript import { getUnencodedText } from 'prettier-plugin-astro/src/printer/utils'; const text = getUnencodedText(textNode); ``` -------------------------------- ### Prettier's Usage of getVisitorKeys (Pseudo-code) Source: https://github.com/withastro/prettier-plugin-astro/blob/main/_autodocs/api-reference/get-visitor-keys.md Illustrates how Prettier utilizes the getVisitorKeys function during AST traversal to identify and process child nodes. ```javascript // Pseudo-code showing Prettier's usage const keys = getVisitorKeys(node); for (const key of keys) { const childNodes = Array.isArray(node[key]) ? node[key] : [node[key]]; for (const child of childNodes) { // Recursively print each child print(child); } } ``` -------------------------------- ### Tree Traversal with Print Function Source: https://github.com/withastro/prettier-plugin-astro/blob/main/_autodocs/architecture.md Illustrates the recursive process of the print() function in traversing AST nodes, starting from the root and recursively calling print() for children, attributes, and other node types. It returns an array of Doc objects. ```text print(rootNode) ↓ case 'root': ↓ Print each child via path.map(print, 'children') ↓ For each child, call print() recursively ↓ For each attribute, call print() recursively ↓ Returns: Doc[] with formatting directives ``` ```text print(node) { if (!node) → return '' if (ignoreNext) → return raw original text if (typeof node === 'string') → return node switch (node.type) { case 'root' → format root with children case 'text' → handle text with fill() case 'element' → format element with opening/closing tags case 'component' → format component case 'attribute' → format specific attribute kind case 'comment' → format comment, check for prettier-ignore case 'doctype' → return default → throw error for unhandled type } } ``` -------------------------------- ### Enable astroAllowShorthand in .prettierrc (JSON) Source: https://github.com/withastro/prettier-plugin-astro/blob/main/_autodocs/configuration.md Configure the plugin to enable attribute shorthand syntax in .prettierrc JSON files using API overrides. ```json // .prettierrc - using API override { "plugins": ["prettier-plugin-astro"], "astroAllowShorthand": true } ``` -------------------------------- ### Configure overrides for Astro files in .prettierrc.cjs Source: https://github.com/withastro/prettier-plugin-astro/blob/main/_autodocs/configuration.md Set default Prettier options and override settings for Astro files, including skipping frontmatter, in .prettierrc.cjs. ```javascript // .prettierrc.cjs with overrides for different file types module.exports = { // Default settings semi: true, singleQuote: true, // Astro files with plugin overrides: [ { files: '*.astro', options: { parser: 'astro', plugins: ['prettier-plugin-astro'], astroSkipFrontmatter: true, astroAllowShorthand: false, }, }, ], }; ``` -------------------------------- ### Registering getVisitorKeys with Prettier Printer Source: https://github.com/withastro/prettier-plugin-astro/blob/main/_autodocs/api-reference/get-visitor-keys.md Shows how the getVisitorKeys function is registered within the Prettier printer configuration for Astro files. ```typescript // From src/index.ts export const printers: Record = { astro: { print, embed, getVisitorKeys, // Registered here }, }; ``` -------------------------------- ### Enable astroAllowShorthand in .prettierrc.mjs Source: https://github.com/withastro/prettier-plugin-astro/blob/main/_autodocs/configuration.md Configure the plugin to enable attribute shorthand syntax in .prettierrc.mjs files using API overrides. ```javascript // .prettierrc.mjs - using API override export default { plugins: ['prettier-plugin-astro'], astroAllowShorthand: true, }; ``` -------------------------------- ### Accessing Default Tab Width Source: https://github.com/withastro/prettier-plugin-astro/blob/main/_autodocs/api-reference/index.md Demonstrates how to import and access the default tab width setting from the plugin's default options. ```typescript import { defaultOptions } from 'prettier-plugin-astro'; console.log(defaultOptions.tabWidth); // 2 ``` -------------------------------- ### Using Fragments in JSX Expressions in Astro Source: https://github.com/withastro/prettier-plugin-astro/blob/main/test/fixtures/markdown/embedded-in-markdown/output.md When rendering multiple elements within a JSX expression in Astro, Fragments (`<>...`) are required to group them without adding extra DOM nodes. This example maps an array to render sets of list items within fragments. ```astro --- const items = ["Dog", "Cat", "Platipus"]; ---
    { items.map((item) => ( <>
  • Red {item}
  • Blue {item}
  • Green {item}
  • )) }
``` -------------------------------- ### Format Code with Custom Prettier Options Source: https://github.com/withastro/prettier-plugin-astro/blob/main/_autodocs/README.md Demonstrates how to format Astro code using Prettier with custom options, including plugin-specific settings like `astroAllowShorthand` and standard Prettier configurations like `printWidth` and `singleQuote`. ```javascript const formatted = await prettier.format(code, { parser: 'astro', plugins: [astroPlugin], printWidth: 120, tabWidth: 4, useTabs: true, semi: false, singleQuote: true, astroAllowShorthand: true, }); ``` -------------------------------- ### Astro code formatting with astroAllowShorthand enabled Source: https://github.com/withastro/prettier-plugin-astro/blob/main/_autodocs/configuration.md Illustrates Astro code formatting when `astroAllowShorthand` is set to `true`. ```astro With `astroAllowShorthand: true`: ```astro ``` ``` -------------------------------- ### Configure Biome for JavaScript Formatting Source: https://github.com/withastro/prettier-plugin-astro/blob/main/_autodocs/configuration.md This JSON configuration is for Biome, enabling its import organization and formatting capabilities. It specifies indentation and line width settings. ```json // biome.json { "organizeImports": { "enabled": true }, "format": { "enabled": true, "indentStyle": "space", "indentSize": 2, "lineWidth": 100 }, "linter": { "enabled": true, "rules": { "recommended": true } } } ``` -------------------------------- ### Correct URL Resolution using Asset Import Source: https://github.com/withastro/prettier-plugin-astro/blob/main/test/fixtures/markdown/embedded-in-markdown/input.md Import assets within the component script for correct URL resolution. This approach is useful for organizing assets alongside components. ```astro --- // ✅ Correct: references src/thumbnail.png import thumbnailSrc from './thumbnail.png'; --- ``` -------------------------------- ### Format Astro Files via CLI Source: https://github.com/withastro/prettier-plugin-astro/blob/main/_autodocs/api-summary.md Use the Prettier CLI to format all Astro files in a directory. This command writes the formatted code back to the files and enables Astro-specific shorthand syntax. ```bash prettier --write "**/*.astro" --astro-allow-shorthand true ``` -------------------------------- ### Format Astro Code Source: https://github.com/withastro/prettier-plugin-astro/blob/main/_autodocs/api-reference/printer.md Demonstrates how to format a full Astro code string using the 'astro' parser and the plugin. Ensure the plugin and parser are correctly configured. ```typescript const astroCode = `---\nconst message = "Hello";\n---` const formatted = await format(astroCode, { parser: 'astro', plugins: [plugin], }); ``` -------------------------------- ### Format Astro File with Prettier CLI Source: https://github.com/withastro/prettier-plugin-astro/blob/main/_autodocs/configuration.md Use the Prettier CLI to format all Astro files in a 'src' directory, with frontmatter processing explicitly set to false. ```bash prettier --write "src/**/*.astro" --astro-skip-frontmatter false ``` -------------------------------- ### Basic Prettier Configuration for Astro Source: https://github.com/withastro/prettier-plugin-astro/blob/main/README.md Add the prettier-plugin-astro to your Prettier configuration file (.prettierrc.mjs). This enables the plugin to recognize and format Astro files. ```javascript // .prettierrc.mjs /** @type {import("prettier").Config} */ export default { plugins: ['prettier-plugin-astro'], }; ``` -------------------------------- ### Prettier Printer Methods Source: https://github.com/withastro/prettier-plugin-astro/blob/main/_autodocs/api-summary.md Lists the essential methods provided by Prettier's `path` object that are available within the plugin's print function for AST traversal and manipulation. ```typescript print(path: AstPath, opts: ParserOptions, printFn: printFn): Doc ``` ```typescript embed(path: AstPath, opts: Options): (textToDoc: TextToDoc, print: printFn) => Promise ``` ```typescript getVisitorKeys(node: any): string[] ``` -------------------------------- ### Utility Functions Source: https://github.com/withastro/prettier-plugin-astro/blob/main/_autodocs/api-summary.md Utility functions available via direct import from `src/printer/utils.ts` for advanced usage. ```APIDOC ## Utility Functions Available via direct import if needed from `src/printer/utils.ts`. ### Functions - `isTextNode(node)`: Check if node is text. - `isExpressionNode(node)`: Check if node is expression. - `isTagLikeNode(node)`: Check if node is tag-like. - `isBlockElement(node, opts)`: Check if block element. - `isInlineElement(path, opts, node)`: Check if inline element. - `isNodeWithChildren(node)`: Check if has children. - `isEmptyTextNode(node)`: Check if empty text. - `isIgnoreDirective(node)`: Check for prettier-ignore. - `isPreTagContent(path)`: Check if in `
` tag.
- `isTextNodeStartingWithWhitespace(node)`: Check starting whitespace.
- `isTextNodeEndingWithWhitespace(node)`: Check ending whitespace.
- `isTextNodeStartingWithLinebreak(node, nrLines)`: Check starting linebreak.
- `getUnencodedText(node)`: Get text content.
- `printRaw(node, strip)`: Serialize node.
- `startsWithLinebreak(text, nrLines)`: Check text start.
- `endsWithLinebreak(text, nrLines)`: Check text end.
- `shouldHugStart(node, opts)`: Format decision.
- `shouldHugEnd(node, opts)`: Format decision.
- `canOmitSoftlineBeforeClosingTag(path, opts)`: Format decision.
- `trimTextNodeLeft(node)`: Trim left side.
- `trimTextNodeRight(node)`: Trim right side.
- `printClassNames(value)`: Format class attribute.
- `manualDedent(input)`: Remove indentation, returns `{tabSize, char, result}`.
- `getSiblings(path)`: Get sibling nodes.
- `getNextNode(path)`: Get next sibling.
- `hasSetDirectives(node)`: Check for set:* directives.
- `getPreferredQuote(content, preferred)`: Select quote character, returns `QuoteResult`.
- `inferParserByTypeAttribute(type)`: Infer parser from type, returns `BuiltInParserName`.
```

--------------------------------

### Programmatic API for Formatting Astro Code

Source: https://github.com/withastro/prettier-plugin-astro/blob/main/_autodocs/configuration.md

Demonstrates how to use the Prettier programmatic API to format Astro code, specifically with the 'astroSkipFrontmatter' option set to true.

```typescript
import prettier from 'prettier';
import astroPlugin from 'prettier-plugin-astro';

// Format with frontmatter skipped
const formatted = await prettier.format(code, {
  parser: 'astro',
  plugins: [astroPlugin],
  astroSkipFrontmatter: true,
});
```

--------------------------------

### Configure Prettier Plugins in package.json

Source: https://github.com/withastro/prettier-plugin-astro/blob/main/_autodocs/configuration.md

An alternative method to configure Prettier plugins and options by specifying them within the 'prettier' field in your package.json file. This approach is less recommended than using a dedicated config file.

```json
{
  "prettier": {
    "plugins": ["prettier-plugin-astro"],
    "astroAllowShorthand": false,
    "astroSkipFrontmatter": false,
    "printWidth": 100,
    "tabWidth": 2
  }
}
```

--------------------------------

### Attribute Handling and Formatting

Source: https://github.com/withastro/prettier-plugin-astro/blob/main/_autodocs/architecture.md

Categorizes different types of attributes (empty, quoted, expression, shorthand, spread, template-literal) and illustrates how they are formatted, including the option for a single attribute per line.

```text
Attribute kinds and formatting:

empty:     
quoted:
expression:
(via embed) shorthand:
(when astroAllowShorthand=true) spread:
template-literal:
Single attribute per line (when singleAttributePerLine=true): ``` -------------------------------- ### Dynamic HTML Rendering with .map() Source: https://github.com/withastro/prettier-plugin-astro/blob/main/test/fixtures/markdown/embedded-in-markdown/output.md Render dynamic lists of HTML elements by using JavaScript's .map() function within the template to iterate over arrays. ```astro --- const items = ["Dog", "Cat", "Platipus"]; ---
    {items.map((item) =>
  • {item}
  • )}
``` -------------------------------- ### Astro Plugin Options Definition Source: https://github.com/withastro/prettier-plugin-astro/blob/main/_autodocs/api-reference/index.md TypeScript definition for plugin-specific configuration options. It maps option keys to their support metadata. ```typescript export const options: Record ``` -------------------------------- ### Scoped CSS in an Astro Component Source: https://github.com/withastro/prettier-plugin-astro/blob/main/test/fixtures/markdown/embedded-in-markdown/output.md Shows how to use a `
``` -------------------------------- ### Plugin Options Interface Source: https://github.com/withastro/prettier-plugin-astro/blob/main/_autodocs/types.md Defines Astro-specific configuration options for Prettier. Use this interface to type partial options when configuring the plugin. ```typescript interface PluginOptions { astroAllowShorthand: boolean; astroSkipFrontmatter: boolean; } ``` -------------------------------- ### Format with astroAllowShorthand enabled programmatically Source: https://github.com/withastro/prettier-plugin-astro/blob/main/_autodocs/configuration.md Format code with attribute shorthand enabled using the Prettier programmatic API. ```typescript import prettier from 'prettier'; import astroPlugin from 'prettier-plugin-astro'; // Format with shorthand enabled const formatted = await prettier.format(code, { parser: 'astro', plugins: [astroPlugin], astroAllowShorthand: true, }); ``` -------------------------------- ### Astro AST Node Type Hierarchy Source: https://github.com/withastro/prettier-plugin-astro/blob/main/_autodocs/types.md Illustrates the hierarchical relationships between different Abstract Syntax Tree (AST) node types in Astro. This helps understand how various parts of an Astro file are represented. ```plaintext Node (base) ├── RootNode (has children) ├── TextNode ├── CommentNode ├── DoctypeNode ├── ExpressionNode ├── AttributeNode ├── TagLikeNode (base for tag-like) │ ├── ElementNode (has children, attributes) │ ├── ComponentNode (has children, attributes) │ ├── CustomElementNode (has children, attributes) │ └── FragmentNode (has children, attributes) └── FrontmatterNode ``` -------------------------------- ### Runtime Dependencies for Prettier Plugin Astro Source: https://github.com/withastro/prettier-plugin-astro/blob/main/_autodocs/api-summary.md Lists the core runtime dependencies required for the Prettier plugin Astro to function, including the Astro compiler and Prettier itself. ```json { "@astrojs/compiler": "^2.9.1", "prettier": "^3.5.3", "sass-formatter": "^0.7.6" } ``` -------------------------------- ### Plugin Options Interface Source: https://github.com/withastro/prettier-plugin-astro/blob/main/_autodocs/README.md Defines the configuration options specific to the prettier-plugin-astro, including options for enabling shorthand attributes and skipping frontmatter formatting. ```typescript interface PluginOptions { astroAllowShorthand: boolean; // default: false astroSkipFrontmatter: boolean; // default: false } ``` -------------------------------- ### Define and Use Component Props in Astro Source: https://github.com/withastro/prettier-plugin-astro/blob/main/test/fixtures/markdown/embedded-in-markdown/input.md Access component props using `Astro.props` in the frontmatter script. Destructure props to set default values for optional props. ```astro --- // Example: const { greeting = 'Hello', name } = Astro.props; ---

{greeting}, {name}!

``` -------------------------------- ### Configure Prettier for Astro with External JavaScript Formatters Source: https://github.com/withastro/prettier-plugin-astro/blob/main/_autodocs/configuration.md Use this configuration in your .prettierrc.mjs file to enable the Prettier Astro plugin and skip formatting JavaScript frontmatter. It also sets standard Prettier options for the template portion. ```javascript // .prettierrc.mjs export default { plugins: ['prettier-plugin-astro'], // Skip formatting the JavaScript frontmatter astroSkipFrontmatter: true, // Format the template portion printWidth: 100, tabWidth: 2, useTabs: false, singleQuote: false, trailingComma: 'all', }; ``` -------------------------------- ### Default Options for Astro Files Source: https://github.com/withastro/prettier-plugin-astro/blob/main/_autodocs/api-reference/index.md Provides the default formatting options, such as tab width, applied to all Astro files processed by the plugin. ```typescript export const defaultOptions: { tabWidth: number; } ``` -------------------------------- ### Asset Import Reference in Astro Source: https://github.com/withastro/prettier-plugin-astro/blob/main/test/fixtures/markdown/embedded-in-markdown/output.md Alternatively, assets can be organized alongside Astro components and imported within the component script. This method works but makes the asset's final URL less predictable compared to using the `public/` directory. ```astro --- // ✅ Correct: references src/thumbnail.png import thumbnailSrc from "./thumbnail.png"; --- ``` -------------------------------- ### Handle Null or Undefined Input Source: https://github.com/withastro/prettier-plugin-astro/blob/main/_autodocs/api-reference/get-visitor-keys.md When provided with null or undefined input, getVisitorKeys returns an empty array, indicating no properties to visit. ```typescript getVisitorKeys(null) // Returns: [] getVisitorKeys(undefined) // Returns: [] ``` -------------------------------- ### Astro Printer Interface Source: https://github.com/withastro/prettier-plugin-astro/blob/main/_autodocs/api-reference/index.md Defines the structure for the Astro printer, which converts Astro AST nodes into formatted output. Includes functions for printing, embedding, and visiting AST nodes. ```typescript { print: (path: AstPath, opts: ParserOptions, print: printFn) => Doc, embed: (path: AstPath, opts: Options) => Embed, getVisitorKeys: (node: any) => string[] } ``` -------------------------------- ### Importing Prettier Astro Plugin Types Source: https://github.com/withastro/prettier-plugin-astro/blob/main/_autodocs/types.md Provides the necessary import statements to use the various AST node types and configuration options from the 'prettier-plugin-astro' package in your TypeScript project. ```typescript import type { // Configuration PluginOptions, // AST Nodes RootNode, ElementNode, ComponentNode, CustomElementNode, ExpressionNode, TextNode, DoctypeNode, CommentNode, FragmentNode, FrontmatterNode, AttributeNode, Node, ParentLikeNode, TagLikeNode, anyNode, // Printer ParserOptions, AstPath, } from 'prettier-plugin-astro'; // For Prettier types import type { Doc, Parser, Printer, SupportLanguage, SupportOption } from 'prettier'; ``` -------------------------------- ### VS Code Settings for Prettier with Astro Source: https://github.com/withastro/prettier-plugin-astro/blob/main/README.md Configure VS Code to use the Prettier extension for formatting Astro files. These settings ensure that Prettier is recognized as the default formatter for *.astro files. ```json { "prettier.documentSelectors": ["**/*.astro"], "[astro]": { "editor.defaultFormatter": "esbenp.prettier-vscode" } } ```