Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,31 @@ Notes:
* [H33: Supplementing link text with the title attribute](https://www.w3.org/TR/WCAG20-TECHS/H33.html)


### MDX / Link Reference Comment Syntax

When using MDX files (e.g. with [fumadocs](https://fumadocs.dev), [Astro](https://astro.build/), or other JSX-based static site generators), HTML comments (`<!-- -->`) are not supported. An alternative comment syntax using [markdown link reference definitions](https://spec.commonmark.org/0.31.2/#link-reference-definitions) can be used instead:

<pre>
[//]: # (snippet: MySnippetName)
[//]: # (endSnippet)
</pre>

This works the same way as the HTML comment syntax but is compatible with both standard markdown and MDX parsers. When using InPlaceOverwrite convention, the content between the markers will be replaced with the snippet content, and the link reference format will be preserved:

[//]: # (snippet: MySnippetName)
```cs
My Snippet Code
```
[//]: # (endSnippet)

This syntax also works for web-snippets:

<pre>
[//]: # (web-snippet: https://example.com/file.cs#snippetKey)
[//]: # (endSnippet)
</pre>


### Including a snippet from the web

Snippets that start with `http` will be downloaded and the contents rendered. For example:
Expand Down
25 changes: 25 additions & 0 deletions readme.source.md
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,31 @@ Notes:
* [H33: Supplementing link text with the title attribute](https://www.w3.org/TR/WCAG20-TECHS/H33.html)


### MDX / Link Reference Comment Syntax

When using MDX files (e.g. with [fumadocs](https://fumadocs.dev), [Astro](https://astro.build/), or other JSX-based static site generators), HTML comments (`<!-- -->`) are not supported. An alternative comment syntax using [markdown link reference definitions](https://spec.commonmark.org/0.31.2/#link-reference-definitions) can be used instead:

<pre>
[//]: # (snippet: MySnippetName)
[//]: # (endSnippet)
</pre>

This works the same way as the HTML comment syntax but is compatible with both standard markdown and MDX parsers. When using InPlaceOverwrite convention, the content between the markers will be replaced with the snippet content, and the link reference format will be preserved:

[//]: # (snippet: MySnippetName)
```cs
My Snippet Code
```
[//]: # (endSnippet)

This syntax also works for web-snippets:

<pre>
[//]: # (web-snippet: https://example.com/file.cs#snippetKey)
[//]: # (endSnippet)
</pre>


### Including a snippet from the web

Snippets that start with `http` will be downloaded and the contents rendered. For example:
Expand Down
1 change: 1 addition & 0 deletions src/MarkdownSnippets/Processing/IncludeProcessor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -210,6 +210,7 @@ static IEnumerable<Line> BuildMultiple(Line line, string? path, Include include,
static bool ShouldWriteIncludeOnDiffLine(string line) =>
SnippetKey.IsSnippetLine(line) ||
line.StartsWith("<!-- endSnippet -->") ||
line.StartsWith("[//]: # (endSnippet)") ||
line.EndsWith("```") ||
line.StartsWith('|') ||
line.EndsWith('|');
Comment on lines 210 to 216
Copy link

Copilot AI Mar 21, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ShouldWriteIncludeOnDiffLine checks snippet/end markers with StartsWith(...) on the raw line. Since snippet detection elsewhere trims leading whitespace, indented markers like [//]: # (endSnippet) (or <!-- endSnippet -->) won't match here and may cause include markers to be appended to the same line, potentially breaking subsequent snippet processing. Consider applying TrimStart() before these StartsWith checks (including the newly-added link-ref endSnippet check) to align behavior with SnippetKey.Extract* parsing.

Suggested change
static bool ShouldWriteIncludeOnDiffLine(string line) =>
SnippetKey.IsSnippetLine(line) ||
line.StartsWith("<!-- endSnippet -->") ||
line.StartsWith("[//]: # (endSnippet)") ||
line.EndsWith("```") ||
line.StartsWith('|') ||
line.EndsWith('|');
static bool ShouldWriteIncludeOnDiffLine(string line)
{
var trimmed = line.TrimStart();
return
SnippetKey.IsSnippetLine(trimmed) ||
trimmed.StartsWith("<!-- endSnippet -->") ||
trimmed.StartsWith("[//]: # (endSnippet)") ||
line.EndsWith("```") ||
trimmed.StartsWith('|') ||
line.EndsWith('|');
}

Copilot uses AI. Check for mistakes.
Expand Down
67 changes: 51 additions & 16 deletions src/MarkdownSnippets/Processing/MarkdownProcessor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -181,20 +181,20 @@ Action<string> CreateIndentedAppendLine(string indent) => s =>
continue;
}

void AppendSnippet(string key1)
void AppendSnippet(string key1, bool useLinkRefFormat = false)
{
builder.Clear();
var indentedAppendLine = CreateIndentedAppendLine(line.LeadingWhitespace);
ProcessSnippetLine(indentedAppendLine, missingSnippets, usedSnippets, key1, relativePath, line);
ProcessSnippetLine(indentedAppendLine, missingSnippets, usedSnippets, key1, relativePath, line, useLinkRefFormat);
builder.TrimEnd();
line.Current = builder.ToString();
}

void AppendWebSnippet(string url, string snippetKey, string? viewUrl = null)
void AppendWebSnippet(string url, string snippetKey, string? viewUrl = null, bool useLinkRefFormat = false)
{
builder.Clear();
var indentedAppendLine = CreateIndentedAppendLine(line.LeadingWhitespace);
ProcessWebSnippetLine(indentedAppendLine, missingSnippets, usedSnippets, url, snippetKey, viewUrl, line);
ProcessWebSnippetLine(indentedAppendLine, missingSnippets, usedSnippets, url, snippetKey, viewUrl, line, useLinkRefFormat);
builder.TrimEnd();
line.Current = builder.ToString();
}
Expand Down Expand Up @@ -244,6 +244,34 @@ void AppendWebSnippet(string url, string snippetKey, string? viewUrl = null)
continue;
}

if (SnippetKey.ExtractLinkRefCommentSnippet(line, out key))
{
AppendSnippet(key, useLinkRefFormat: true);

index++;

lines.RemoveUntil(
index,
"[//]: # (endSnippet)",
relativePath,
line);
continue;
}

if (SnippetKey.ExtractLinkRefCommentWebSnippet(line, out url, out snippetKey, out viewUrl))
{
AppendWebSnippet(url, snippetKey, viewUrl, useLinkRefFormat: true);

index++;

lines.RemoveUntil(
index,
"[//]: # (endSnippet)",
relativePath,
line);
continue;
}
Comment on lines +261 to +273
Copy link

Copilot AI Mar 21, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Link-reference comment handling for web-snippets was added (ExtractLinkRefCommentWebSnippet / AppendWebSnippet(... useLinkRefFormat: true)), but there are no tests covering the overwrite and missing-snippet cases for the [//]: # (web-snippet: ...) format. Adding tests similar to WithCommentWebSnippetUpdate / LinkRefComment_Overwrite_Missing would help ensure the new marker format is preserved and endSnippet removal works as expected.

Copilot uses AI. Check for mistakes.

if (line.Current.TrimStart() == "<!-- toc -->")
{
tocLine = line;
Expand Down Expand Up @@ -292,14 +320,16 @@ bool ValidateContent(string? relativePath, Line line, List<ValidationError> vali
return true;
}

void ProcessSnippetLine(Action<string> appendLine, List<MissingSnippet> missings, List<Snippet> used, string key, string? relativePath, Line line)
void ProcessSnippetLine(Action<string> appendLine, List<MissingSnippet> missings, List<Snippet> used, string key, string? relativePath, Line line, bool useLinkRefFormat = false)
{
appendLine($"<!-- snippet: {key} -->");
var startMarker = useLinkRefFormat ? $"[//]: # (snippet: {key})" : $"<!-- snippet: {key} -->";
var endMarker = useLinkRefFormat ? "[//]: # (endSnippet)" : "<!-- endSnippet -->";
appendLine(startMarker);

if (TryGetSnippets(key, relativePath, line.Path, out var snippetsForKey))
{
appendSnippets(key, snippetsForKey, appendLine);
appendLine("<!-- endSnippet -->");
appendLine(endMarker);
used.AddRange(snippetsForKey);
return;
}
Expand All @@ -309,14 +339,19 @@ void ProcessSnippetLine(Action<string> appendLine, List<MissingSnippet> missings
appendLine("```");
appendLine($"** Could not find snippet '{key}' **");
appendLine("```");
appendLine("<!-- endSnippet -->");
appendLine(endMarker);
}

void ProcessWebSnippetLine(Action<string> appendLine, List<MissingSnippet> missings, List<Snippet> used, string url, string snippetKey, string? viewUrl, Line line)
void ProcessWebSnippetLine(Action<string> appendLine, List<MissingSnippet> missings, List<Snippet> used, string url, string snippetKey, string? viewUrl, Line line, bool useLinkRefFormat = false)
{
var commentText = viewUrl == null
? $"<!-- web-snippet: {url}#{snippetKey} -->"
: $"<!-- web-snippet: {url}#{snippetKey} {viewUrl} -->";
var endMarker = useLinkRefFormat ? "[//]: # (endSnippet)" : "<!-- endSnippet -->";
var commentText = useLinkRefFormat
? (viewUrl == null
? $"[//]: # (web-snippet: {url}#{snippetKey})"
: $"[//]: # (web-snippet: {url}#{snippetKey} {viewUrl})")
: (viewUrl == null
? $"<!-- web-snippet: {url}#{snippetKey} -->"
: $"<!-- web-snippet: {url}#{snippetKey} {viewUrl} -->");
appendLine(commentText);
// Download file content
try
Expand All @@ -329,7 +364,7 @@ void ProcessWebSnippetLine(Action<string> appendLine, List<MissingSnippet> missi
appendLine("```");
appendLine($"** Could not fetch or parse web-snippet '{url}#{snippetKey}' **");
appendLine("```");
appendLine("<!-- endSnippet -->");
appendLine(endMarker);
return;
}
// Extract snippets from content
Expand All @@ -343,7 +378,7 @@ void ProcessWebSnippetLine(Action<string> appendLine, List<MissingSnippet> missi
appendLine("```");
appendLine($"** Could not find snippet '{snippetKey}' in '{url}' **");
appendLine("```");
appendLine("<!-- endSnippet -->");
appendLine(endMarker);
return;
}
// Create new snippet with viewUrl if provided
Expand All @@ -359,7 +394,7 @@ void ProcessWebSnippetLine(Action<string> appendLine, List<MissingSnippet> missi
expressiveCode: found.ExpressiveCode,
viewUrl: viewUrl);
appendSnippets(snippetKey, [snippetToAppend], appendLine);
appendLine("<!-- endSnippet -->");
appendLine(endMarker);
used.Add(snippetToAppend);
}
catch
Expand All @@ -369,7 +404,7 @@ void ProcessWebSnippetLine(Action<string> appendLine, List<MissingSnippet> missi
appendLine("```");
appendLine($"** Could not fetch or parse web-snippet '{url}#{snippetKey}' **");
appendLine("```");
appendLine("<!-- endSnippet -->");
appendLine(endMarker);
}
}

Expand Down
82 changes: 82 additions & 0 deletions src/MarkdownSnippets/Processing/SnippetKey.cs
Original file line number Diff line number Diff line change
Expand Up @@ -158,4 +158,86 @@ public static bool IsStartCommentWebSnippetLine(string line) =>

public static bool IsStartCommentWebSnippetLine(CharSpan line) =>
line.StartsWith("<!-- web-snippet:", StringComparison.OrdinalIgnoreCase);

// [//]: # (snippet: key) format — link reference comment syntax for MDX compatibility

public static bool ExtractLinkRefCommentSnippet(Line line, [NotNullWhen(true)] out string? key)
{
var lineCurrent = line.Current.AsSpan().TrimStart();
if (!IsLinkRefCommentSnippetLine(lineCurrent))
{
key = null;
return false;
}

// after "[//]: # (snippet: " = 18 chars
var substring = lineCurrent[18..];
var indexOf = substring.IndexOf(")", StringComparison.Ordinal);
Comment on lines +164 to +175
Copy link

Copilot AI Mar 21, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ExtractLinkRefCommentSnippet slices lineCurrent[18..] after only checking StartsWith("[//]: # (snippet:"). That prefix does not require a space after the colon, so inputs like [//]: # (snippet:myKey) (no space) will be mis-parsed (first character of the key is dropped). Consider deriving the start index from the actual prefix length and then trimming optional whitespace after the colon (or parsing by finding "snippet:" and the closing ) rather than using a hard-coded offset).

Copilot uses AI. Check for mistakes.
if (indexOf < 0)
{
throw new SnippetException($"Could not find closing ')' in: {line.Original}. Path: {line.Path}. Line: {line.LineNumber}");
}

key = substring[..indexOf].Trim().ToString();
return true;
}

public static bool ExtractLinkRefCommentWebSnippet(Line line, [NotNullWhen(true)] out string? url, [NotNullWhen(true)] out string? snippetKey) =>
ExtractLinkRefCommentWebSnippet(line, out url, out snippetKey, out _);

public static bool ExtractLinkRefCommentWebSnippet(Line line, [NotNullWhen(true)] out string? url, [NotNullWhen(true)] out string? snippetKey, out string? viewUrl)
{
var lineCurrent = line.Current.AsSpan().TrimStart();
if (!IsLinkRefCommentWebSnippetLine(lineCurrent))
{
url = null;
snippetKey = null;
viewUrl = null;
return false;
}

// after "[//]: # (web-snippet: " = 22 chars
var substring = lineCurrent[22..];
Comment on lines +199 to +200
Copy link

Copilot AI Mar 21, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ExtractLinkRefCommentWebSnippet uses a hard-coded slice lineCurrent[22..] after checking StartsWith("[//]: # (web-snippet:"), which does not enforce a space after the colon. If a user writes [//]: # (web-snippet:https://...#key) the URL will be truncated by one character. Recommend parsing based on the actual prefix length and trimming optional whitespace, instead of relying on a fixed offset.

Suggested change
// after "[//]: # (web-snippet: " = 22 chars
var substring = lineCurrent[22..];
const string prefix = "[//]: # (web-snippet:";
var substring = lineCurrent[prefix.Length..].TrimStart();

Copilot uses AI. Check for mistakes.
var indexOf = substring.IndexOf(")", StringComparison.Ordinal);
if (indexOf < 0)
{
throw new SnippetException($"Could not find closing ')' in: {line.Original}. Path: {line.Path}. Line: {line.LineNumber}");
}

var value = substring[..indexOf].Trim();

// Check for optional second URL separated by whitespace
var firstSpaceIndex = value.IndexOfAny([' ', '\t']);
CharSpan firstPart;
if (firstSpaceIndex >= 0)
{
firstPart = value[..firstSpaceIndex];
var secondPart = value[(firstSpaceIndex + 1)..].TrimStart();
var nextSpace = secondPart.IndexOfAny([' ', '\t']);
viewUrl = (nextSpace >= 0 ? secondPart[..nextSpace] : secondPart).ToString();
}
else
{
firstPart = value;
viewUrl = null;
}

var hashIndex = firstPart.LastIndexOf('#');
if (hashIndex < 0 || hashIndex == firstPart.Length - 1)
{
url = null;
snippetKey = null;
viewUrl = null;
return false;
}
url = firstPart[..hashIndex].ToString();
snippetKey = firstPart[(hashIndex + 1)..].ToString();
return true;
}

public static bool IsLinkRefCommentSnippetLine(CharSpan line) =>
line.StartsWith("[//]: # (snippet:", StringComparison.OrdinalIgnoreCase);

public static bool IsLinkRefCommentWebSnippetLine(CharSpan line) =>
line.StartsWith("[//]: # (web-snippet:", StringComparison.OrdinalIgnoreCase);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
{
UsedSnippets: [
{
Key: snippet1,
Language: cs,
Value: Snippet,
Error: ,
FileLocation: thePath(1-2),
IsInError: false
},
{
Key: snippet2,
Language: cs,
Value: Snippet,
Error: ,
FileLocation: thePath(1-2),
IsInError: false
}
],
result:
[//]: # (snippet: snippet1)
```cs
Snippet
```
[//]: # (endSnippet)

some text

[//]: # (snippet: snippet2)
```cs
Snippet
```
[//]: # (endSnippet)

some other text
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
MissingSnippets: [
{
Key: missingKey,
LineNumber: 2
}
],
result:
[//]: # (snippet: missingKey)
```
** Could not find snippet 'missingKey' **
```
[//]: # (endSnippet)
}
Loading
Loading