many markdown implementations are string transformers that map exactly from markdown to HTML
markdown → HTML
instead, RightDown is a full parser. this means an input string is not transformed directly to an output string, but rather to an intermediate token tree. the token tree can then be rendered out to either HTML or back to text
rightdown ↔ token tree → HTML
as such, a rightdown file can be loaded into memory, edited programmatically, and saved back as another – fully normalized – rightdown file
this document is not what you need to use the rightdown library. this may not even be helpful if you are programmatically editing rightdown token trees. this document is my own design notes on how the library is built, and as such, likely useful only if someone is trying to extend this library in their own way
for the main user guide, click here
the rightdown library has many python modules within
these are scaffolding and support
RightDown class that is the main programming interfacerd.py, a command-line toolthis is where the magic happens
parsing happens by building an in-memory tree that represents the structured content of a document. this is called the token tree, because every node in it is an instance of class Token, defined in tokens.py
there are, however, three kinds of Token, which come into play at different times:
LineBlockSnipa Line is a short-duration token used only in the early stages of parsing. by later stages, all Line tokens have been removed from the tree and Blocks or Snips are in their place
a Block is any token that may have sub-tokens under it. as such, the tree’s actual structure is entirely built out of Blocks. even the very high-level RightDown object is itself a subclass of Block
a Snip is always a leaf in the tree, and represents a single small bit of text that has been broken down as far as possible
how a tree is built from these tokens is our topic for the rest of this document
a bit of backstory: this library is my second attempt at making a markdown parser. the first was structurally working, then i found it was 1000x slower than the standard markdown library. the problem was, i had delved too deep, and re-invented grep
grep, or regular expressions, are an amazing means of pattern matching. inside a text parser, one wants to do a lot of pattern matching. but one also wants to do pattern matching against say, lists of tokens, instead of strings of text. the standard pythonic regular expression library only works against text
thus i had built my own pattern matching code. it worked, but was extremely slow as compared to the highly optimized standard python module for regular expressions. this failure soured me, and i put the project down for almost two years
then the obvious finally hit: why not turn a list of tokens into a string of text?
specifically, give each token a short string called its tokentype. all tokentypes are exactly K characters long. then, take our list of tokens and concatenate all the tokentypes. this yields a string K times as long as our token list. do pattern matching on the string. any indices returned, divide by K, and we have indices into the token list instead
with this key idea, i started the rightdown library over again. this time, it all came together. the present rightdown engine, based on this concept, has speed on par with the standard python markdown library
class TokenList in parser.py is the encapsulation of this token indexing logic. our tokentypes are defined in enums.py. each tokentype tag is exactly three letters followed by a comma (K=4)
the reason for the comma is stride: it means our patterns will match only at the exact start of any token, instead of potentially partway through some token based on what letters are in adjacent tokens
the act of transforming an input string into an output string happens in stages
these stages are listed in code at the very top of enums.py
stages 1 – 8 are the parsing stages, and are the steps of turning the input string into a fully-processed token tree. stages 9 & 10 are the printing stages, and are how the token tree is serialized again into text or HTML output
Parser.__init__()there is a precursor stage to parsing any rightdown string. the parser does its work by pattern matching a lot of regular expressions against the input text. all those regular expressions get compiled when the parser inits for the first time in any process
an input string is split by newlines, and each line of text is placed into a Line instance. the Line strips off whitespace and remembers how much there was. rudimentary “what is this?” detection is done with no correlation between adjacent lines
at this point, the token tree is a flat list of Lines
the highest level blocks have been detected. specifically, runs of Lines that look like fenced code or comments have been detected, and a Code or Comment Block token created around each. after these have been extracted, then hard break lines are used to split the remaining input into Fragments
at this point, the token tree is a list of one or more Fragments. each Fragment’s children are probably still just a list of Lines, but Comment and Code blocks may be intermingled
the first Fragment is tested to see if it begins with Lines that can be turned into a Metadata block. if so, the block is constructed and becomes the first child of the Fragment
some few of our parser’s configurable options may be overridden from within the document being parsed. (e.g.: tab_width) this is the stage where those options are tested. if the Fragment 0 metadata contains any overrides, those overrides are applied, then parsing is restarted with the new settings
the remainder of Fragment 0 is processed into Blocks. we extract more metadata such as the document’s title and excerpt
at this point, Fragment 0 is entirely a tree of Blocks. other Fragments still contain Lines
Fragments beyond 0 are allowed to catch up
at this point, the token tree is entirely made of Blocks
many of the Blocks have text inside, and this is the stage where that text is broken apart on its own formatting characters. if the text contains no formatting marks, then a Snip is created and given to the Block as a child. if the text does contain formatting, then a Text block is made instead
a Text block may contain children of its own. for example, if a link pattern is detected, the Text block will contain a Link block as its child. that Link block then has title text of its own, which expands into potentially another Text block in the Link’s children
at this point, the token tree has many Snips added, as well as Text blocks and a few other blocks inside those Text blocks, such as Links, SuperScripts, and SubScripts
the difference between this stage and last is that here we have validated our internal structures to make sure we didn’t horribly screw up
the token tree is fully built and ready for use
the most usual thing to do with a token tree is to render it into an output string. each Block knows a little bit about how to format itself for either plain text or HTML, but the process is overseen by a Printer class
this stage is the first step the Printer takes to do its job. specifically, the token tree is serialized into a list of Imprints. each Imprint is a short, rendered string of text or formatting characters
the most finicky part of the process is breaking the stream of imprints into logical lines. more specifically, lines may need prefixes, may need double-spaced, and may even need both. the Printer is solely responsible for this logic, and may dog have mercy if you ever need to tinker with it
finally, the list of Imprints is converted into pure strings, and those strings are joined together into the output
these are not rigorous, but we have attempted to maintain the following limits around what responsibilities Blocks have, versus what code needs to live inside the parser or printer modules:
[1] during parsing, blocks do not apply any patterns. all patterns are applied by portions of the parser, which we call the linemaker, the blockmaker, and the textmaker respectively
[2] during printing, the printer does no filtering. which blocks emit, and whether they emit markup, formatting marks, or both, are settings contained on a printer, but respected and used by blocks
at some point in processing markdown you have to take a single string of text and break pieces out of it, like fixed-width text for instance. there are two possible approaches to this:
our implementation takes approach 2
the trick then is finding a way to introduce marks into the string that can be differentiated from original string content later. our solution here is we use unicode characters from the private use unicode code page. that is UCS-2 characters 0xE000 – 0xF8FF are used inside the parser to track which parts of strings have been snipped out and need separate formatting
the implication here is that we can not handle documents that natively contain any of these characters. in fact, there is a setting on the parser for what to replace them with on input. default is a space
the inverse of this is if any of our substituted characters end up emitted in the output, we know our code broke somehow. during validation these get replaced with a del character (∇) so they can be easily noticed
the RightDown instance has flags set if either of these conditions is triggered