package ext
- Alphabetic
- Public
- All
Type Members
-
class
ExtensionParsers extends AnyRef
Provides the parsers for all types of extensions (directives and text roles).
Value Members
-
object
Directives
API for creating directives, the extension mechanism of reStructuredText.
API for creating directives, the extension mechanism of reStructuredText.
The API did not aim to mimic the API of the original Python reference implementation. Instead the goal was to create an API that is idiomatic Scala, fully typesafe and as concise as possible. Yet it should be flexible enough to semantically support the options of the Python directives, so that ideally most existing Python directives could theoretically get ported to Laika.
Comparison with Laika Directives
Extensions defined in the way described in this chapter could still be used when parsing the markup documents with a different reStructuredText implementation, as they are fully compatible with the original specification.
If this is not a requirement you may alternatively use the Laika variant of directives. This would give you the following advantages:
- The syntax definition is simpler, while offering the same flexibility. - The directive may be used in other parsers, too, like in the Markdown parser. - The directive may also be used in templates. For details on these alternative directive types see http://typelevel.org/Laika/latest/05-extending-laika/03-implementing-directives.html.
Implementing a Directive
Entry points are the
BlockDirective
andSpanDirective
objects. The Python reference parser does not make this distinction on the API level, but does this internally based on the context a directive is parsed in. Since Laika APIs are typesafe, the distinction is necessary since block level and span level directives create different types of document tree nodes. ASpanDirective
can only be used in a substitution definition which can then be used within flow elements. ABlockDirective
can be used directly in any location other block level content like paragraphs or lists can be used.A directive may consist of any combination of arguments, fields and body elements:
.. myDirective:: arg1 arg2 :field1: value1 :field2: value2 This is the body of the directive. It may consist of any standard or custom block-level and inline markup.
In the example above
arg1
andarg2
are arguments,field1
andfield2
are fields, and followed by body elements after a blank line. If there are no arguments or fields the blank line may be omitted. For the full specification, see http://docutils.sourceforge.net/docs/ref/rst/restructuredtext.html#directives.For each of these directive elements, the API offers a method to specify whether the element is required or optional, and an optional function to convert or validate the parsed value.
Basic Example
Consider the following simple example of a directive with just one argument and a body:
.. note:: This is the title This is the body of the note.
The implementation of this directive could look like this:
case class Note (title: String, content: Seq[Block], options: Options = NoOpt) extends Block with BlockContainer[Note] object MyDirectives extends RstExtensionRegistry { val blockDirectives = Seq( BlockDirective("note") { (argument(withWS = true) ~ blockContent).map { case title ~ content => Note(title, content) } } ) val spanDirectives = Nil val textRoles = Nil ) val transformer = Transformer .from(ReStructuredText) .to(HTML) .using(MyDirectives) .build
The
argument()
method specifies a required argument of typeString
(since no conversion function was supplied). We need to set thewithWS
flag to true as an argument cannot have whitespace per default. TheblockContent
method specifies standard block content (any block-level elements that are supported in normal blocks, too) which results in a parsed value of typeSeq[Block]
. Finally you need to provide a function that accepts the results of the specified directive elements as parameters (of the corresponding type). Here we created a case class with a matching signature so can pass it directly as the target function. For a block directive the final result has to be of typeBlock
which theNote
class satisfies. Finally the directive gets registered with theReStructuredText
parser.Adding Converters and Validators
If any conversion or validation is required on the individual parts of the directive they can be passed to the corresponding function:
def nonNegativeInt (value: String) = try { val num = value.toInt Either.cond(num >= 0, num, s"not a positive int: $num") } catch { case e: NumberFormatException => Left(s"not a number: $value") } case class Message (severity: Int, content: Seq[Block], options: Options = NoOpt) extends Block with BlockContainer[Message] object MyDirectives extends RstExtensionRegistry { val blockDirectives = Seq( BlockDirective("message") { (argument(nonNegativeInt) ~ blockContent).map { case severity ~ content => Message(severity, content) } } ) val spanDirectives = Nil val textRoles = Nil )
The function has to provide an
Either[String, T]
as a result. ALeft
result will be interpreted as an error by the parser with the string being used as the message and an instance ofInvalidBlock
containing the validator message and the raw source of the directive will be inserted into the document tree. In this case the final function (Message
) will never be invoked. ARight
result will be used as an argument to the final function. Note how the case class now expects anInt
as the first parameter.Optional Elements
Finally arguments and fields can also be optional. In case they are missing, the directive is still considered valid and
None
will be passed to your function:case class Message (severity: Option[Int], content: Seq[Block], options: Options = NoOpt) extends Block with BlockContainer[Message] object MyDirectives extends RstExtensionRegistry { val blockDirectives = Seq( BlockDirective("message") { (optArgument(nonNegativeInt) ~ blockContent).map { case severity ~ content => Message(severity.getOrElse(0), content) } } ) val spanDirectives = Nil val textRoles = Nil }
The argument may be missing, but if it is present it has to pass the specified validator.
In case of multiple arguments, the order you specify them is also the order in which they are parsed from the directive markup, with the only exception being that required arguments will always be parsed before optional ones, and arguments with whitespace need to come last.
-
object
ExtensionParsers
Provides the parsers for all types of extensions (directives and text roles).
-
object
TextRoles
API for creating interpreted text roles, the extension mechanism for inline elements of reStructuredText.
API for creating interpreted text roles, the extension mechanism for inline elements of reStructuredText.
The API did not aim to mimic the API of the original Python reference implementation. Instead the goal was to create an API that is idiomatic Scala, fully typesafe and as concise as possible. Yet it should be flexible enough to semantically support the options of the Python text roles, so that ideally most existing Python text roles could theoretically get ported to Laika.
Implementing a Directive
Entry point for creating a new role is the
TextRole
object. It allows to specify the following aspects that define a text role:- The name with which it can be referred to by both, a span of interpreted text and a role directive to further customize it.
- The default value, that should get passed to the role function in case it is used directly in interpreted text without customization through a role directive.
- The role directive that specifies how the role can be customized. The options for role directives are almost identical to regular directives, the only difference being that role directives do not support arguments, only fields and body elements.
- The actual role function. It gets invoked for each occurrence of interpreted text
that refers to this role, either directly by name or to the name of a role directive
that customized this role. The first argument is either the default value
or the result of the role directive, the second is the actual text of the interpreted
text span. The return value of the role function is the actual
Span
instance that the original interpreted text should be replaced with.
Basic Example
A role directive may consist of any combination of fields and body elements:
.. role:: ticket(link) :base-url: http://www.company.com/tickets/
In the example above
ticket
is the name of the customized role,link
the name of the base role andbase-url
the value that overrides the default defined in the base role. For the specification details on role directives see http://docutils.sourceforge.net/docs/ref/rst/directives.html#custom-interpreted-text-roles.Before such a role directive can be used, an implementation has to be provided for the base role with the name
link
. For more details on implementing directives see laika.rst.ext.Directives.The implementation of the
link
text role could look like this:val textRole = TextRole("link", "http://www.company.com/main/")(field("base-url")) { (base, text) => Link(List(Text(text)), base + text) } object MyDirectives extends RstExtensionRegistry { val textRoles = Seq(textRole) val spanDirectives = Seq() val blockDirectives = Seq() } val transformer = Transformer .from(ReStructuredText) .to(HTML) .using(MyDirectives) .build
We specify the name of the role to be
link
, and the default value the URL provided as the second argument. The second parameter list specifies the role directive implementation, in this case only consisting of a call tofield("base-url")
which specifies a required field of typeString
(since no conversion function was supplied). The type of the result of the directive has to match the type of the default value. Finally the role function is defined that accepts two arguments. The first is the base url, either the default in case the base role is used directly, or the value specified with thebase-url
field in a customized role. The second is the actual text from the interpreted text span. Finally the directive gets registered with theReStructuredText
parser.If you need to define more fields or body content they can be added with the
~
combinator just like with normal directives. Likewise you can specify validators and converters for fields and body values like documented in laika.rst.ext.Directives.Using the Text Role in Markup
Our example role can then be used in the following ways:
Using the base role directly:
For details read our :link:`documentation`.
This would result in the following HTML:
For details read our <a href="http://www.company.com/main/documentation">documentation</a>.
Using the customized role called
ticket
:For details see ticket :ticket:`344`.
This would result in the following HTML:
For details see ticket <a href="http://www.company.com/ticket/344">344</a>.