Spec Markdown

Renders Markdown with some additions into an HTML format commonly used for writing technical specification documents. Markdown additions include code syntax highlighting, edit annotations, and the definition of algorithms and grammar productions.

Philosophy

Spec Markdown is first and foremost Markdown. As such, it follows Markdown’s philosophy of intending to be as easy to read and easy to write as is feasible.

In order to interoperate with other tools which use Markdown, Spec Markdown tries to add as little additional syntax as possible, instead preferring conventions. This means any documents written with Spec Markdown in mind should render adequately by other Markdown renderers.

To support the rendering additions of Spec Markdown, some features of Markdown may be limited or removed. As an example, Spec Markdown is strict about the order and locations of headers in a document.

Note This is not a normative spec for Spec Markdown, but just documentation of this tool. Of course, written in Spec Markdown!

1Getting Started

To use Spec Markdown, just write Markdown files. There are some conventions used by Spec Markdown which you can read about in Spec additions.

To convert your Markdown files into an HTML spec document, use the spec-md utility.

npm install -g spec-md
spec-md ./path/to/markdown.md > ./path/to/output.html

You can also require spec-md as a node module.

npm install --save-dev spec-md
const fs = require('fs');
const specMarkdown = require('spec-md');
specMarkdown.html('./path/to/markdown.md').then(html => {
  fs.writeFile('./path/to/output.html', html);
});

Spec Markdown also provides utilities for generating and operating on an intermediate representation of the markdown, which you can explore in Using Spec Markdown.

2Markdown

Spec Markdown is first and foremost Markdown. More specifically, it’s based on Github-flavored Markdown.

This section explains the syntax and capabilities of Markdown that Spec Markdown supports and augments.

2.1Character Encoding

Markdown allows you to write text which uses &, <, and >. The output HTML will automatically use the &amp;, &lt;, and &gt; entities.

Well formed HTML entities can be written inline directly. If you write &copy;, it will appear in the HTML output as ©.

2.1.1Escape sequence

Markdown makes use of certain characters to format text, in order to render one explicitly, place a backslash before it.

You can type *literal asterisks* instead of emphasis by typing \*literal asterisks\*.

Escaping does not apply within code.

Spec Markdown allows backslash escapes for any ASCII punctuation character.

\!\"\#\$\%\&\'\(\)\*\+\,\-\.\/\:\;\<\=\>\?\@\[\\\]\^\_\`\{\|\}\~

Produces the following:

!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~

2.2Inline formatting

Markdown allows for inline stylistic and structual formatting. Inline formatting is allowed in paragraphs, list items, and table cells.

2.2.1Inline HTML

Markdown is not a replacement for HTML and instead leverages HTML by allowing its use inline within paragraphs, links, etc.

This code has blinking and emphasized formatting.

Markdown syntax can continue to be used within inline HTML.

2.2.3Emphasis

Wrapping asterisks (*) indicate emphasis.

Example of **bold** and *italic* and ***bold italic***.

Produces the following:

Example of bold and italic and bold italic.

Alternatively, use underscore (_) for italic emphasis.

Example of _italic_ and **_bold italic_** or _**bold italic**_.

Produces the following:

Example of italic and bold italic or bold italic.

2.2.4Inline Code

Wrapping back-ticks (`) indicate inline code, text inside back-ticks is not formatted, allowing for special characters to be used in inline code without escapes.

This is an `example` of some inline code.

Produces

This is an example of some inline code.

Inline code can also use double- or triple-backticks. Wrapping spaces are removed.

`` ` `` Produces `

2.2.5Images

![Specs](http://i.imgur.com/aV8o3rE.png)

Produces the following:

Specs

2.3Blocks

Markdown allows for block-level structual formatting. Every block is seperated by at least two new lines. Spec Markdown makes use of Markdown’s blocks to produce more specific structural formatting.

2.3.1Block HTML

Markdown is not a replacement for HTML and instead leverages HTML by allowing its use as complete blocks when separated from surrounding content by blank lines.

Note Markdown formatting syntax is not processed within block-level HTML tags.

For example, to add an HTML table to a Markdown article:

Unrelated previous paragraph followed by a blank line

<table>
<tr>
<td>Table cell</td>
<td>

<table>
<tr>
<td>*Tables in tables*</td>
</tr>
</table>

</td>
</tr>
</table>

Produces the following:

Unrelated previous paragraph followed by a blank line

Table cell
*Tables in tables*

And using <pre> produces a simple code block:

<pre>
Buffalo Bill ’s
defunct
       who used to
       ride a watersmooth-silver
                                stallion
and break onetwothreefourfive pigeonsjustlikethat
                                                 Jesus
he was a handsome man
                     and what i want to know is
how do you like your blueeyed boy
Mister Death
</pre>

Produces the following:

Buffalo Bill ’s
defunct
       who used to
       ride a watersmooth-silver
                                stallion
and break onetwothreefourfive pigeonsjustlikethat
                                                 Jesus
he was a handsome man
                     and what i want to know is
how do you like your blueeyed boy
Mister Death

2.3.2Section Headers

Regular Markdown supports two styles of headers, Setext and atx, however Spec Markdown generally only supports atx style headers.

Example № 1# Header

Setext headers are not supported by Spec Markdown.

Counter Example № 2Header
------

The number of # characters refers to the depth of the section. To produce an, <h3>, type ###. Optionally, a header may be “closed” by any number of # characters.

Note Spec Markdown requires that documents start with a header.

2.3.3Paragraphs

Paragraphs are the most simple Markdown blocks. Lines are appended together to form a single <p> tag. Any inline syntax is allowed within a paragraph.

2.3.4Lists

Markdown lists are lines which each start with either a ordered bullet 1. or unordered bullet, *, -, or +. Lists are optionally indented by two spaces.

Lists can be nested within other lists by indenting by at least two spaces.

Example № 3  1. this
  2. is
  3. a
    - nested
  4. list

Produces the following:

  1. this
  2. is
  3. a
    • nested
  4. list

2.3.4.1Task Lists

Spec Markdown also supports task lists. Start a list item with [ ] or [x] to render a checkbox. This can be useful for keeping your tasks inline with in-progress draft specifications.

Example № 4  1. this
  2. [ ] is
  3. [x] a
    - [X] nested
  4. todo list

Produces the following:

  1. this
  2. is
  3. a
    • nested
  4. todo list

2.3.5Code Block

A block of code is formed by either indenting by 4 spaces, or wrapping with ``` on their own lines.

```
const code = sample();
```

Produces the following:

const code = sample();

2.3.6Block Quotes

Spec markdown does not yet support Markdown’s > style block quotes.

2.3.7Horizontal Rules

Spec Markdown does not yet support Markdown’s --- style <hr>.

3Spec Additions

Spec Markdown makes some additions to Markdown to support cases relevant to writing technical specs and documentation. It attempts to be as minimally invasive as possible, leveraging existing Markdown formatting features whenever possible so Spec Markdown documents may render adequately as regular Markdown.

Spec Markdown also makes restrictions to the overall format of the Markdown document in order to derive a structure to the entire document.

3.2Title and Introduction

A Spec Markdown document must start with a header which will be used as the title of the document. Any content between this and the next header will become the introduction to the document.

A Spec Markdown document starts in this form:

# Spec Markdown

Introductory paragraph.

# First Section Header
Note For backwards-compatibility, a setext style header can be used for a document title.

3.3Sections

A Spec Markdown document is separated into a sequence and hierarchy of sections. Those sections can then be used as navigation points and can be used to create a table of contents. A section is started by a header and ends at either the next header of similar or greater precedence or the end of the document. A section can contain other sections if their headers are of lower precedence.

3.3.1Section Headers

Regular Markdown supports two styles of headers, Setext and atx, however Spec Markdown only supports atx style headers as section headers.

# Header

Only use Setext style headers for the title of the document.

Counter Example № 5Header
------

3.3.2Subsection Headers

While sections are numbered and appear in the table of contents, a subsection is similar but not numbered or in the table of contents.

This is a subsection

The subsection’s content appears below the subsection header.

Another subsection

Sections may contain multiple subsections, but subsections cannot contain sections or subsections.

3.3.3Table of Contents

A table of contents is automatically generated from the hierarchy of sections in the Spec Markdown document.

3.3.4Section Numbers

A number is associated with each section, starting with 1. In a hierarchy of sections, the parent sections are joined with dots. This provides an unambiguous location identifier for a given section in a document.

You can specify these section numbers directly in your Markdown documents if you wish by writing them directly after the # and before the text of the header.

3.3.4.8Custom Numbers

If the section number is written in the document, the last number will be used as the number for that section. This is useful when writing a proposal against an existing spec and wish to reference a particular section.

The header for this section was written as

#### 3.2.3.8. Custom Numbers

3.3.4.9Appendix / Annex Sections

If a top level section is written with a letter, such as A instead of a number, that will begin an Appendix section.

# A. Appendix: Grammar

3.4Smart Characters

The Spec Markdown renderer will replace easy to type characters like quotes and dashes with their appropriate typographic entities. These replacements will not occur within blocks of code.

3.4.1Quotes and Dashes

Prose text has “smart quotes”, hyphens, en-dashes and em-dashes—you shouldn’t have to think about it, they’ll just work.

For example, a quote of a quote (with an inner apostrophe and emphasis for flair):

"She told me that 'he isn't here right *now*' - so I left."

Will render as:

“She told me that ‘he isn’t here right now’ – so I left.”

Escaped \"quotes \'and single\-quotes\'\" becomes: \“quotes \‘and single-quotes'".

3.4.2Math

Math operators like ≥, ≤, and ≈ can be written as >=, <=, and ~=.

Escaped \>= \<= \~= becomes: >= <= ~=.

3.4.3Arrows

Smart arrows → and ← and ↔ can be written as ->, <- and <->.

Fat smart arrows ⇒ and ⇐ and ⇔ can be written as =>, <== and <=>.

Escaped \-> \<- \<-> \=> \<== \<=> becomes: -> <- <-> => <== <=>.

3.5Tables

Similar to Github flavored Markdown

| This | is a | table |
| ---- | ---: | :---: |
| key  | val  | etc   |

Produces the following:

This is a table
key val etc

Table cells can contain any content that a paragraph can contain.

3.6Comments

Spec Markdown will ignore HTML style comments before or within blocks of text. By default these comments are omitted from the resulting HTML, but can be included by passing the option --includeComments when calling spec-md.

For example this paragraph:

This is a <!-- comment inside of a --> paragraph.

Produces the following:

This is a paragraph.

3.7Definitions

Spec Markdown provides two forms for defining terms, definition lists and definition paragraphs.

3.7.1Definition List

A definition list is written as a defined term on a single line followed by one or more definition lines, each starting with a : .

Cookie
:   A small piece of data that a server sends to the user's web browser. The
    browser may store it and send it back with later requests to the same server.
:   A delicious snack, often containing chocolate chips.

Produces the following:

Cookie
A small piece of data that a server sends to the user’s web browser. The browser may store it and send it back with later requests to the same server.
A delicious snack, often containing chocolate chips.
Note Term definitions can optionally be separated by a single blank line.

3.7.2Definition Paragraph

A definition paragraph starts with a :: and contains an italicized term. This is useful when it is easier to define a term in a sentence containing that term.

:: The study of *Philosophy* investigates general and fundamental questions.

Produces the following:

The study of Philosophy investigates general and fundamental questions.

3.7.3Definition References

A defined term can be later referenced by italicizing that term. Referenced terms are case insensitive.

After studying *philosophy*, you may eat a *cookie*.

Produces the following:

After studying philosophy, you may eat a cookie.

3.8Note

Notes can be written inline with a spec document, and are often helpful to supply non-normative explanatory text or caveats in a differently formatted style. Case insensitive, the : is optional.

Notes automatically have short links generated for them. If the contents of the note changes, so will the link URL. However if a note moves around, or content around the note changes the existing links will still point to the right place, very useful for consistently evolving specifications!

Note: Notes are awesome.

Produces the following:

Note Notes are awesome.

3.9Todo

It’s often helpful to write a draft of a document and leave “to-do” comments in not-yet-completed sections. Case insensitive, the : is optional.

TODO: finish this section

Produces the following:

finish this section
Note You can also write TK in place of TODO, nerds.

3.10Syntax Highlighting

Spec Markdown will apply syntax highlighting to blocks of code if a github-flavored-markdown style language is supplied.

You may provide a highlight function as an option to customize this behavior.

To render this highlighted javascript:

```js
const baz = foo("bar");
```

Produces the following:

const baz = foo("bar");

You may also prefix your highlight function with “raw” if you want to avoid other tools, such as Prettier, from interpreting a code block.

```raw js
const baz = foo("bar");
```

Produces the following:

const baz = foo("bar");

3.10.1Examples

Spec Markdown helps you write examples, visually indicaticating the difference from normative code blocks, and generating permalinks to those examples. Just write example after the ```.

```example
const great = useOf.example("code");
```

Produces the following:

Example № 6const great = useOf.example("code");

Examples can also be syntax highlighted, by placing the language directly before writing example:

```js example
const great = useOf.example("code");
```

Produces the following:

Example № 7const great = useOf.example("code");

3.10.2Counter Examples

In addition to examples, Spec Markdown helps you write counter-examples, which are examples of things you should not do. These are visually indicated as different from normative code blocks and other examples. Just write counter-example after the ``` (and optional language).

```js counter-example
const shit = dontSwear();
```

Produces the following:

Counter Example № 8const shit = dontSwear();

3.11Imports

When compiled, an import reference will be inlined into the same document. An import reference looks like a link to a “.md” file as a single paragraph.

[AnythingGoesHere](SomeName.md)

You can optionally prefix the import reference with # characters to describe at what section level the import should apply. By default an import reference will be imported as a child of the current section.

3.12Inline editing

A portion of the CriticMarkup spec is supported.

For example, we can add or remove text with the {++add++} or {--remove--} syntax.

3.13Block editing

We can also add and remove entire blocks of content, by using {++ or {-- on their own line with empty lines on either side:

These paragraphs

have been added.

And

These paragraphs

have been removed.

By typing:

{++

These paragraphs

have been *added*.

++}

And

{--

These paragraphs

have been *removed*.

--}
Note imports and section headers cannot be included in a added or removed section to preserve the ability to render a table of contents.

3.14Algorithms

Specifications for procedures or algorithms can be defined in terms of nested markdown lists. These lists can be of any kind, but will always have ordered formatting. The bullet labeling for algorithms is specific will cycle between decimal, lower-alpha, and lower-roman.

An algorithm definition also describes its arguments in terms of variables.

Algorithm(arg) :
  1. first
  1. then
    * substep
      * deeper substep
      * another deep substep
    * another step
  1. okay

Produces the following:

Algorithm(arg)
  1. first
  2. then
    1. substep
      1. deeper substep
      2. another deep substep
    2. another step
  3. okay

3.15Grammar

Spec Markdown makes it easier to describe context-free grammatical productions.

Grammars are defined by a sequence of terminal characters or sequence of characters, which are then referenced by non-terminal rules. The definition of a non-terminal is referred to as a production.

3.15.1Grammar Production

The : token indicates an “is defined as” production for a non-terminal, where a single definition can be written directly after the :.

PBJ : Bread PeanutButter Jelly Bread

Produces the following:

PBJ
BreadPeanutButterJellyBread

Or if PBJ has definition options, they are written immediately after as a Markdown list.

PBJ :
  - Bread PeanutButter Jelly Bread
  - Bread Jelly PeanutButter Bread

Produces the following:

PBJ
BreadPeanutButterJellyBread
BreadJellyPeanutButterBread

Each definition is a space seperated list of terminal or non-terminal tokens, and may also include conditionals and constraints.

Definition lists aren’t required to be indented:

PBJ :

- Bread PeanutButter Jelly Bread
- Bread Jelly PeanutButter Bread

Produces the following:

PBJ
BreadPeanutButterJellyBread
BreadJellyPeanutButterBread

3.15.2Production types

Often languages wish to specify different types of grammar productions, such as lexical or syntactical, or if certain characters line whitespace or newlines are permitted between symbols in the right-hand-side. Spec-md allows this this distinction based on the number of colons:

TypeOne : `type` `one`

TypeTwo :: `type` `two`

TypeThree ::: `type` `three`

Produces the following:

TypeOne
typeone
TypeTwo
typetwo
TypeThree
typethree

3.15.3One of

If each definition option is a single token, it can be expressed as a “one of” expression instead of a markdown list.

AssignmentOperator : one of *= `/=` %= += -= <<= >>= >>>= &= ^= |=

Produces the following:

AssignmentOperator
*=/=%=+=-=<<=>>=>>>=&=^=|=

“one of” can also be followed by a line break and multiple lines of tokens. To improve legibility in other tools, each line may optionally begin with a bullet.

Keyword : one of
  - break     do        in          typeof
  - case      else      instanceof  var
  - catch     export    new         void
  - class     extends   return      while
  - const     finally   super       with
  - continue  for       switch      yield
  - debugger  function  this
  - default   if        throw
  - delete    import    try

Produces the following:

Keyword
breakdointypeof
caseelseinstanceofvar
catchexportnewvoid
classextendsreturnwhile
constfinallysuperwith
continueforswitchyield
debuggerfunctionthis
defaultifthrow
deleteimporttry

3.15.4Non Terminal Token

Non-terminal tokens with a defined as a grammar production can be referred to in other grammar productions. Non-terminals must match the regular expression /[A-Z][_a-zA-Z]*/. That is, they must start with an uppercase letter, followed by any number of letters or underscores.

3.15.5Prose

Grammars can describe arbitrary rules by using prose within a grammar definition by using "quotes".

Sandwich : Bread "Any kind of topping" Bread

Produces the following:

Sandwich
BreadAny kind of toppingBread

3.15.6Terminal Token

Terminal tokens refer to a character or sequence of characters. They can be written unadorned in the grammar definition.

BalancedParens : ( BalancedParens )

Produces the following:

Any sequence of characters can be written to indicate a terminal token:

WhileStatement : while ( Expression ) { Statements }

Produces

WhileStatement
while(Expression){Statements}

Terminals can also be quoted with back-ticks ` to remove any ambiguity from other meanings, for example to allow a terminal token to start with an uppercase letter, or a slash / or backslash \, or later contain a ] or }.

DivisionExpression : Expression `/` Expression

Produces

DivisionExpression
Expression/Expression

3.15.7Regular Expression

When a grammar is intended to be interpretted as a single token and can be clearly written as a regular expression, you can do so directly.

UppercaseWord : /[A-Z][a-z]*/

Produces the following:

UppercaseWord
/[A-Z][a-z]*/

3.15.8Quantifiers

Tokens can be followed by quantifiers to alter their meaning and as a short-hand for common patterns of optionality and repetition.

Optional Tokens

A subscript suffix Token? renders as Tokenopt and is a shorthand for two possible definitions, one including that token and one excluding it.

Sentence : Noun Verb Adverb?

Produces the following:

Sentence
NounVerbAdverbopt

Which is shorthand for:

Sentence
NounVerbAdverb
NounVerb
Token Lists

A subscript suffix Token+ renders as Tokenlist and is shorthand for a list of one or more of that token.

Book : Cover Page+ Cover

Produces the following:

Book
CoverPagelistCover

Which, unless your specification document declares otherwise, is shorthand for:

Book
CoverPage_listCover

Some specifications may wish to declare Tokenlist as a shorthand for a comma-separated list, in which case the previous example would be shorthand for:

Book
CoverPage_listCover
Page_list
Page
Optional Lists

A subscript suffix Token* renders as Tokenlistopt and is shorthand for an optional list, which describes zero or more of that token.

Sandwich : Bread Topping* Bread

Produces the following:

Sandwich
BreadToppinglistoptBread

Which is shorthand for:

Sandwich
BreadTopping_listBread
BreadBread
Topping_list
Topping
Use with Non-Terminals

Quantifiers also apply to non-terminal tokens with the same rules. For example:

UnionMembers :
  - UnionMembers | NamedType
  - `|`? NamedType

Produces the following:

UnionMembers
UnionMembers|NamedType
|optNamedType

However, unquoted non-terminals may use the *, ? and + characters, so always quote the terminal if the intent is to apply a quantifer.

Counter Example № 9UnionMembers :
  - UnionMembers | NamedType
  - |? NamedType

Produces the terminal |?, not an optional |:

UnionMembers
UnionMembers|NamedType
|?NamedType

3.15.9Conditional Parameters

It can be a useful short-hand to provide conditional parameters when defining a non-terminal token rather than defining two very similar non-terminals.

A conditional parameter is written in braces Token[Param] and renders as TokenParam. When used in definitions is shorthand for two symbol definitions: one appended with that parameter name, the other without.

Example[WithCondition] : "Definition TBD"

Produces the following:

ExampleWithCondition
Definition TBD

Which is shorthand for:

Example
Definition TBD
Example_WithCondition
Definition TBD

The conditions are applied at the beginning of a definition for the non-terminal by prefixing with [if Param] (alternatively [+Param]) or [if not Param] (alternatively [~Param]) to only include the definition when the variant with the conditional parameter is or is not used, respectively.

Example[WithCondition] :
  - A
  - [if WithCondition] B
  - [if not WithCondition] C
  - [+WithCondition] D
  - [~WithCondition] E

Produces the following:

ExampleWithCondition
A
WithConditionB
WithConditionC
WithConditionD
WithConditionE

Which is shorthand for:

Example
A
C
E

The same bracket suffix on a non-terminal within a rule is shorthand for using that variant of the rule. If the parameter starts with ?, that form of the symbol is conditionally used only in the derived production with the same parameter. If the parameter starts with !, that form of the symbol is only used when in the derived production without that parameter.

Example[WithCondition] :
  - Example
  - Example[WithCondition]
  - Example[?WithCondition]
  - Example[!WithCondition]

Produces the following:

ExampleWithCondition
ExampleWithCondition
ExampleWithCondition
ExampleWithCondition

Which is shorthand for:

Multiple conditional parameters can be used on both the production definition and on non-terminals within a rule, in which case it is short form for the permutation of all conditions:

Example[P, Q] :
  - [if P] `p`
  - [if Q] `q`
  - Example[!P, ?Q]

Produces the following:

ExamplePQ
Pp
Qq

Which is shorthand for:

Conditional parameters on a usage can be followed by a quantifier.

Example[P, ?Q]*

Produces the following:

ExamplePQlistopt

3.15.10Constraints

Any token can be followed by “but not” or “but not one of” to place a further constraint on the previous token:

Example : A B but not foo or bar

Produces the following:

Example
ABfoobar

Optionally can mention “one of”, this will be omitted when rendered. Commas can be used instead of “or”.

Example : A B but not one of foo, bar

Produces the following:

Example
ABfoobar

3.15.11Meta Tokens

Spec Markdown can specify some tokens which do not consume any characters.

The empty set, written [empty] appears as [empty] can be used to define a non-terminal as matching no terminal or non-terminal tokens.

Example : [empty]

Produces the following:

Example
[empty]

Lookaheads can appear anywhere in a sequence of tokens, and describe additional constraints on the following token.

Example :
  - [lookahead token] Token
  - [lookahead ! token] Token
  - [lookahead != token] Token
  - [lookahead NonTerminal] Token
  - [lookahead ! NonTerminal] Token
  - [lookahead != NonTerminal] Token
  - [lookahead {token, set}] Token
  - [lookahead ! {token, set}] Token
  - [lookahead != {token, set}] Token

Produces the following:

Example
tokenToken
tokenToken
tokenToken
NonTerminalToken
NonTerminalToken
NonTerminalToken
tokensetToken
tokensetToken
tokensetToken

3.16Grammar Semantics

Once grammar is defined, it can be useful to define the semantics of the grammar in terms of algorithm steps. A single grammar definition followed by a list is interpretted as a grammar semantic:

PBJ : Bread PeanutButter Jelly Bread

* Let {bottomBread} be the result of placing the first {Bread} on the plate.
* Let {pbSpread} be the result of getting {PeanutButter} from the jar.
* Spread {pbSpread} onto {bottomBread}.
* Let {topBread} be the result of placing the last {Bread} on the plate.
* Let {jamSpread} be the result of getting {Jelly} from the jar.
* Spread {jamSpread} onto {topBread}.
* Let {sandwich} be the result of rotating {topBread} 180&deg; and placing on {bottomBread}.
* Return {sandwich}.

Produces the following:

PBJ
BreadPeanutButterJellyBread
  1. Let bottomBread be the result of placing the first Bread on the plate.
  2. Let pbSpread be the result of PeanutButter.
  3. Spread pbSpread onto bottomBread.
  4. Let topBread be the result of placing the last Bread on the plate.
  5. Let jamSpread be the result of Jelly.
  6. Spread jamSpread onto topBread.
  7. Let sandwich be the result of rotating topBread 180° and placing on bottomBread.
  8. Return sandwich.

3.17Value Literals

Value literals allow any text to refer to a value which has semantic meaning in the specification by wrapping it in { } curly brace characters.

I can reference {foo}, {"foo"}, {null}, {true}.

Produces the following:

I can reference foo, "foo", null, true.

Variables

Write {foo} to produce a variable (represented by a <var> tag) like foo.

Keywords

Some known keywords like null, undefined, true and false are rendered as constants instead of variables.

String literal

Write {"foo"} to produce a string literal like "foo".

Grammar tokens

Any grammar token can be written inline, like {Example} to represent the non-terminal token Example, {`terminal`} to represent the terminal token terminal. Even meta tokens like {[empty]} for [empty] and {[lookahead !{ x, y }]} for xy.

Algorithm calls

A call to an algorithm can be expressed as a value literal:

{Algorithm(foo, "string", null)}

Produces the following:

Algorithm(foo, "string", null)

3.18Biblio

By supplying a "biblio" key in a metadata file, you can have Algorithm calls and Non-terminal tokens which are not defined in this spec to link to where they are defined.

spec-md -m metadata.json myspec.md

Where metadata.json includes:

{
  "biblio": {
    "http://people.mozilla.org/~jorendorff/es6-draft.html": {
      "Identifier": "#sec-names-and-keywords",
      "PrimaryExpression": "#sec-primary-expression",
      "ReturnIfAbrupt()": "#sec-returnifabrupt",
      "Get()": "#sec-get-o-p"
    }
  }
}

Then referring to these tokens will link out to that page.

MemberExpression : PrimaryExpression . Identifier

  * Let {reference} be the result of evaluating {PrimaryExpression}.
  * Let {propName} be the string value of {Identifier}.
  * Let {value} be {Get(reference, propName)}.
  * {ReturnIfAbrupt(value)}.
  * Return {value}.

Produces the following:

MemberExpression
  1. Let reference be the result of evaluating PrimaryExpression.
  2. Let propName be the string value of Identifier.
  3. Let value be Get(reference, propName).
  4. ReturnIfAbrupt(value).
  5. Return value.

AUsing Spec Markdown

If installed globally, using spec-md as a shell executable is the easiest way to use Spec Markdown. The spec-md executable expects a filepath to a Markdown document as input and outputs HTML on stdout. Use > to write stdout to a file.

npm install -g spec-md
spec-md ./path/to/markdown.md > ./path/to/output.html

You can also require spec-md as a node module, after which you might add the spec-md command as a node script.

npm install --save-dev spec-md
const fs = require('fs');
const specMarkdown = require('spec-md');
const html = specMarkdown.html('./path/to/markdown.md');
fs.writeFileSync('./path/to/output.html', html);

The spec-md node module provides a few functions:

A.1Print Options

The html(filePath, options) and print(filePath) functions both take options as an optional second argument. These options allow for customization control over the returned HTML, more options may be added in the future.

  • githubSource - a base URL, that if provided will be used to construct Github source links to the original Markdown files throughout the returned HTML. (example: “https://github.com/leebyron/spec-md/blame/main/”)
  • includeComments - If true, any HTML style comments that occur within the original markdown files will be included in the returned HTML.
  • highlight - a function which is called when blocks of code are encountered, with the first argument as the string of code, the second argument being the language specified. This function should return well formed HTML, complete with escaped special characters.
  • head - a string which is inserted in the <head> tag in the returned HTML. Use this to introduce additional meta tags and scripts.
Note When using githubSource take note that normal Github view (eg. “blob” instead of “blame”) show rendered instead of source markdown and cannot link to specific lines.

A.2Hot rebuilding with nodemon

The spec-md shell executable follows the Unix Philosophy of doing one thing and doing it well. Try out nodemon to continuously rebuild the HTML output as you edit the markdown specification:

npm install -g nodemon
nodemon --exec "spec-md > ./path/to/output.html" ./path/to/markdown.md

BContributing to Spec Markdown

We want to make contributing to this project as easy and transparent as possible. Hopefully this document makes the process for contributing clear and answers any questions you may have. If not, feel free to open an Issue.

B.1Pull Requests

All active development of Spec Markdown happens on GitHub. We actively welcome your pull requests.

  1. Fork the repo and create your branch from main.
  2. Install all dependencies. (npm install)
  3. If you’ve added code, add tests.
  4. If you’ve changed APIs, update the documentation.
  5. Run tests and ensure your code passes lint. (npm test)

B.2`main` is unsafe

We will do our best to keep main in good shape, with tests passing at all times. But in order to move fast, we might make API changes that your application might not be compatible with. We will do our best to communicate these changes and always version appropriately so you can lock into a specific version if need be. If any of this is worrysome to you, just use npm.

B.3Issues

We use GitHub issues to track public bugs and requests. Please ensure your bug description is clear and has sufficient instructions to be able to reproduce the issue. The best way is to provide a reduced test case on jsFiddle or jsBin.

B.4Coding Style

  • 2 spaces for indentation (no tabs)
  • 80 character line length strongly preferred.
  • Prefer ' over "
  • Use semicolons;
  • Trailing commas,
  • Avd abbr wrds.

B.5License

By contributing to Spec Markdown, you agree that your contributions will be licensed under its MIT license.

§Index

  1. Algorithm
  2. AssignmentOperator
  3. BalancedParens
  4. Book
  5. Cookie
  6. DivisionExpression
  7. Example
  8. Example_P
  9. Example_P_Q
  10. Example_Q
  11. Example_WithCondition
  12. Keyword
  13. Page_list
  14. PBJ
  15. Philosophy
  16. Sandwich
  17. Sentence
  18. Topping_list
  19. TypeOne
  20. TypeThree
  21. TypeTwo
  22. UnionMembers
  23. UppercaseWord
  24. WhileStatement
  1. 1Getting Started
  2. 2Markdown
    1. 2.1Character Encoding
      1. 2.1.1Escape sequence
    2. 2.2Inline formatting
      1. 2.2.1Inline HTML
      2. 2.2.2Links
      3. 2.2.3Emphasis
      4. 2.2.4Inline Code
      5. 2.2.5Images
    3. 2.3Blocks
      1. 2.3.1Block HTML
      2. 2.3.2Section Headers
      3. 2.3.3Paragraphs
      4. 2.3.4Lists
        1. 2.3.4.1Task Lists
      5. 2.3.5Code Block
      6. 2.3.6Block Quotes
      7. 2.3.7Horizontal Rules
      8. 2.3.8Automatic Links
  3. 3Spec Additions
    1. 3.1Link Anything
    2. 3.2Title and Introduction
    3. 3.3Sections
      1. 3.3.1Section Headers
      2. 3.3.2Subsection Headers
      3. 3.3.3Table of Contents
      4. 3.3.4Section Numbers
        1. 3.3.4.8Custom Numbers
        2. 3.3.4.9Appendix / Annex Sections
    4. 3.4Smart Characters
      1. 3.4.1Quotes and Dashes
      2. 3.4.2Math
      3. 3.4.3Arrows
    5. 3.5Tables
    6. 3.6Comments
    7. 3.7Definitions
      1. 3.7.1Definition List
      2. 3.7.2Definition Paragraph
      3. 3.7.3Definition References
    8. 3.8Note
    9. 3.9Todo
    10. 3.10Syntax Highlighting
      1. 3.10.1Examples
      2. 3.10.2Counter Examples
    11. 3.11Imports
    12. 3.12Inline editing
    13. 3.13Block editing
    14. 3.14Algorithms
    15. 3.15Grammar
      1. 3.15.1Grammar Production
      2. 3.15.2Production types
      3. 3.15.3One of
      4. 3.15.4Non Terminal Token
      5. 3.15.5Prose
      6. 3.15.6Terminal Token
      7. 3.15.7Regular Expression
      8. 3.15.8Quantifiers
      9. 3.15.9Conditional Parameters
      10. 3.15.10Constraints
      11. 3.15.11Meta Tokens
    16. 3.16Grammar Semantics
    17. 3.17Value Literals
    18. 3.18Biblio
  4. AUsing Spec Markdown
    1. A.1Print Options
    2. A.2Hot rebuilding with nodemon
  5. BContributing to Spec Markdown
    1. B.1Pull Requests
    2. B.2`main` is unsafe
    3. B.3Issues
    4. B.4Coding Style
    5. B.5License
  6. §Index