# cortav specification

cortav is a markup language designed to be a simpler, but more capable alternative to markdown. its name derives from the Ranuir words cor “writing” and tav “document”, translating to something like “(plain) text document”.

the cortav format can be called cortavgil, or gil cortavi, to differentiate it from the reference implementation cortavsir or sir cortavi.

## cortav vs. markdown

the most important difference between cortav and markdown is that cortav is strictly line-oriented. this choice was made to ensure that cortav was relatively easy to parse. so while a simple .ct file may look a bit like a .md file, in reality it’s a lot closer to gemtext than any flavor of markdown.

however, the differences go much deeper. the most distinctive feature of cortav is that its syntax is strongly recursive. with markdown, you can apply at most one styling to any given block or span or text. with cortav, you can nest as many styles as you like, and you can style text in places markdown wouldn’t ordinarily let you: within headings, inside link text, even in code listings if you absolutely insist (this needs to be turned on by a special directive before the listing in question, however).

this manual describes cortav exhaustively, but if you just want a quick reference on how markdown translates to cortav, look no further.

• headings: cortav uses almost the same syntax for headings that markdown does, except it only allows the “ATX style” headings, with one or more hash characters at the start of the line. the only differences from markdown are:
• you can use the unicode section character § instead of # if you’re feeling snobby
• you must put a space between the control sequence (the sequence of hashes or section symbols, in this case) and the title text. # title creates a section with the heading text “title”, but #title creates a new section with no heading at all; instead, it gives the anonymous section the ID title. and of course, you can combine the two: #ttl title creates a section with the heading text “title” and the ID ttl. what are IDs for? we’ll get to that in a little bit
• paragraphs are mostly the same as in markdown, except that a paragraph break occurs after every newline character, not every blank line. paragraphs can be indented by however many spaces you like; such indentation will be ignored. (tabs have a special meaning, however). in cortav, you can also explicitly mark a line of text as a paragraph by preceding it with a period character (.), which is useful if you want to start a paragraph with text that would otherwise be interpreted specially.
• italic text — or rather, emphasized text — is written as [!my spiffy italic text]. in cortav, these spans can be nested within other spans (or titles, or table cells, or…), and the starting and ending point is unambiguous.
• bold text — or rather, strong text — is written as [*my commanding bold text].
• bold-italic text — or rather, emphasized strong text — has no specific notation. rather, you create it by nesting one span within the other, for instance: [*[!my ostentatious bold-italic text]].
• links are quite different from their markdown equivalents. cortav does not have inline links, as it is intended to be easily readable in both formatted and plain-text format, and long URLs rather disrupt the flow of reading. rather, a link tag is written with the notation [>nifty-link my nifty link], where the word nifty-link immediately following the arrow is an identifier indicating the destination of the link. (instead of a greater-than sign, you can also use the unicode arrow symbol →.) if the identifier is the same as one you’ve assigned to a section, cortav produces a link within the document to that section. otherwise, it will look for a reference to tell it the URI for the link. a reference is a key-value pair created by adding a line like nifty-link: https://zombo.com indented by exactly one tab. you can place this reference anywhere you like so long as it’s in the same section; if you want to name a reference in another section, you have to prefix it with that section’s ID, e.g. [>spiffy-section.nifty-link my nifty link declared in a spiffy section].
• lists use a different syntax from markdown. you can start a line with a * to create an unordered list, or : to create an ordered list; indentation doesn’t matter. if you want to nest list items, instead of putting two spaces before the child item, you just add another star or colon. and of course, you can nest lists of different kinds within one another.
• horizontal rules use roughly the same syntax: three or more hyphens on a line of their own (---). underlines also work (___, -_-, __-__-__ etc).
• some markdown implementations support tables. cortav does too, using a very simple notation.
• underlines are supported by some markdown implementations. in cortav, you can apply them with the notation [_my underlined text] — please just use them sparingly when you render to HTML!
• strikethrough is supported by some extended versions of markdown. cortav uses the notation [~my deleted text], with the intended semantics of text that is being removed by some revision of a document. (you can also denote text that is being added by using a plus sign instead of a tilde)
• images are a bit more complicated. see the section on resources for an explanation.
• smart quotes and em dashes are inserted automatically, just as in markdown, provided you have the transmogrify extension available. (it is part of the reference implementation and defined by the spec, but not required.) in fact, you can insert longer dashes than em dashes just by increasing the number of hyphens. the reference implementation’s transmogrifier also translates ascii arrows like --> into their unicode equivalents (→).
• literals (also known as code text) can be inserted with the [int main(void); syntax. note however that literals are not protected from the transmogrifier, and are parsed like any other span, which may cause problems if the source code you’re quoting makes use of such forbidden runes. in this case, you’ll want to wrap the code span in a raw span. the syntax for this is [[\int main(void);]], but since this is a bit unwieldy it can also be abbreviated as [\int main(void);].

of course, this is only a small taste of what cortav can do, not even touching on key features like macros, footnotes, or equation formatting. read the sections on blocks and spans for all the gory details.

## encoding

a cortav document is made up of a sequence of codepoints. UTF-8 must be supported, but other encodings (such as UTF-32 or C6B) may be supported as well. lines will be derived by splitting the codepoints at the linefeed character or equivalent. note that unearthly encodings like C6B or EBCDIC will need to select their own control sequences.

## file type

a cortav source file is identified using a file extension, file type, and/or magic byte sequence.

three file extensions are defined as identifying a cortav source file. where relevant, all must be recognized as indicating a cortav source file.

• ct is the shorthand extension
• cortav is the canonical disambiguation extension, for use in circumstances where *.ct is already defined to mean a different file format.
•  is the canonical Corran extension, a byte sequence comprising the unicode codepoints U+E3CE U+E3BD. where the filesystem in question does not specify a filename encoding, the bytes should be expressed in UTF-8.

three more extensions are reserved for identifying a cortav intent file.

• ctc is the shorthand extension
• cortavcun is the canonical disambiguation extension
•  is the canonical Corran extension, a byte sequence comprising the unicode codepoints U+E3CE U+E3BD U+E3CE. where the filesystem in question does not specify a filename encoding, the bytes should be expressed in UTF-8.

on systems which use metadata to encode filetype, two values are defined to identify cortav source files

• text/x-cortav should be used when strings or arbitrary byte sequences are supported
• CTAV (that is, the byte sequence 0x43 54 41 56) should be used on systems that support only 32-bit file types/4-character type codes like Classic Mac OS.

two more values are defined to identify cortav intent files.

• text/x-cortav-intent
• CTVC (the byte sequence 0x43 54 56 43)

on systems which do not define a canonical way of encoding the filetype but support extended attributes of some kind, such as linux, an attribute named mime may be created and given the value text/x-cortav or text/x-cortav-intent; alternatively, extensions may be used.

it is also possible to indicate the nature of a cortav file without using filesystem metadata. this is done by prefixing the file with a magic byte sequence. the sequence used depends on the encoding.

• for UTF-8 and ASCII plain text files, %ct\n (that is, the byte sequence 0x25 63 74 0A) should be used
• for C6B+PS files (parastream), the file should begin with the paragraph , which equates to the byte sequence  0x3E 2E 14 0C 01 04 00 00 00 03 07 3E 2D, including the parastream header).

consequently, this sequence should be ignored by a cortav parser at the start of a file (except as an indication of file format).

• &$mymacro arg 1|arg 2|arg 3 • &image embeds an image or other block-level object. image can be a reference with a url or file path, or it can be an embed section (e.g. for SVG files) • &myimg All that remained of the unfortunate blood magic pageant contestants and audience (police photo) • &-section styled-text embeds a closed disclosure element. in interactive outputs, this will display as a block section which can be clicked on to view the full contents of the referenced section; if styled-text is present, it overrides the title of the section you are embedding. in static outputs, the disclosure object will display as an enclosed box with styled-text as the title text • &-ex-a Prosecution Exhibit A (GRAPHIC CONTENT) • &+section styled-text is like the above, but the disclosure element is open by default • horizontal rule (---): inserts a horizontal rule or other context break; does not end the section. must be followed by newline. underlines can also be used in place of dashes. • page break (^^): for formats that support pagination, like HTML (when printed), indicates that the rest of the current page should be blank. for formats that do not, extra margins will be inserted. does not create a new section • page rule (^-^): inserts a page break for formats that support them, and a horizontal rule for formats that do not. does not create a new section • table cells (+ |): see table examples. • equations (=) block-level equations can be inserted with the = • empty lines (that is, lines consisting of nothing but whitespace) constitute a break, which terminates multiline objects that do not have a dedicated termination sequence, for example lists and asides. ## styled text most blocks contain a sequence of spans. these spans are produced by interpreting a stream of styled-text following the control sequence. styled-text is a sequence of codepoints potentially interspersed with escapes. an escape is formed by an open square bracket [ followed by a span control sequence, and arguments for that sequence like more styled-text. escapes can be nested. • strong  [*styled-text]: causes its text to stand out from the narrative, generally rendered as bold or a brighter color. • emphatic  [!styled-text]: indicates that its text should be spoken with emphasis, generally rendered as italics • custom style  [.id styled-text]: applies a specially defined font style. for example, if you have defined caution to mean “demibold italic underline”, cortav will try to apply the proper weight and styling within the constraints of the current font to the span styled-text. see the fonts section for more information about this mechanism. • literal  [styled-text]: indicates that its text is a reference to a literal sequence of characters or other discrete token. generally rendered in monospace • variable  [$styled-text]: indicates that its text is a stand-in that will be replaced with what it names. generally rendered in italic monospace, ideally of a different color
• underline  [_styled-text]: underlines the text. use sparingly on text intended for webpages — underlined text is distinct from links, but underlining non-links is still a violation of convention.
• strikeout  [~styled-text]: indicates that its text should be struck through or otherwise indicated for deletion
• insertion  [+styled-text]: indicates that its text should be indicated as a new addition to the text body.
• consider using a macro definition edit: [~[#1]][+[#2]] to save typing if you are doing editing work
• link [>ref styled-text]: produces a hyperlink or cross-reference denoted by ref, which may be either a URL specified with a reference or the name of an object like an image or section elsewhere in the document. the unicode characters → and 🔗 can also be used instead of > to denote a link.
• footnote  [^ref styled-text]: annotates the text with a defined footnote. in interactive output media [^citations.qtheo Quantum Theosophy: A Neophyte's Catechism] will insert a link with the next Quantum Theosophy: A Neophyte’s Catechism that, when clicked, causes a footnote to pop up on the screen. for static output media, the text will simply have a superscript integer after it denoting where the footnote is to be found.
• superscript  ['styled-text]
• subscript  [,styled-text]
• raw  [\ raw-text]: causes all characters within to be interpreted literally, without expansion. the only special characters are square brackets, which must have a matching closing bracket, and backslashes.
• raw literal [$\raw-text]: shorthand for [$[\…]]
• macro {[!name] [!arguments]}: invokes a macro, specified with a reference
• argument  [#var]: in macros only, inserts the var-th argument. otherwise, inserts a context variable provided by the renderer.
• raw argument  [##var]: like above, but does not evaluate var.
• term  [&name],  [&name expansion]: quotes a defined term with a link to its definition, optionally with a custom expansion of the term (for instance, to expand the first use of an acronym)
• inline image  [&@name]: shows a small image or other object inline. the unicode character 🖼 can also be used instead of &@.
• unicode codepoint  [U+hex-integer]: inserts an arbitrary UCS codepoint in the output, specified by hex-integer. lowercase u is also legal.
• math mode  [=equation]: activates additional transformations on the span to format it as a mathematical equation; e.g. * becomes × and /÷.
• extension  [%ext …]: invokes extension named in ext. ext will usually be an extension name followed by a symbol (often a period) and then an extension-specific directive, although for some simple extensions it may just be the plain extension name. further syntax and semantics depend on the extension. this syntax can also be used to apply formatting specific to certain renderers, such as assigning a CSS class in the html renderer ([%html.myclass my [!styled] text]).
• critical extension  [%!ext …]: like extension, but will trigger an error if the requested extension is not available
• extension text  [%:ext styled-text]: like extension, but when the requested extension is not present, styled-text wlil be emitted as-is. this is a better way to apply CSS classes, as the text will still be visible when rendered to formats other than HTML.
• inline comment  [%%...]: ignored. useful for editorial annotations not intended to be part of the rendered product.

## tables

tables are encoded using a very simple notation. any line that begins with a plus + or bar | denotes a table row. each plus or bar separates one column from the other: a plus opens a new header cell, a bar opens a new normal cell.

the alignment of a cell can be specified by placing colons at one edge or both edges of the given cell. a colon on the left (|: my table cell |) indicates a left-aligned cell, a colon on right a right-aligned cell (| my table cell :|), and a colon on both sides a centered cell (|: my table cell :|). if you want to use a special character without it being eaten by the table parser, just put a backslash in from of it, e.g. | this cell | contains a pipe + a plus sign and ends with a colon :|. and of course, table cells are just normal spans — they can contain any other kind of span formatting you like, such as links, emphasis, or footnotes.

no other features (like colspans or rowspans) are currently part of the spec but they will be added eventually (if i can figure out a decent way to implement them without creating a huge mess).

you can finish each row with a bar or plus character, but it’s not necessary. only do it if you think it makes the source easier to read.

## identifiers

any identifier (including a reference) that is defined within a named section must be referred to from outside that section as sec.obj, where sec is the ID of the containing section and obj is the ID of the object one wishes to reference.

## resources

a resource represents content that is not encoded directly into the source file, but which is embedded by some means in the output. resources can either be embedded, in which case they are compiled into the final document itself, or they can be linked, in which case the final document only contains a URI or similar tag referencing the resource. not all render backends support both linking and embedding embedding, nor do all backends support all object types (for instance, groff does not support video embedding.)

a resource definition is begun by line consisting of an @ sign and an identifier. this line is followed by any number of parameters. a parameter is a line beginning with a single tab, a keyword, a colon, and a then a value. additional lines can be added to a parameter by following it with a line that consists of two tabs followed by the text you wish to add. (this is the same syntax used by references.) a resource definition is terminated by a break, or any line that does not begin with a tab

a resource definition in use looks like this:

rendered as HTML, this might produce the following:

note that empty elements with CSS classes are used in the output, to avoid repeating long image definitions (especially base64 inline encoded ones!)

inline resources are defined a bit differently:

for an inline resource, the identifier is followed by a MIME type and an opening bracket. the opening bracket may be any of the characters {[(<, and can optionally be followed by additional characters to help disambiguate the closing bracket. the closing bracket is determined by “flipping” the opening bracket, producing bracket pairs like the following:

• {::}
• <!— —!>
• (*<>*)
• <><> (disables nesting!)

if the open and closing brackets are distinguishable, they will nest appropriately, meaning that {} alone is very likely to be a safe choice to escape a syntactically correct C program (that doesn’t abuse macros too badly). brackets are searched for during parsing; encoded resources are not decoded until a later stage, so a closing bracket character in a base64-encoded text file cannot break out of its escaping.

as a convenience, if the first line of the resource definition begins with a single tab, one tab will be dropped from every following line in order to allow legible indentation. similarly, if an opening bracket is followed immediately by a newline, this newline is discarded.

text within a resource definition body is not expanded unless the resource definition is preceded with an %expand directive. if an expand directive is found, the MIME type will be used to try and determine an appropriate type of formatting, potentially invoking a separate renderer. for example, text/html will invoke the html backend, and application/x-troff will invoke the groff backend. if no suitable renderer is available, expansions will generate only plain text.

two suffixes are accepted: ;base64 and ;hex. the former will decode the presented strings using the base64 algorithm to obtain the resources data; the second will ignore all characters but ASCII hexadecimal digits and derive the resource data byte-by-byte by reading in hexadecimal pairs. for instance, the following sections are equivalent:

inline resources can also be (ab)used for multiline macros:

to make this usage simpler, resources with a type of text/x-cortav can omit the MIME type field.

### supported parameters

• src (all): specifies where to find the file, what it is, and how to embed it. each line of src should consist of three whitespace-separated words: embed method, MIME type, and URI.
• embed methods
• local: loads the resource at build time and embeds it into the output file. not all implementations may allow loading remote network resources at build time.
• remote: only embeds a reference to the location of the resource. use this for e.g. live iframes, dynamic images, or images hosted by a CDN.
• auto: embeds a reference in file formats where that’s practical, and use a remote reference otherwise.
• MIME types: which file types are supported depends on the individual implementation and renderer backend; additionally, extensions can add support for extra types. MIME-types that have no available handler will, where possible, result in an attachment that can be extracted by the user, usually by clicking on a link. however, the following should be usable with all compliant implementations
• image/* (graphical outputs only)
• video/* (interactive outputs only)
• image/svg+xml is handled specially for HTML files, and may or may not be compatible with other renderer backends.
• font/* can be used with the HTML backend to reference a web font
• font/woff2 can be used with the HTML backend to reference a web font
• text/plain (will be inserted as a preformatted text block)
• text/css (can be used when producing HTML files to link in an extra stylesheet, either by embedding it or referencing it from the header)
• text/x-cortav (will be parsed and inserted as a formatted text block; context variables can be passed to the file with ctx.var parameters)
• application/x-troff can be used to supply sections of text written in raw groff syntax. these are ignored by other renderers.
• text/html can be used to supply sections of text written in raw HTML.
• any MIME-type that matches the type of file being generated by the renderer can be used to include a block of data that will be passed directly to the renderer.
• URI types: additional URI types can be added by extensions or different implementations, but every compliant implementation must support these URIs.
• http, https: accesses resources over HTTP. add a file fallback if possible for the benefit of renderers/viewers that do not have internet access abilities.
• file: references local files. absolute paths should begin file:/; the slash should be omitted for relative paths. note that this doesn’t have quite the same meaning as in HTML — file can (and usually should be) used with HTML outputs to refer to resources that reside on the same server. a cortav URI of file:/etc/passwd will actually result in the link /etc/passwd, not file:///etc/passwd when converted to HTML. generally, you only should use http when you’re referring to a resource that exists on a different domain.
• name: a special URI used generally for referencing resources that are already installed on a target system and do not need to be embedded or linked, the name and type are enough for a renderer on another machine to locate the correct resource. this is useful mostly for fonts, where it’s more typical to refer to fonts that are installed on your system rather than providing paths to font files.
• gemini: accesses resources over the gemini protocol. currently you should really only use this for local resources unless you’re using the gemtext renderer backend, since nothing but gemini browsers are liable to support this protocol.
• desc: supplies a narrative description of the resources, for use as an “alt-text” when the image cannot be loaded and for screenreaders.
• detail: supplies extra narrative commentary that is displayed contextually, e.g. when the user hovers her mouse cursor over the embedded object. also used for desc if desc is not supplied.

note that in certain cases, full MIME types do not need to be used. say you’re defining a font with the name URI — you can’t necessary know what file type the system fonts on another computer are going to be. in this case, you can just write font instead of font/ttf or font/woff2 or similar. all cortav needs to know in this case is what abstract kind of object you’re referencing. groff fonts (referenced with the dit URI) don’t have a specific MIME type either.

## context variables

context variables are provided so that cortav renderers can process templates. certain context variables are provided for by the standard. you can test for the presence of a context variable with the directive %when ctx var. context variables are accessed with the  [#name] span.

• cortav.file: the name of the file currently being rendered
• cortav.path: the absolute path of the file currently being rendered
• cortav.time: the current system time in the form 13:20:29
• cortav.date: the current system date in the form Wednesday 29 December 2021
• cortav.datetime: the current system date and time represented in the locale or system-standard manner (e.g. Wed Dec 29 13:20:29 2021)
• cortav.page: the number of the page currently being rendered
• cortav.id: the identifier of the renderer
• cortav.hash: the SHA3 hash of the source file being rendered

on systems with environment variables, these may be accessed as context variables by prefixing their name with env..

different renderers may provide context in different ways, such as from command line options or a context file. any predefined variables should carry an appropriate prefix to prevent conflation.

## fonts

for output backends that support font specification, cortav provides a sophisticated font management system by means of the font stack.

when a document parse begins, the font stack is empty (unless a default font has already been loaded by an intent file).

when the font stack is empty, cortav does not include font specifications in its output, and thus will use whatever the default of the various rendering programs is.

to use fonts, we first have to define the fonts as resources.

here we have defined two font families, fonts.serif and fonts.sans. each contains a list of references to fonts which will be tried in order. for example, this could be translated into the following CSS:

there are two things that aren’t super clear from the CSS, however. notice how we used auto on a couple of those specs? this means it’s up to the renderer to decide whether to link or embed the font. in HTML, a font specified by name can’t really be embedded, but for some file formats, it can be. auto lets us produce valid HTML while still taking advantage of font embedding in other formats.

now that we have our font families defined, we can use their identifiers with the %font directive to control the font stack. the first thing we need to do is push a new font context. there’s two ways we can do this:

• %font dup will create a copy of the current font context, allowing us to make some changes and then revert later with the %font pop command. this isn’t useful in our case, however, because right now the stack is empty; there’s nothing to duplicate.
• %font new will create a brand new empty context for us to work with and push it to the stack. this can also be used to temporarily revert to the system default fonts, and then switch back with %font pop.
• %font set changes one or more entries in the current font context. it can take a space-separated list of arguments in the form entry=font-id. the supported entries are:
• body: the fallback font. if only this is set in a given font context, it will be used for everything
• paragraph: the font used for normal paragraphs
• header: the font used in headers
• subtitle: the font used in subtitles
• list: the font used in lists
• table: the font used in tables
• caption: the font used for captions
• %font pop removes the top context from the font stack.

note that extensions may consult the font context for their entries specific to them. for instance, toc checks for toc before falling back to body and then the default font.

these commands are enough to give us a very flexible setup. consider the following:

you may have noticed the rather odd bit at the end of our font definition, with the dit URI. the reasons for this are tragic. groff, while delightful, has a thoroughly antiquated understanding of fonts, and doesn’t support normal font formats like truetype. groff ships with a limited number of fonts in its own format, identified by obscurantist letter code (HBI is “Helvetica Bold Italic”, for instance) and lacking normal metadata. for this reason, you’ll have to tell cortav how you want your fonts translated.

it is possible to use modern fonts with groff, but to do that you’ll have to convert and install them, which is outside the scope of this document. however, even if you do this, you should specify a fallback font (if possible) so that people rendering your document on other machines still get somewhat sensible output.

the syntax of a dit specification is dit:regular, where regular specifies the name of the regular font. this can be followed by any number of variant specifications /variant=name, where variant is one of the tags described in the custom style section, and name is the name of a DIT font. so the URI in the example names a font T with bold TB, italic TI, and bold-italic TBI.

the groff backend does do a little magic to make this mess more bearable, however. some of groff’s built-in fonts can be accessed by a name URI instead of having to construct them by hand with a dit URI — the backend hardcodes metadata for these fonts so that documents can render somewhat intellgibly in groff even if the original author did not make special provisions for this. the groff fonts accessible by name are:

• Times New Roman
• Helvetica
• Courier
• Bookman

additionally, as a shortcut, if the regular, bold, italic, and bold-italic variants of a DIT font have the predictable pattern of X, XB, XI, XBI (which many do), you can simply write the URI dit:X and cortav will infer the rest. so the example above could be rewritten as dit:T to exactly the same effect.

### custom styles

sometimes you want to be able to issue more specific formatting instructions than “italic” or “bold”. cortav provides a simple custom style mechanism to allow this. a custom style is simply a reference that binds a name to a sequence of space-separated formatting directives. these directives include:

• regular: applies the regulat form of the font, overriding any previous set styles
• medium: applies a weight of the font between regular and bold, defaulting to regular if one is not available
• demibold: applies a weight of the font between regular and bold, defaulting to bold if one is not available
• bold: applies the usual “bold” weight of the font
• dense: applies the heaviest available weight of th the font. usually the same as bold
• light: applies the usual “light” weight of the font. most fonts do not have a light weight, so this will be the same as regular.
• thin: applies the slimmest available weight of the font. usually the same as light.
• underline: underlines the text
• strike: strikes the text out
• italic: applies a slanted variant of the font
• oblique: applies the most slanted variant of the font available. usually the same as italic
• font=id: switches to font id for the duration of the span. id must be the ID of a resource defining a font.
• ext.prop=word: attaches extra information for use by formatting extensions. ext must be the ID of the extension.

once a custom style is defined, you can make use of it using the  [.id styled-text] span notation, where id is the identifier of the reference containing your style. for instance, to define and use a style named important that specifies a dense, underlined variant of font impact1 and applies the CSS class blink when rendered with the html backend:

you should always give your styles semantic names where practicable, instead of simply describing their graphical characteristics. this is good practice in general, but especially because your document will be renderable to different formats with different characteristics, and what makes text look important on a manpage in the terminal may be quite different from how it looks in a webpage or PDF.

## directives

• %author encodes document authorship. multiple author directives can be issued to add additional coauthors
• %cols specifies the number of columns the next object should be rendered with
• %include transcludes another file
• %import reads in the contents of another file as an embeddable section
• %quote transcludes another file, without expanding the text except for paragraphs
• %embed, where possible, embeds another file as an object within the current one. in HTML this could be accomplished with e.g. an iframe.
• %expand causes the next object (usually a code block) to be fully expanded when it would otherwise not be
• %font controls the font stack, for outputs that support changing fonts. see fonts for more information.
• %lang changes the current language, which is used by extensions to e.g. control typographical conventions, and may be encoded into the output by certain renderers (e.g. HTML). note that quotes and blockquotes can be set to a separate language with a simpler syntax. the language should be notated using IETF language tags
• %lang is x-ranuir-Cent-CR8 sets the current language to Ranuir as spoken in the Central Worlds, written in Corran and encoded using UTF-8. this might be used at the top of a document to set its primary language.
• %lang push gsw-u-sd-chzh temporarily switches to Zürich German, e.g. to quote a German passage in an otherwise Ranuir document
• %lang sec en-US switches to American English for the duration of a section. does not affect the language stack.
• %lang pop drops the current language off the language stack, returning to whatever was pushed or set before it. this would be used, for instance, at the end of a passage
• %pragma supplies semantic data about author intent, the kind of information the document contains and hints about how it should be displayed to the user. think of them like offhand remarks to the renderer — there’s no guarantee that it’ll pay any attention, but if it does, your document will look better. pragmas have no scope; they affect the entire document. the pragma function exists primarily as a means to allow parameters that would normally need to be specified on e.g. the command line to be encoded in the document instead in a way that multiple implementations can understand. a few standard pragmas are defined.
• %pragma layout gives a hint on how the document should be layed out. the first hint that is understood will be applied; all others will be discarded. standard hints include:
• essay
• narrative
• screenplay: uses asides to denote actions, quotes for dialogue
• stageplay: uses asides to denote actions, quotes for dialogue
• manual
• glossary
• news
• book: section depths 1-3 gain additional semantics
1. part: the section gets a page to itself to announce the beginning of a new part or appendix
2. chapter: the section is preceded by a page break
3. heading: the section can occur on the same page as text and headings from other sections
• %pragma accent specifies an accent hue (in degrees around the color wheel) for renderers which support colorized output
• %pragma accent-spread is a factor that controls the “spread” of hues used in the document. if 0, only the accent color will be used; if larger, other hues will be used in addition to the primary accent color.
• %pragma dark-on-light on|off controls whether the color scheme used should be light-on-dark or dark-on-light
• %pragma page-width indicates how wide the pages should be
• %pragma title-page specifies a section to use as a title page, for renderer backends that support pagination

## extensions

the cortav specification also specifies a number of extensions that do not have to be supported for a renderer to be compliant. the extension mechanism supports the following directives.

• inhibits: prevents an extension from being used even where available
• uses: turns on an extension that is not specified by the user operating the renderer (e.g. on the command line)
• needs: causes rendering to fail with an error if the extensions are not available

where possible, instead of needs x y z, the directive when has-ext x y z should be used instead. this causes the next section to be rendered only if the named extensions are available. unless has-ext x y z can be used to provide an alternative format.

extensions are mainly interacted with through directives. all extension directives must be prefixed with the name of the extension.

the reference implementation seeks to support all standardized extensions. it’s not quite there yet, however.

### toc

sections that have a title will be included in the table of contents. the table of contents is by default inserted at the break between the first level-1 section and the section immediately following it. you may instead place the directive toc where you wish the TOC to be inserted, or suppress it entirely with inhibits toc. note that some renderers may not display the TOC as part of the document itself.

toc provides the directives:

• %toc: insert a table of contents in the specified position. this can be used more than once, but doing so may have confusing, incorrect, or nonsensical results under some renderers, and some may just ignore the directive entirely
• %toc mark styled-text: inserts a TOC entry with the label styled-text pointing to the current location. this can be used to e.g. mark noteworthy images, instances of long quotes or literal blocks, or functions inside an expanded code block.
• %toc name id styled-text: like %toc mark but allows an additional id parameter which specifies the ID the renderer will assign to an anchor element. this is not meaningful for all renderers and when it is, it is up to the renderer to decide what it means.
• the html render backend interprets id as the id element for the anchor tag
• the groff render backend ignores id

### transmogrify

a cortav renderer may automatically translate punctuation marks or symbol sequences to superior representations depending on their context. to be compliant this extension should implement, at minimum:

• smart quotes (with consideration for the typographical conventions languages like German or Spanish)
• %transmogrify can be used to explicitly set the language; otherwise, it must be determined from the value of %pragma. if this is not present, implementations may fall back on their own methods for determining the language in use, such as command-line flags.
• multigraph to glyph conversion, including at least:
• -- → “—”
• --> → “→”
• <-- → “←”

an escape character before any of the sequence characters should prevent the sequence from being rendered. raw nodes (that is, […] and […]) should not be scanned for transmogrification, nor should the contents of code blocks unless marked with the %expand directive

transmogrification shall only take place after all other parsing steps are completed.

### hilite

code can be highlighted according to the formal language it is written in. a compliant hilite implementation must implement basic keyword, symbol, comment, pragma, and literal highlighing for the following formal languages.

the highlighter should make use of semantic HTML tags like <var> where possible.

### lua

renderers with a lua interpreter available can evaluate lua code:

• %lua use file: evaluates file and makes its definitions available
• [%lua raw [!script]]: evaluates script and emits the string it returns (if any) in raw span context.
•  [%lua exp script]: evaluates script and emits the string it returns (if any) in expanded span context.
• %lua raw script: evaluates script and emits the string array it returns (if any) in raw block context.
• %lua exp script: evaluates script and emits the string array it returns (if any) in expanded block context.

the interpreter should provide a cortav table with the objects:

• ctx: contains context variables

used files should return a table with the following members

• macros: an array of functions that return strings or arrays of strings when invoked. these will be injected into the global macro namespace.

### ts

the ts extension allows documents to be marked up for basic classification constraints and automatically redacted. if you are seriously relying on ts for confidentiality, make damn sure you start the file with %requires ts, so that rendering will fail with an error if the extension isn’t supported.

ts enables the directives:

• %ts class scope level (styled-text): indicates a classification level for either the while document (scope doc) or the next section (scope sec). if the ts level is below level, the section will be redacted or rendering will fail with an error, as appropriate. if styled-text is included, this will be treated as the name of the classification level.
• %ts word scope word (styled-text): indicates a codeword clearance that must be present for the text to render. if styled-text is present, this will be used to render the name of the codeword instead of word.
• %when ts level level
• %when ts word word

ts enables the spans:

• [🔒#[!level] [$styled-text]]: redacts the span if the security level is below that specified. • [🔒.[!word] [$styled-text]]: redacts the span if the specified codeword clearance is not enabled.

(the padlock emoji is shorthand for %ts.)

ts redacts spans securely; that is, they are simply replaced with an indicator that they have been redacted, without visually leaking the length of the redacted text.

# reference implementation

the cortav standard is implemented in cortav.lua, found in this repository. only the way cortav.lua interprets the cortav language is defined as a reference implementation; other behaviors are simply how cortav.lua implements the specification and may be copied, ignored, tweaked, violently assaulted, or used as inspiration by a compliant parser.

the reference implementation can be used both as a lua library and from the command line. cortav.lua contains the parser and renderers, ext/* contain various extensions, sirsem.lua contains utility functions, and cli.lua contains the CLI driver.

## lua library

there are various ways to use cortav from a lua script; the simplest however is probably to precompile your script with luac and link in the necessary components of the implementation. for instance, say we have the following program

and the only extension we need is the table-of-contents extension. our script can be translated into a self-contained lua bytecode blob with the following command

and can then be operated with the command lua stdin2html.lc, with no further need for the cortav repository files. note that the order of the luac command is important! sirsem.lua must come first, followed by cortav.lua, followed by any extensions. your driver script (i.e. the script with the entry point into the application) should always come last.

### building custom tools

generally, most existing file-format conversion tools (cmark, pandoc, and so on) have a crucial limitation: they hardcode specific assumptions like document structure. this means that the files they output are generally not suitable as-is for the users’ purposes, and require further munging, usually by hateful shell or perl scripts. some tools do provide libraries end users to use as a basis for designing their own tools, but these are often limited, and in any case the user ends up having to write their own (non-standard) driver. it’s no surprise that very few people end up doing this.

cortav.lua”s design lends itself to a more elegant solution. one can of course write their own driver using cortav as a library, but most of the time when you’re compiling document sources, you just want a binary you can run from the command line or a makefile. with cortav.lua, you can extend its capabilities easily while keeping the same driver.

in the cortav spec, extensions are mostly intended to give different implementations the ability to offer extra capabilities, but the reference implementation uses an extension architecture that makes it easy to write and add your own. for each type of new behavior you want to implement, just create a new extension and list it on the make command line:

the cortav binary this produces will have all the extra capabilities you personally need, without any need to fork cortav.lua itself or even touch the repository.

there’s no reason cortav.lua shouldn’t be able to load extensions at runtime as well; i just haven’t implemented this behavior yet. it probably would only take a few extra lines of code tho.

i will eventually document the extension API, but for now, look at ext/toc.lua for a simple example of how to register an extension.

## command line driver

the cortav.lua command line driver can be run from the repository directory with the command lua ./cli.lua, or by first compiling it into a bytecode form that links in all its dependencies. this is the preferred method for installation, as it produces a self-contained executable which loads more quickly, but running the driver in script form may be desirable for development or debugging.

the repository contains a GNU makefile to automate compilation of the reference implementation on unix-like OSes. simply run $make cortav or $ gmake cortav from the repository root to produce a self-contained bytecode executable that can be installed anywhere on your filesystem, with no dependencies other than the lua interpreter.

henceforth it will be assumed that you have produced the cortav executable and placed it somewhere in your $PATH; if you are instead running cortav.lua directly as an interpreted script, you’ll need to replace $ cortav with $lua ./cli.lua in incantations. when run without commands, cortav.lua will read input from standard input and write to standard output. alternately, a source file can be given as an argument. to write to a specific file instead of the standard output stream, use the -o file flag. ### building the command line driver is built and installed with a GNU make script. this script accepts the variables shown below with their default values: prefix build $HOME/.local the path under which the package will be installed build the directory where generated objects will be placed; useful for out-of-tree builds $prefix/bin directory to install the executables to" -m html:width 35em a list of flags that will be passed by the viewer script to cortav when generating a html fille the following targets are supplied to automate the build: • install builds everything, installs the bytecode-executable and the viewer script to$bin_prefix, and registers the viewer script with XDG
• install-bin is like install but installs the binary version instead of the bytecode one
• excise deletes everything installed and deregisters the file handlers (note that the same variables must be passed to exicse as were passed to install!)
• clean deletes build artifacts from the $build directory like it was never there • wipe is equivalent to $ make excise && make clean

if you don’t want to install cortav, you can just run $make without arguments to build the executable. there are two different ways of building the driver. one is to generate a bytecode file that can be executed directly as a script. this is the most straightforward method, and requires only lua and luac. however, it has several substantial downsides: because it’s only a bytecode file, it requires the lua interpreter to run — and in some environments, the security characteristics of the lua interpreter may make this undesirable. it also must hardcode the path to the lua interpreter (though admittedly this is easy enough to fix if you copy it to another machine of the same architecture). lua is not an entirely predictable environment, as it is controlled by environment variables and may hypothetically do things like load default libraries or alter paths in ways that disrupt the workings of cortav. finally, because the bytecode file is not a binary executable, it cannot directly be given enhanced capabilities on unix-like systems through filesystem metadata — SUID and caps will be ignored by the kernel. while this is of no importance in ordinary operation, there are niche cases where this could be troublesome. a potentially superior alternative is to build cortav as a directly executable binary. when you tell make to build the binary version, it first compiles the driver to raw bytecode, then invokes tool/makeshim.lua to create a C source file embedding that bytecode, which is then piped into a C compiler. the huge downside, of course, is that building the cortav driver in this way requires a C compiler. however, the binary that it produces is easier to distribute to other computers — you can even statically link in lua so it can run on systems where lua isn’t installed. to build the binary version, run $ make build/cortav.bin. if you want to make the build to link lua statically, you’ll additionally need to supply lua’s library prefix in the variable lua-lib-prefix. some example incantations:

• $make build/cortav.bin lua-lib-prefix=/usr/lib on most Linux distros • $ make build/cortav.bin lua-lib-prefix=/usr/local/lib on FreeBSD
• $make build/cortav.bin lua-lib-prefix=$(nix path-info nixpkgs.lua5_3)/lib on NixOS, or on OSX if you’re using the Nix package manager

alternately, you can build lua yourself and link the static library in place without installing it systemwide, which is useful if you want to build a specialized version of lua to link with (or if the sysop doesn’t want your grubby luser hands all over his precious filesystem). note that if you’re building a self-contained version of cortav to distribute, you may want to slim down the binary by building lua without its parser, as the self-contained version of the driver only needs the bytecode VM part of lua to run.

#### build variables

there are numerous variables you can use to control the build process.

lua path to the lua interpreter cortav should be built and run with path to the lua compiler path to a bourne-compatible shell list of paths to extensions to enable, defaults to ext/*.lua. use extens+=path to add additional extensions from out of tree list of paths to renderers to enable, defaults to render/*.lua path to the build directory, defaults to build. change this for out-of-tree builds name of the executable to be generated, defaults to cortav specifies command line options that the viewer script should pass to cortav where files should be installed, defaults to $HOME/.local where executables should be installed, defaults to $(prefix)/bin if set, builds executables with debugging symbols; if absent, executables are stripped if set, embeds character class data for supported multibyte encodings into the program. on by default; \$ make encoding-data= to unset path to the UnicodeData.txt file for UCS-based encodings like UTF-8. by default it is automatically downloaded with curl where to download UnicodeData.txt from, if encoding-data-ucs is not changed. defaults to the unicode consortium website

#### deterministic builds

some operating systems, like NixOS, require packages that can be built in reproducible ways. this implies that all data, all state that goes into producing a package needs to be accounted for before the build proper begins. the cortav build process needs to be slightly altered to support such a build process.

while the cortav specification itself does not concern itself with matters like whether a particular character is a numeral or a letter, optimal typesetting in some cases requires such information. this is the case for the equation span- and block-types, which need to be able to distinguish between literals, variables, and mathematical symbols in the equations they format2. the ASCII charset is small enough that exhaustive character class information can be manually hardcoded into a cortav implementation, the various encodings of Unicode most certainly are not.

for this reason, the reference implementation of cortav embeds the file UnicodeData.txt, a database maintained by the Unicode Consortium. this is a rather large file that updates for each new Unicode version, so it is downloaded as part of the build process. to build on NixOS, you’ll need to either disable the features that rely on this database (not recommended), or download the database yourself and tell the build script where to find it. this is the approach the official nix expression will take when i can be bothered to write it. see the examples below for how to conduct a deterministic build

do note that no cortav implementation needs to concern itself with character class data. this functionality is provided in the reference implementation strictly as an (optional) extension to the spec to improve usability, not as a normative requirement.

### switches

cortav.lua offers various switches to control its behavior.

longshortfunction
--out file-osets the output file (default stdout)
--log file-lsets the log file (default stderr)
--define var val-dsets the context variable var to val
--mode-set mode-yactivates the mode with ID mode
--mode-clear mode-ndisables the mode with ID mode
--mode id val-mconfigures mode id with the value val
--mode-set-weak mode-Yactivates the mode with ID mode if the source file does not specify otherwise
--mode-clear-weak mode-Ndisables the mode with ID mode if the source file does not specify otherwise
--mode-weak id val-Mconfigures mode id with the value val if the source file does not specify otherwise
--help-hdisplay online help
--version-Vdisplay the interpreter version

### modes

most of cortav.lua”s implementation-specific behavior is controlled by use of modes. these are namespaced options which may have a boolean, string, or numeric value. boolean modes are set with the -y -n flags; other modes use the -m flags.

most modes are defined by the renderer backend. the following modes affect the behavior of the frontend:

IDtypeeffect
render:formatstringselects the renderer (default html)
parse:show-treeflagdumps the parse tree to the log after parsing completes

## renderers

cortav.lua implements a frontend-backend architecture, separating the parsing stage from the rendering stage. this means new renderers can be added to cortav.lua relatively easily. currently, only an HTML renderer is included; however, a groff backend is planned at some point in the future, so that PDFs and manpages can be generated from cortav files.

### html

the HTML renderer is activated with the incantation -m render:format html. it is currently the default backend. it produces a single HTML file, optionally with CSS styling data, from a .ct input file.

#### modes

html supports the following modes:

• string (css length) html:width sets a maximum width for the body content in order to make the page more readable on large displays
• number html:accent applies an accent hue to the generated webpage. the hue is specified in degrees, e.g. -m html:accent 0 applies a red accent.
• flag html:dark-on-light uses dark-on-light styling, instead of the default light-on-dark
• flag html:fossil-uv outputs an HTML snippet suitable for use with the Fossil VCS webserver. this is intended to be used with the unversioned content mechanism to host rendered versions of documentation written in cortav that’s stored in a Fossil repository.
• number html:hue-spread generates a color palette based on the supplied accent hue. the larger the value, the more the other colors diverge from the accent hue.
• string html:link-css generates a document linking to the named stylesheet
• flag html:gen-styles embeds appropriate CSS styles in the document (default on)
• flag html:snippet produces a snippet of html instead of an entire web page. note that proper CSS scoping is not yet implemented (and can’t be implemented hygienically since scoped was removed 😢)
• string html:title specifies the webpage titlebar contents (normally autodetected from the document based on headings or directives)
• string html:font specifies the default font to use when rendering as a CSS font specification (e.g. -m html:font ”Alegreya, Junicode, Georgia, “Times New Roman”)

#### directives

html supplies the following render directives.

• %html link rel mime href: inserts a <link> tag in the header, for example, to link in an alternate stylesheet, or help feed readers find your atom or rss feed.
• %html link alternate\ stylesheet text/css /res/style2.css
• %html link alternate application/atom+xml /feed.atom
• %html style id: adds the stylesheet referenced by id into the document stylesheet. the stylesheet is specified using a resource.

#### stylesheets

the html backend offers some additional directives for external CSS files that are embedded into the document, in order to simplify integration with the accent mechanism. these are:

• @fg: resolves to a color expression denoting the selected foreground color. equivalent to tone(1)
• @bg: resolves to a color expression denoting the selected background color. equivalent to tone(0)
• @tone[/alpha](fac [shift [saturate]] ): resolves to a color expression. fac is a floating-point value scaling from the background color to the foreground color. shift is a value in degrees controlling how far the hue will shift relative to the accent. saturate is a floating-point value controlling how satured the color is.

### groff

the groff backend produces a text file suitable for supplying to a groff compiler. groff is the GNU implementation of a venerable typesetting system from the early days of UNIX

you can produce a final output directly by piping from the cortav driver into groff. if your document uses an encoding other than ASCII, you’ll need to notify groff of this with the -K flag. for example, to render a UTF8 cortav file to PDF:

in the future, it is planned to enable the driver to operate groff automatically and directly produce the desired output format when the binary wrapper is in use. doing so securely and hygienically is not possible in pure lua, however.

#### modes

groff supports the following modes:

• string groff:annotate controls how footnotes will be handled.
• footnote places footnotes at the end of the page they are referenced on. if the same footnote is used on multiple pages, it will be duplicated on each.
• secnote places footnotes at the end of each section. footnotes used in multiple sections will be duplicated for each
• endnote places all footnotes at the end of the rendered document.
• string groff:title-page takes an identifier that names a section. this section will be treated as the title page for the document.
• string groff:title sets a specific title to be used in headers instead of relying on header heuristics

### directives

• %pragma title-page id sets the title page to section id. this causes it to be specially formatted, with a large, centered title and subtitle.

### quirks

if the toc extension is active but %toc directive is provided, the table of contents will be given its own section at the start of the document (after the title page, if any).

## further directions

it is eventually intended to support to following backends, if reasonably practicable.

• html: emit HTML and CSS code to typeset the document. in progress
• svg: emit SVG, taking advantage of its precise layout features to produce a nicely formatted and paginated document. pagination can be accomplished through emitting multiple files or by assigning one layer to each page. long term
• groff: the most important output backend, rivalling html. will allow the document to be typeset in a wide variety of formats, including PDF and manpage. short term
• gemtext: essentially a downrezzing of cortav to make it readable to Gemini clients
• ast: produces a human- and/or machine-readable dump of the document’s syntax tree, to aid in debugging or for interoperation with systems that do not support cortav direcly. mode ast:repr wil allow selecting formats for the dump. ast:rel can be tree (the default) to emit a hierarchical representation, or flat to emit an array of nodes that convey hierarchy by naming one another3, rather than being placed inside one another. tree is easier for humans to parse; flat is easier for computers. origin information can be included for each node with the flag ast:debug-syms, but be aware this will greatly increase file size.
• tabtree (default): a hierarchical tree view, with the number of tabs preceding an item showing its depth in the tree
• sexp
• binary: emit a raw binary format that is easier for programs to read. maybe an lmdb or cdb file?
• json

some formats may eventually warrant their own renderer, but are not a priority:

• text: cortav source files are already plain text, but a certain amount of layout could be done using ascii art.
• ansi: emit sequences of ANSI escape codes to lay out a document in a terminal-friendly way
• tex: TeX is an unholy abomination and i neither like nor use it, but lots of people do and if cortav ever catches on, a TeX backend should probably be written eventually.

PDF is not on either list because it’s a nightmarish mess of a format and groff, which is installed on most linux systems already, can easily generate PDFs

### LCH support

right now, the use of color in the HTML renderer is very unsatisfactory. the accent mechanism operates on the basis of the CSS HSL function, which is not perceptually uniform; different hues will present different mixes of brightness and some (yellows?) may be ugly or unreadable.

the ideal solution would be to simply switch to using LCH based colors. unfortunately, only Safari actually supports the LCH color function right now, and it’s unlikely (unless Lea Verou and her husband manage to work a miracle) that Colors Level 4 is going to be implemented very widely any time soon.

this leaves us in an awkward position. we can of course do the math ourselves, working in LCH to implement the internal @tone macro, and then “converting” these colors to HSL. unfortunately, you can’t actually convert from LCH to HSL; it’s like converting from pounds to kilograms. LCH can represent any color the human visual system can perceive; sRGB can’t, and CSS HSL is implemented in sRGB. however, we could at least approximate something that would allow for perceptually uniform brightness, which would be an improvement, and this is probably the direction to go in, unless a miracle occurs and lch() or color() pop up in Blink.

it may be possible to do a more reasonable job of handling colors in the postscript and TeX outputs. unsure about SVG but i assume it suffers the same problems HTML/CSS do. does groff even support color??

### intent files

there’s currently no standard way to describe the intent and desired formatting of a document besides placing pragmata in the source file itself. this is extremely suboptimal, as when generating collections of documents, it’s ideal to be able to keep all formatting information in one place. users should also be able to specify their own styling overrides that describe the way they prefer to read cortav files, especially for uses like gemini or gopher integration.

at some point soon cortav` needs to address this by adding intent files that can be activated from outside the source file, such as with a command line flag or a configuration file setting. these will probably consist of lines that are interpreted as pragmata. in addition to the standard intent format however, individual implementations should feel free to provide their own ways to provide intent metadata; e.g. the reference implementation, which has a lua interpreter available, should be able to take a lua script that runs after the parse stage and generates . this will be particularly useful for the end-user who wishes to specify a particular format she likes reading her files in without forcing that format on everyone she sends the compiled document to, as it will be able to interrogate the document and make intelligent decisions about what pragmata to apply.

intent files should also be able to define resources, context variables, and macros.

2

sadly, i was not at any point consulted by any of the generations of mathematicians stretching back into antiquity, who as a direct consequence devised their notations without any regard for machine-readability. for shame!

1