Skip to content

Commit

Permalink
MarkdownPart: identify mdoc code fence modifier
Browse files Browse the repository at this point in the history
  • Loading branch information
kitbellew committed Nov 3, 2023
1 parent b8b3fd7 commit 61b593b
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 9 deletions.
15 changes: 6 additions & 9 deletions mdoc/src/main/scala/mdoc/internal/markdown/FenceInput.scala
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,10 @@ case class StringFenceInput(block: CodeFence, input: Input, mod: Str)
case class ScalaFenceInput(block: CodeFence, input: Input, mod: Modifier)

class FenceInput(ctx: Context, baseInput: Input) {
def getModifier(info: Text): Option[Modifier] = {
val string = info.value.stripLineEnd
if (!string.startsWith("scala mdoc")) None
else {
if (!string.contains(':')) Some(Modifier.Default())
def getModifier(block: CodeFence): Option[Modifier] = {
block.getMdocMode.flatMap { mode =>
if (mode.isEmpty) Some(Modifier.Default())
else {
val mode = string.stripPrefix("scala mdoc:").takeWhile(!_.isWhitespace)
Modifier(mode)
.orElse {
val (name, info) = mode.split(":", 2) match {
Expand All @@ -47,15 +44,15 @@ class FenceInput(ctx: Context, baseInput: Input) {
}
}
.orElse {
invalid(info, s"Invalid mode '$mode'")
invalid(block.info, s"Invalid mode '$mode'")
None
}
}
}
}

private def invalid(info: Text, message: String): Unit = {
val offset = "scala mdoc:".length
val offset = CodeFence.tag.length + 1 // includes colon
val start = info.posBeg + offset
val end = info.posEnd - 1
val pos = Position.Range(baseInput, start, end)
Expand Down Expand Up @@ -95,7 +92,7 @@ class FenceInput(ctx: Context, baseInput: Input) {
}
}
def unapply(block: CodeFence): Option[ScalaFenceInput] = {
getModifier(block.info) match {
getModifier(block) match {
case Some(mod) =>
if (isValid(block.info, mod)) {
val input = Input.Slice(baseInput, block.body.posBeg, block.body.posEnd)
Expand Down
14 changes: 14 additions & 0 deletions parser/src/main/scala/mdoc/parser/MarkdownPart.scala
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,11 @@ final case class Text(value: String) extends MarkdownPart {
} else this
}
}

object CodeFence {
val tag = "scala mdoc"
}

final case class CodeFence(
openBackticks: Text,
info: Text,
Expand All @@ -154,4 +159,13 @@ final case class CodeFence(
var newBody = Option.empty[String]
def indent: Int = tag.value.length
def hasBlankTag: Boolean = tag.value.forall(_.isWhitespace)

def getMdocMode: Option[String] = {
val infoStr = info.value.stripLineEnd
val mode = infoStr.stripPrefix(CodeFence.tag)
if (mode eq infoStr) None
else if (mode.isEmpty) Some("")
else if (mode.charAt(0) != ':') None
else Some(mode.substring(mode.indexWhere(!_.isWhitespace, 1).max(1)))
}
}

0 comments on commit 61b593b

Please sign in to comment.