# MD051 - Link Fragments Should Be Valid

## Description

This rule ensures that link fragments (the part after the # in a link) point to valid headings in the  
document. This helps prevent broken internal links and improves navigation within Markdown documents.

<!-- markdownlint-disable -->
## Examples

### Valid

```markdown
# Introduction

## Getting Started

[Link to Getting Started](#getting-started)

[Link with formatting](#heading-with-bold-and-italic)

# Heading with **bold** and *italic*
```

### Invalid

```markdown
# Introduction

## Getting Started

[Link to non-existent heading](#installation)
```

### Fixed

```markdown
# Introduction

## Getting Started

## Installation

[Link to Installation](#installation)
```
<!-- markdownlint-enable -->

## Configuration

This rule has no configuration options.

## Special Cases

- This rule only applies to internal links with fragments (links that start with #)
- It does not apply to external links (links to other documents or websites)
- The rule checks if the fragment matches a heading in the document
- Heading IDs are generated by converting the heading text to lowercase and replacing spaces with hyphens
- Special characters in headings are removed when generating IDs
- Markdown formatting (bold, italic, code spans, links) is stripped from headings when generating IDs
- The rule performs case-insensitive matching for fragments
- Links in code blocks are ignored
- Headings in code blocks are also ignored

## Implementation Details

The rule follows GitHub's algorithm for generating heading IDs:
1. Strip all Markdown formatting (code spans, emphasis, links, etc.)
2. Convert to lowercase
3. Replace spaces with hyphens
4. Remove non-alphanumeric characters except hyphens
5. Replace multiple consecutive hyphens with a single hyphen

## Related Rules

- [MD042 - No empty links](md042.md): Ensures links have content
- [MD034 - No bare URLs](md034.md): Ensures URLs are properly formatted
- [MD039 - No space inside link text](md039.md): Ensures proper formatting of link text
