A dotnet tool or MsBuild Task that extract snippets from code files and merges them into markdown documents.
See Milestones for release notes.
.net 8 or higher is required to run the dotnet tool.
Automatically extract snippets from code and injecting them into markdown documents has several benefits:
- Snippets can be verified by a compiler or parser.
- Tests can be run on snippets, or snippets can be pulled from existing tests.
- Changes in code are automatically reflected in documentation.
- Snippets are less likely to get out of sync with the main code-base.
- Snippets in markdown is easier to create and maintain since any preferred editor can be used to edit them.
- Recursively scan the target directory for code files containing snippets. (See exclusion).
- Recursively scan the target directory for markdown (
.mdormdx) files. (See Document Scanning). - Merge the snippets into those markdown files.
Ensure dotnet CLI is installed.
Install MarkdownSnippets.Tool
dotnet tool install -g MarkdownSnippets.ToolSee also: MsBuild Task usage
mdsnippets C:\Code\TargetDirectoryIf no directory is passed the current directory will be used, but only if it exists with a git repository directory tree. If not an error is returned.
There are two approaches scanning and modifying markdown files.
This is the default.
The file convention recursively scans the target directory for all *.source.md files. Once snippets are merged the .source.md to produce .md files. So for example readme.source.md would be merged with snippets to produce readme.md. Note that this process will overwrite any existing .md files that have matching .source.md files.
There is a secondary convention that leverages the use of a directory named mdsource. Where .source.md files are placed in a mdsource sub-directory, the mdsource part of the file path will be removed when calculating the target path. This allows the .source.md to be grouped in a sub directory and avoid cluttering up the main documentation directory.
When using the mdsource convention, all references to other files, such as links and images, should specify the full path from the root of the repository. This will allow those links to work correctly in both the source and generated markdown files. Relative paths cannot work for both the source and the target file.
Recursively scans the target directory for all *.md files and merges snippets into those files.
mdsnippets -c InPlaceOverwritemdsnippets --convention InPlaceOverwriteCan be enabled in mdsnippets.json config file.
{
"Convention": "InPlaceOverwrite"
}- Ensure
"WriteHeader": falseis used inmdsnippets.json. - Ensure
"ReadOnly": falseis used inmdsnippets.json. - Ensure using the current stable version and a docs generation has run.
- Delete all
.source.mdfiles. - Modify
mdsnippets.jsonto add"Convention": "InPlaceOverwrite". - Run the docs generation.
To mark the resulting documents files as read only use -r or --read-only.
This can be helpful in preventing incorrectly editing the documents file instead of the .source. file conventions.
mdsnippets -r truemdsnippets --read-only trueAny code wrapped in a convention based comment will be picked up. The comment needs to start with begin-snippet: which is followed by the key. The snippet is then terminated by end-snippet.
// begin-snippet: MySnippetName
My Snippet Code
// end-snippet
Named C# regions will also be picked up, with the name of the region used as the key.
To stop regions collapsing in Visual Studio disable 'enter outlining mode when files open'. See Visual Studio outlining.
Urls to files to be included as snippets. Space separated for multiple values.
Each url will be accessible using the file name as a key. Any snippets within the files will be extracted and accessible as individual keyed snippets.
mdsnippets --urls-as-snippets "https://github.com/SimonCropp/MarkdownSnippets/snippet.cs"mdsnippets -u "https://github.com/SimonCropp/MarkdownSnippets/snippet.cs"The keyed snippets can be used in any documentation .md file by adding the text snippet: KEY.
Then snippets with that key.
For example
Some blurb about the below snippet snippet: MySnippetName
The resulting markdown will be:
Some blurb about the below snippet
<!-- snippet: MySnippetName -->
<a id='snippet-MySnippetName'></a>
```
My Snippet Code
```
<sup><a href='/relativeUrlToFile#L1-L11' title='Snippet source file'>snippet source</a> | <a href='#snippet-MySnippetName' title='Start of snippet'>anchor</a></sup>
<!-- endSnippet -->
Notes:
- The vertical bar ( | ) is used to separate adjacent links as per web accessibility recommendations: https://webaim.org/techniques/hypertext/hypertext_links#groups
- H33: Supplementing link text with the title attribute
Snippets that start with http will be downloaded and the contents rendered. For example:
snippet: https://raw.githubusercontent.com/SimonCropp/MarkdownSnippets/master/license.txt
Will render:
<!-- snippet: https://raw.githubusercontent.com/SimonCropp/MarkdownSnippets/master/license.txt -->
<a id='snippet-https://raw.githubusercontent.com/SimonCropp/MarkdownSnippets/master/license.txt'></a>
```txt
The MIT License (MIT)
...
```
<sup><a href='#snippet-https://raw.githubusercontent.com/SimonCropp/MarkdownSnippets/master/license.txt' title='Snippet source file'>anchor</a></sup>
<!-- endSnippet -->
Files are downloaded to %temp%MarkdownSnippets with a maximum of 100 files kept.
web-snippet: can be used to reference remote content where a specific snippet is defined in that content.
web-snippet: https://raw.githubusercontent.com/SimonCropp/MarkdownSnippets/main/src/Tests/DirectorySnippetExtractor/Case/code1.txt#snipPet
Will render:
<!-- web-snippet: https://raw.githubusercontent.com/SimonCropp/MarkdownSnippets/main/src/Tests/DirectorySnippetExtractor/Case/code1.txt#snipPet -->
<a id='snippet-snipPet'></a>
```txt
Some code
```
<sup><a href='#snippet-snipPet' title='Start of snippet'>anchor</a></sup>
<!-- endSnippet -->
If no snippet is found matching the defined name. The target directory will be searched for a file matching that name. For example:
snippet: license.txt
Will render:
<!-- snippet: license.txt -->
<a id='snippet-license.txt'></a>
```txt
The MIT License (MIT)
Copyright (c) 2013 Simon Cropp
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
```
<sup><a href='/license.txt#L1-L20' title='Snippet source file'>snippet source</a> | <a href='#snippet-license.txt' title='Start of snippet'>anchor</a></sup>
<!-- endSnippet -->
Defines the format of snippet source links that appear under each snippet.
mdsnippets --link-format Bitbucketmdsnippets -l Bitbucketnamespace MarkdownSnippets;
public enum LinkFormat
{
GitHub,
Tfs,
Bitbucket,
GitLab,
DevOps,
None
}Link format None will omit the source link but still keep the snippet anchor.
The links below a snippet can be omitted.
mdsnippets --omit-snippet-links true{
"OmitSnippetLinks": true
}
switch (linkFormat)
{
case LinkFormat.GitHub:
Polyfill.Append(builder, $"{path}#L{snippet.StartLine}-L{snippet.EndLine}");
return;
case LinkFormat.Tfs:
Polyfill.Append(builder, $"{path}&line={snippet.StartLine}&lineEnd={snippet.EndLine}");
return;
case LinkFormat.Bitbucket:
Polyfill.Append(builder, $"{path}#lines={snippet.StartLine}:{snippet.EndLine}");
return;
case LinkFormat.GitLab:
Polyfill.Append(builder, $"{path}#L{snippet.StartLine}-{snippet.EndLine}");
return;
case LinkFormat.DevOps:
Polyfill.Append(builder, $"?path={path}&line={snippet.StartLine}&lineEnd={snippet.EndLine}&lineStartColumn=1&lineEndColumn=999");
return;
case LinkFormat.None:
throw new($"Unknown LinkFormat: {linkFormat}");
}UrlPrefix allows a string to be defined that will prefix all snippet links. This is helpful when the markdown file are being hosted on a site that is not co-located with the source code files. It can be defined in the config file, the MsBuild task, and the dotnet tool.
mdsnippets --url-prefix "TheUrlPrefix"{
"UrlPrefix": "TheUrlPrefix"
}
Use src/context-menu.reg to add MarkdownSnippets to the Windows Explorer context menu.
Windows Registry Editor Version 5.00
[HKEY_CLASSES_ROOT\Directory\Shell]
@="none"
[HKEY_CLASSES_ROOT\Directory\shell\mdsnippets]
"MUIVerb"="run mdsnippets"
"Position"="bottom"
[HKEY_CLASSES_ROOT\Directory\Background\shell\mdsnippets]
"MUIVerb"="run mdsnippets"
"Position"="bottom"
[HKEY_CLASSES_ROOT\Directory\shell\mdsnippets\command]
@="cmd.exe /c mdsnippets \"%V\""
[HKEY_CLASSES_ROOT\Directory\Background\shell\mdsnippets\command]
@="cmd.exe /c mdsnippets \"%V\""When defining snippets, additional metadata can be added at the source to the rendered snippet using the following syntax.
// begin-snippet: HelloWorld(title=Program.cs {1})
Console.WriteLine("Hello, World");
// end-snippetNote the text within the parenthesis; this is metadata we want to add to the rendered Markdown block immediately after the language declaration. The metadata is stripped and the key remains HelloWorld. The feature produces the following output destination (will vary based on configuration):
<-- begin-snippet: HelloWorld -->
```csharp title=Program.cs {1}
Console.WriteLine("Hello, World");
```
<-- end-snippet -->This syntax is known as Expressive Code and is supported in documentation systems such as Astro Starlight but can be installed in any Markdown-powered tool that supports reHype.
It is important to note, the metadata is not explicitly limited to Expressive code. Any text within the () will be rendered after the language block. This can be useful for adding additional information based on specific rendering engine. For example, if a presentation tool such as Sli.dev, then this feature to apply magic-move animations.
// begin-snippet: EncapsulateVariable({*|2})
Console.WriteLine("Hello, World");
// end-snippetThe above snippet will render as follows:
<-- begin-snippet: EncapsulateVariable -->
```csharp {*|2}
Console.WriteLine("Hello, World");
```
<-- end-snippet -->- Developer Information
- Customisation
- Writing Documentation
Loosely based on some code from https://github.com/shiftkey/scribble.
Down by Alfredo Creates from The Noun Project.