Markdown parser
This page demonstrates how to use FSharp.Formatting.Markdown to parse a Markdown
document, process the obtained document representation, and
how to turn the code into a nicely formatted HTML.
First, we need to load the assembly and open the necessary namespaces:
open FSharp.Formatting.Markdown
open FSharp.Formatting.Common
Parsing documents
The F# Markdown parser recognizes the standard Markdown syntax and it is not the aim of this tutorial to fully document it. The following snippet creates a simple string containing a document with several elements and then parses it using the Markdown.Parse method:
let document =
"""
# F# Hello world
Hello world in [F#](http://fsharp.net) looks like this:
printfn "Hello world!"
For more see [fsharp.org][fsorg].
[fsorg]: http://fsharp.org "The F# organization." """
let parsed = Markdown.Parse(document)
The sample document consists of a first-level heading (written using one of the two alternative styles) followed by a paragraph with a direct link, code snippet and one more paragraph that includes an indirect link. The URLs of indirect links are defined by a separate block as demonstrated on the last line (and they can then be easily used repeatedly from multiple places in the document).
Working with parsed documents
The F# Markdown processor does not turn the document directly into HTML. Instead, it builds a nice F# data structure that we can use to analyze, transform and process the document. First of all the MarkdownDocument.DefinedLinks property returns all indirect link definitions:
parsed.DefinedLinks
val it : IDictionary<string,(string * string option)> =
dict [("fsorg", ("http://fsharp.org", Some "The F# organization."))]
The document content can be accessed using the MarkdownDocument.Paragraphs property that returns a sequence of paragraphs or other first-level elements (headings, quotes, code snippets, etc.). The following snippet prints the heading of the document:
// Iterate over all the paragraph elements
for par in parsed.Paragraphs do
match par with
| Heading (size = 1; body = [ Literal (text = text) ]) ->
// Recognize heading that has a simple content
// containing just a literal (no other formatting)
printfn "%s" text
| _ -> ()
You can find more detailed information about the document structure and how to process it in the book F# Deep Dives.
Processing the document recursively
The library provides active patterns that can be used to easily process the Markdown document recursively. The example in this section shows how to extract all links from the document. To do that, we need to write two recursive functions. One that will process all paragraph-style elements and one that will process all inline formattings (inside paragraphs, headings etc.).
To avoid pattern matching on every single kind of span and every single kind of paragraph, we can use active patterns from the MarkdownPatterns module. These can be use to recognize any paragraph or span that can contain child elements:
/// Returns all links in a specified span node
let rec collectSpanLinks span =
seq {
match span with
| DirectLink (link = url) -> yield url
| IndirectLink (key = key) -> yield fst (parsed.DefinedLinks.[key])
| MarkdownPatterns.SpanLeaf _ -> ()
| MarkdownPatterns.SpanNode (_, spans) ->
for s in spans do
yield! collectSpanLinks s
}
/// Returns all links in the specified paragraph node
let rec collectParLinks par =
seq {
match par with
| MarkdownPatterns.ParagraphLeaf _ -> ()
| MarkdownPatterns.ParagraphNested (_, pars) ->
for ps in pars do
for p in ps do
yield! collectParLinks p
| MarkdownPatterns.ParagraphSpans (_, spans) ->
for s in spans do
yield! collectSpanLinks s
}
// Collect links in the entire document
Seq.collect collectParLinks parsed.Paragraphs
val it : seq<string> =
seq ["http://fsharp.net"; "http://fsharp.org"]
The collectSpanLinks function works on individual span elements that contain inline
formatting (emphasis, strong) and also links. The DirectLink node from MarkdownSpan represents an inline
link like the one pointing to http://fsharp.net while IndirectLink represents a
link that uses one of the link definitions. The function simply returns the URL associated
with the link.
Some span nodes (like emphasis) can contain other formatting, so we need to recursively
process children. This is done by matching against MarkdownPatterns.SpanNodes which is an active
pattern that recognizes any node with children. The library also provides a function
named MarkdownPatterns.SpanNode that can be used to reconstruct the same node (when you want
to transform a document). This is similar to how the ExprShape module for working with
F# quotations works.
The function collectParLinks processes paragraphs - a paragraph cannot directly be a
link so we just need to process all spans. This time, there are three options.
ParagraphLeaf represents a case where the paragraph does not contain any spans
(a code block or, for example, a <hr> line); the ParagraphNested case is used for paragraphs
that contain other paragraphs (quotation) and ParagraphSpans is used for all other
paragraphs that contain normal text - here we call collectSpanLinks on all nested spans.
Generating HTML output
Finally, the Markdown type also includes a method Markdown.ToHtml that can be used to generate an HTML document from the Markdown input. The following example shows how to call it:
let html = Markdown.ToHtml(parsed)
There are also methods to generate .fsx, .ipynb, .md and .tex.
namespace FSharp
--------------------
namespace Microsoft.FSharp
and transforming Markdown documents.
type Markdown =
static member Parse:
text: string *
?newline: string *
?parseOptions: MarkdownParseOptions ->
MarkdownDocument
static member ToFsx:
doc: MarkdownDocument *
?newline: string *
?substitutions: (ParamKey * string) list *
?crefResolver: (string -> (string * string) option) *
?mdlinkResolver: (string -> string option) ->
string
static member ToHtml: doc: MarkdownDocument * ?newline: string * ?substitutions: (ParamKey * string) list * ?crefResolver: (string -> (string * string) option) * ?mdlinkResolver: (string -> string option) -> string + 1 overload
static member ToLatex: doc: MarkdownDocument * ?newline: string * ?substitutions: (ParamKey * string) list * ?crefResolver: (string -> (string * string) option) * ?mdlinkResolver: (string -> string option) * ?lineNumbers: bool -> string + 1 overload
static member ToMd:
doc: MarkdownDocument *
?newline: string *
?substitutions: (ParamKey * string) list *
?crefResolver: (string -> (string * string) option) *
?mdlinkResolver: (string -> string option) ->
string
static member ToPynb:
doc: MarkdownDocument *
?newline: string *
?substitutions: (ParamKey * string) list *
?crefResolver: (string -> (string * string) option) *
?mdlinkResolver: (string -> string option) ->
string
static member WriteHtml: doc: MarkdownDocument * writer: TextWriter * ?newline: string * ?substitutions: (ParamKey * string) list * ?crefResolver: (string -> (string * string) option) * ?mdlinkResolver: (string -> string option) -> unit + 1 overload
static member WriteLatex: doc: MarkdownDocument * writer: TextWriter * ?newline: string * ?substitutions: (ParamKey * string) list * ?crefResolver: (string -> (string * string) option) * ?mdlinkResolver: (string -> string option) * ?lineNumbers: bool -> unit + 1 overload
text: string *
?newline: string *
?parseOptions: MarkdownParseOptions ->
MarkdownDocument
property MarkdownDocument.DefinedLinks: System.Collections.Generic.IDictionary<string,(string * string option)> with get
property MarkdownDocument.Paragraphs: MarkdownParagraphs with get
size: int *
body: MarkdownSpans *
range: MarkdownRange ->
MarkdownParagraph
union case MarkdownSpan.Literal:
text: string *
range: MarkdownRange ->
MarkdownSpan
--------------------
type LiteralAttribute =
inherit Attribute
new: unit -> LiteralAttribute
--------------------
new: unit -> LiteralAttribute
val collectSpanLinks: span: MarkdownSpan -> string seq
val seq: sequence: 'T seq -> 'T seq
--------------------
type 'T seq = System.Collections.Generic.IEnumerable<'T>
body: MarkdownSpans *
link: string *
title: string option *
range: MarkdownRange ->
MarkdownSpan
body: MarkdownSpans *
original: string *
key: string *
range: MarkdownRange ->
MarkdownSpan
It lets you decompose documents into leafs and nodes with nested paragraphs.
module MarkdownPatterns
from FSharp.Formatting.Markdown
Reconstructs a leaf span from its SpanLeafInfo tag
val SpanLeaf: MarkdownPatterns.SpanLeafInfo -> MarkdownSpan
--------------------
Active pattern that classifies a MarkdownSpan as either a leaf (no children) or a node (with children)
active recognizer SpanLeaf:
MarkdownSpan ->
Choice<MarkdownPatterns.SpanLeafInfo,(MarkdownPatterns.SpanNodeInfo * MarkdownSpans)>
Reconstructs a node span from its SpanNodeInfo tag and a (possibly updated) child span list
val SpanNode:
MarkdownPatterns.SpanNodeInfo *
spans: MarkdownSpans ->
MarkdownSpan
--------------------
Active pattern that classifies a MarkdownSpan as either a leaf (no children) or a node (with children)
active recognizer SpanNode:
MarkdownSpan ->
Choice<MarkdownPatterns.SpanLeafInfo,(MarkdownPatterns.SpanNodeInfo * MarkdownSpans)>
val collectParLinks: par: MarkdownParagraph -> string seq
Reconstructs a leaf paragraph from its ParagraphLeafInfo tag
val ParagraphLeaf: MarkdownPatterns.ParagraphLeafInfo -> MarkdownParagraph
--------------------
Active pattern that classifies a MarkdownParagraph as spans-container, leaf, or nested-paragraphs container
active recognizer ParagraphLeaf:
MarkdownParagraph ->
Choice<MarkdownPatterns.ParagraphLeafInfo,(MarkdownPatterns.ParagraphNestedInfo * MarkdownParagraphs list),(MarkdownPatterns.ParagraphSpansInfo * MarkdownSpans)>
Reconstructs a nested-paragraph container with an updated flat list of child paragraphs
val ParagraphNested:
MarkdownPatterns.ParagraphNestedInfo *
pars: MarkdownParagraphs list ->
MarkdownParagraph
--------------------
Active pattern that classifies a MarkdownParagraph as spans-container, leaf, or nested-paragraphs container
active recognizer ParagraphNested:
MarkdownParagraph ->
Choice<MarkdownPatterns.ParagraphLeafInfo,(MarkdownPatterns.ParagraphNestedInfo * MarkdownParagraphs list),(MarkdownPatterns.ParagraphSpansInfo * MarkdownSpans)>
Reconstructs a spans-container paragraph with an updated span list
val ParagraphSpans:
MarkdownPatterns.ParagraphSpansInfo *
spans: MarkdownSpans ->
MarkdownParagraph
--------------------
Active pattern that classifies a MarkdownParagraph as spans-container, leaf, or nested-paragraphs container
active recognizer ParagraphSpans:
MarkdownParagraph ->
Choice<MarkdownPatterns.ParagraphLeafInfo,(MarkdownPatterns.ParagraphNestedInfo * MarkdownParagraphs list),(MarkdownPatterns.ParagraphSpansInfo * MarkdownSpans)>
from Microsoft.FSharp.Collections
markdownText: string *
?newline: string *
?substitutions: (FSharp.Formatting.Templating.ParamKey * string) list *
?crefResolver: (string -> (string * string) option) *
?mdlinkResolver: (string -> string option) ->
string
static member Markdown.ToHtml:
doc: MarkdownDocument *
?newline: string *
?substitutions: (FSharp.Formatting.Templating.ParamKey * string) list *
?crefResolver: (string -> (string * string) option) *
?mdlinkResolver: (string -> string option) ->
string
FSharp.Formatting