diff options
34 files changed, 870 insertions, 0 deletions
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..b63da45 --- /dev/null +++ b/.gitignore @@ -0,0 +1,42 @@ +.gradle +build/ +!gradle/wrapper/gradle-wrapper.jar +!**/src/main/**/build/ +!**/src/test/**/build/ + +### IntelliJ IDEA ### +.idea/modules.xml +.idea/jarRepositories.xml +.idea/compiler.xml +.idea/libraries/ +*.iws +*.iml +*.ipr +out/ +!**/src/main/**/out/ +!**/src/test/**/out/ + +### Eclipse ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache +bin/ +!**/src/main/**/bin/ +!**/src/test/**/bin/ + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ + +### VS Code ### +.vscode/ + +### Mac OS ### +.DS_Store
\ No newline at end of file diff --git a/build.gradle.kts b/build.gradle.kts new file mode 100644 index 0000000..5081342 --- /dev/null +++ b/build.gradle.kts @@ -0,0 +1,22 @@ +plugins { + kotlin("jvm") version "1.9.22" +} + +group = "org.example" +version = "1.0-SNAPSHOT" + +repositories { + mavenCentral() +} + +dependencies { + implementation("org.jetbrains:markdown:0.5.0") + testImplementation("org.jetbrains.kotlin:kotlin-test") +} + +tasks.test { + useJUnitPlatform() +} +kotlin { + jvmToolchain(17) +}
\ No newline at end of file diff --git a/data/test.md b/data/test.md new file mode 100644 index 0000000..ccd4932 --- /dev/null +++ b/data/test.md @@ -0,0 +1,9 @@ +# Hello World + +***lol* hehe** + +```java +public class ObjectControllerFactoryManagerProvider<T extends ObjectControllerFactoryManager<T>> { + +} +```
\ No newline at end of file diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..7fc6f1f --- /dev/null +++ b/gradle.properties @@ -0,0 +1 @@ +kotlin.code.style=official diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar Binary files differnew file mode 100644 index 0000000..7f93135 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.jar diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..3fa8f86 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.4-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists @@ -0,0 +1,249 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..93e3f59 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,92 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/settings.gradle.kts b/settings.gradle.kts new file mode 100644 index 0000000..ec04c91 --- /dev/null +++ b/settings.gradle.kts @@ -0,0 +1,2 @@ +rootProject.name = "blog" + diff --git a/src/main/kotlin/moe/nea/blog/md/Begin.kt b/src/main/kotlin/moe/nea/blog/md/Begin.kt new file mode 100644 index 0000000..482c114 --- /dev/null +++ b/src/main/kotlin/moe/nea/blog/md/Begin.kt @@ -0,0 +1,8 @@ +package moe.nea.blog.md + +import java.io.PrintStream + +class Begin : MarkdownFormat { + override fun debugFormat(printStream: PrintStream) { + } +}
\ No newline at end of file diff --git a/src/main/kotlin/moe/nea/blog/md/BlockParser.kt b/src/main/kotlin/moe/nea/blog/md/BlockParser.kt new file mode 100644 index 0000000..2ca812f --- /dev/null +++ b/src/main/kotlin/moe/nea/blog/md/BlockParser.kt @@ -0,0 +1,7 @@ +package moe.nea.blog.md + +interface BlockParser { + fun detect(line: String): Boolean + fun parse(parser: MarkdownParser): MarkdownBlock + val prio: Int +}
\ No newline at end of file diff --git a/src/main/kotlin/moe/nea/blog/md/BlogPost.kt b/src/main/kotlin/moe/nea/blog/md/BlogPost.kt new file mode 100644 index 0000000..25ec13f --- /dev/null +++ b/src/main/kotlin/moe/nea/blog/md/BlogPost.kt @@ -0,0 +1,11 @@ +package moe.nea.blog.md + +import java.io.File + + +fun main() { + val parser = MarkdownParser(File("data/test.md").readText()) + parser.addDefaultParsers() + val doc = parser.readDocument() + doc.debugFormat(System.out) +}
\ No newline at end of file diff --git a/src/main/kotlin/moe/nea/blog/md/Bold.kt b/src/main/kotlin/moe/nea/blog/md/Bold.kt new file mode 100644 index 0000000..aa46622 --- /dev/null +++ b/src/main/kotlin/moe/nea/blog/md/Bold.kt @@ -0,0 +1,11 @@ +package moe.nea.blog.md + +import java.io.PrintStream + +data class Bold(val inner: MarkdownFormat) : MarkdownFormat { + override fun debugFormat(printStream: PrintStream) { + printStream.print("<b>") + inner.debugFormat(printStream) + printStream.print("</b>") + } +}
\ No newline at end of file diff --git a/src/main/kotlin/moe/nea/blog/md/CodeBlock.kt b/src/main/kotlin/moe/nea/blog/md/CodeBlock.kt new file mode 100644 index 0000000..2882b77 --- /dev/null +++ b/src/main/kotlin/moe/nea/blog/md/CodeBlock.kt @@ -0,0 +1,18 @@ +package moe.nea.blog.md + +import moe.nea.blog.util.indent +import java.io.PrintStream + +data class CodeBlock(val language: String, val lines: List<String>) : MarkdownBlock { + override fun debugFormat(indent: Int, printStream: PrintStream) { + printStream.indent(indent) + printStream.println("<code lang=$language>") + lines.forEach { + printStream.indent(indent) + printStream.println(it) + } + printStream.indent(indent) + printStream.println("</code>") + } +} + diff --git a/src/main/kotlin/moe/nea/blog/md/CodeBlockParser.kt b/src/main/kotlin/moe/nea/blog/md/CodeBlockParser.kt new file mode 100644 index 0000000..0c894fe --- /dev/null +++ b/src/main/kotlin/moe/nea/blog/md/CodeBlockParser.kt @@ -0,0 +1,23 @@ +package moe.nea.blog.md + +object CodeBlockParser : BlockParser { + override fun detect(line: String): Boolean { + return line.startsWith("```") + } + + override fun parse(parser: MarkdownParser): MarkdownBlock { + val language = parser.consumeLine()!!.removePrefix("```") + val lines = mutableListOf<String>() + while (true) { + val line = parser.consumeLine() ?: error("Unfinished code block") + if (line == "```") + break + lines.add(line) + } + return CodeBlock(language, lines) + } + + override val prio: Int + get() = 10 + +}
\ No newline at end of file diff --git a/src/main/kotlin/moe/nea/blog/md/Document.kt b/src/main/kotlin/moe/nea/blog/md/Document.kt new file mode 100644 index 0000000..ce83ef1 --- /dev/null +++ b/src/main/kotlin/moe/nea/blog/md/Document.kt @@ -0,0 +1,11 @@ +package moe.nea.blog.md + +import java.io.PrintStream + +data class Document( + val list: List<MarkdownBlock> +) : MarkdownElement { + fun debugFormat(printStream: PrintStream) { + list.forEach { it.debugFormat(0, printStream) } + } +}
\ No newline at end of file diff --git a/src/main/kotlin/moe/nea/blog/md/FormatSequence.kt b/src/main/kotlin/moe/nea/blog/md/FormatSequence.kt new file mode 100644 index 0000000..94b55b9 --- /dev/null +++ b/src/main/kotlin/moe/nea/blog/md/FormatSequence.kt @@ -0,0 +1,11 @@ +package moe.nea.blog.md + +import java.io.PrintStream + +data class FormatSequence(val list: List<MarkdownFormat>) : MarkdownFormat { + constructor(vararg list: MarkdownFormat) : this(list.toList()) + + override fun debugFormat(printStream: PrintStream) { + list.forEach { it.debugFormat(printStream) } + } +}
\ No newline at end of file diff --git a/src/main/kotlin/moe/nea/blog/md/Header.kt b/src/main/kotlin/moe/nea/blog/md/Header.kt new file mode 100644 index 0000000..fab2306 --- /dev/null +++ b/src/main/kotlin/moe/nea/blog/md/Header.kt @@ -0,0 +1,11 @@ +package moe.nea.blog.md + +import moe.nea.blog.util.indent +import java.io.PrintStream + +data class Header(val level: Int, val text: String) : MarkdownBlock { + override fun debugFormat(indent: Int, printStream: PrintStream) { + printStream.indent(indent) + printStream.println("header level=$level: $text") + } +}
\ No newline at end of file diff --git a/src/main/kotlin/moe/nea/blog/md/HeaderParser.kt b/src/main/kotlin/moe/nea/blog/md/HeaderParser.kt new file mode 100644 index 0000000..928cf58 --- /dev/null +++ b/src/main/kotlin/moe/nea/blog/md/HeaderParser.kt @@ -0,0 +1,17 @@ +package moe.nea.blog.md + +object HeaderParser : BlockParser { + override fun detect(line: String): Boolean { + return line.matches("#+ .*".toRegex()) + } + + override fun parse(parser: MarkdownParser): MarkdownBlock { + val line = parser.consumeLine()!! + val level = line.indexOf(" ") + val text = line.substring(level).trim() + return Header(level, text) + } + + override val prio: Int + get() = 10 +}
\ No newline at end of file diff --git a/src/main/kotlin/moe/nea/blog/md/InlineParser.kt b/src/main/kotlin/moe/nea/blog/md/InlineParser.kt new file mode 100644 index 0000000..4b60963 --- /dev/null +++ b/src/main/kotlin/moe/nea/blog/md/InlineParser.kt @@ -0,0 +1,7 @@ +package moe.nea.blog.md + +interface InlineParser { + fun detect(lookback: MarkdownFormat, rest: String): Boolean + val specialSyntax: Set<Char> + fun parse(parser: MarkdownParser, text: String): Pair<MarkdownFormat, String> +}
\ No newline at end of file diff --git a/src/main/kotlin/moe/nea/blog/md/Italics.kt b/src/main/kotlin/moe/nea/blog/md/Italics.kt new file mode 100644 index 0000000..47d8db2 --- /dev/null +++ b/src/main/kotlin/moe/nea/blog/md/Italics.kt @@ -0,0 +1,11 @@ +package moe.nea.blog.md + +import java.io.PrintStream + +data class Italics(val inner: MarkdownFormat) : MarkdownFormat { + override fun debugFormat(printStream: PrintStream) { + printStream.print("<i>") + inner.debugFormat(printStream) + printStream.print("</i>") + } +}
\ No newline at end of file diff --git a/src/main/kotlin/moe/nea/blog/md/ItalicsParser.kt b/src/main/kotlin/moe/nea/blog/md/ItalicsParser.kt new file mode 100644 index 0000000..afecf79 --- /dev/null +++ b/src/main/kotlin/moe/nea/blog/md/ItalicsParser.kt @@ -0,0 +1,91 @@ +package moe.nea.blog.md + +object ItalicsParser : InlineParser { + override fun detect(lookback: MarkdownFormat, rest: String): Boolean { + return lookback is Whitespace && "\\*+[^ ].*".toRegex().matches(rest) + } + + override val specialSyntax: Set<Char> + get() = setOf('*') + + override fun parse(parser: MarkdownParser, text: String): Pair<MarkdownFormat, String> { + var firstStarCount = 0 + while (firstStarCount in text.indices) { + if (text[firstStarCount] != '*') break + firstStarCount++ + } + + if (firstStarCount < 1 || firstStarCount > 3) error("Invalid italics/bold sequence") + + val isBold = firstStarCount >= 2 + val isItalics = (firstStarCount % 2) == 1 + + val firstSequence = mutableListOf<MarkdownFormat>() + var remainingText = text.substring(firstStarCount) + var lastToken: MarkdownFormat = Begin() // TODO: dedicated begin token + while (true) { + val (element, next) = parser.parseInlineTextOnce(lastToken, remainingText) + remainingText = next + lastToken = element + firstSequence.add(element) + if (element !is Whitespace && next.startsWith("*")) break + } + + var secondStarCount = 0 + while (secondStarCount in remainingText.indices) { + if (remainingText[secondStarCount] != '*') break + secondStarCount++ + } + + if (secondStarCount > firstStarCount) + secondStarCount = firstStarCount + if (secondStarCount < 1) error("Invalid italics/bold sequence") + + remainingText = remainingText.substring(secondStarCount) + var firstElement = parser.collapseInlineFormat(firstSequence) + if (secondStarCount == 2) + firstElement = Bold(firstElement) + if (secondStarCount == 1) + firstElement = Italics(firstElement) + if (secondStarCount == firstStarCount) { + if (isBold) + firstElement = Bold(firstElement) + if (isItalics) + firstElement = Italics(firstElement) + return Pair(firstElement, remainingText) + } + + val secondSequence = mutableListOf<MarkdownFormat>() + lastToken = Begin() + while (true) { + val (element, next) = parser.parseInlineTextOnce(lastToken, remainingText) + remainingText = next + lastToken = element + secondSequence.add(element) + if (element !is Whitespace && next.startsWith("*")) break + } + + var thirdStarCount = 0 + while (thirdStarCount in remainingText.indices) { + if (remainingText[thirdStarCount] != '*') break + thirdStarCount++ + } + + if (thirdStarCount > firstStarCount - secondStarCount) + thirdStarCount = firstStarCount + + remainingText = remainingText.substring(thirdStarCount) + + if (thirdStarCount != firstStarCount - secondStarCount) { + error("Invalid italics/bold sequence") + } + var secondElement = parser.collapseInlineFormat(secondSequence) + var combined: MarkdownFormat = FormatSequence(firstElement, secondElement) + if (thirdStarCount == 1) + combined = Italics(combined) + if (thirdStarCount == 2) + combined = Bold(combined) + return Pair(combined, remainingText) + } + +}
\ No newline at end of file diff --git a/src/main/kotlin/moe/nea/blog/md/Link.kt b/src/main/kotlin/moe/nea/blog/md/Link.kt new file mode 100644 index 0000000..f8fc858 --- /dev/null +++ b/src/main/kotlin/moe/nea/blog/md/Link.kt @@ -0,0 +1,11 @@ +package moe.nea.blog.md + +import java.io.PrintStream + +data class Link(val label: MarkdownFormat?, val target: String) : MarkdownFormat { + override fun debugFormat(printStream: PrintStream) { + printStream.print("<link target=$target>") + label?.debugFormat(printStream) + printStream.print("</link>") + } +}
\ No newline at end of file diff --git a/src/main/kotlin/moe/nea/blog/md/MarkdownBlock.kt b/src/main/kotlin/moe/nea/blog/md/MarkdownBlock.kt new file mode 100644 index 0000000..fc432ef --- /dev/null +++ b/src/main/kotlin/moe/nea/blog/md/MarkdownBlock.kt @@ -0,0 +1,7 @@ +package moe.nea.blog.md + +import java.io.PrintStream + +interface MarkdownBlock : MarkdownElement { + fun debugFormat(indent: Int, printStream: PrintStream) +}
\ No newline at end of file diff --git a/src/main/kotlin/moe/nea/blog/md/MarkdownElement.kt b/src/main/kotlin/moe/nea/blog/md/MarkdownElement.kt new file mode 100644 index 0000000..74aac6d --- /dev/null +++ b/src/main/kotlin/moe/nea/blog/md/MarkdownElement.kt @@ -0,0 +1,3 @@ +package moe.nea.blog.md + +interface MarkdownElement {}
\ No newline at end of file diff --git a/src/main/kotlin/moe/nea/blog/md/MarkdownFormat.kt b/src/main/kotlin/moe/nea/blog/md/MarkdownFormat.kt new file mode 100644 index 0000000..d647854 --- /dev/null +++ b/src/main/kotlin/moe/nea/blog/md/MarkdownFormat.kt @@ -0,0 +1,7 @@ +package moe.nea.blog.md + +import java.io.PrintStream + +interface MarkdownFormat : MarkdownElement { + fun debugFormat(printStream: PrintStream) +}
\ No newline at end of file diff --git a/src/main/kotlin/moe/nea/blog/md/MarkdownParser.kt b/src/main/kotlin/moe/nea/blog/md/MarkdownParser.kt new file mode 100644 index 0000000..86b92d2 --- /dev/null +++ b/src/main/kotlin/moe/nea/blog/md/MarkdownParser.kt @@ -0,0 +1,96 @@ +package moe.nea.blog.md + +import moe.nea.blog.util.indentSize +import java.util.* + + +class MarkdownParser(source: String) { + private val lines = source.lines() + private var lineIndex = 0 + private var blockIndents = 0 + private val indentStack = Stack<Int>() + + private val blockParsers = mutableListOf<BlockParser>() + private val inlineParsers = mutableListOf<InlineParser>() + + fun findParserFor(line: String): BlockParser? { + return blockParsers.filter { it.detect(line) } + .maxByOrNull { it.prio } + } + + fun readChildBlock(): MarkdownBlock? { + val peek = peekLine() ?: return null + val blockParser = findParserFor(peek) ?: ParagraphParser + return blockParser.parse(this) + } + + fun pushIndent(newIndent: Int) { + require(newIndent > blockIndents) + indentStack.push(blockIndents) + blockIndents = newIndent + } + + fun popIndent() { + blockIndents = indentStack.pop() + } + + fun consumeLine(): String? { + val line = peekLine() + if (line != null) + lineIndex++ + return line + } + + fun peekLine(): String? { + if (lineIndex !in lines.indices) return null + val line = lines[lineIndex] + val indent = line.indentSize() + if (indent != null && indent < blockIndents) + return null + return line.substring(blockIndents) + } + + fun parseInlineTextOnce(lookback: MarkdownFormat, text: String): Pair<MarkdownFormat, String> { + val parser = inlineParsers.find { it.detect(lookback, text) } + if (parser != null) + return parser.parse(this, text) + require(!text.isEmpty()) // TODO handle empty string + if (text[0] == ' ') + return Pair(Whitespace(), text.substring(1)) + val nextSpecial = text.indexOfFirst { it in inlineParsers.flatMap { it.specialSyntax } || it == ' ' } + return Pair(Word(text.substring(0, nextSpecial)), text.substring(nextSpecial)) + } + + fun parseInlineText(text: String): MarkdownFormat { + val seq = mutableListOf<MarkdownFormat>() + var remaining = text + var lastToken: MarkdownFormat = Begin() + while (remaining.isNotEmpty()) { + val (tok, next) = parseInlineTextOnce(lastToken, remaining) + seq.add(tok) + lastToken = tok + remaining = next + } + return collapseInlineFormat(seq) + } + + fun collapseInlineFormat(sequence: List<MarkdownFormat>): MarkdownFormat { + return FormatSequence(sequence) + } + + fun readDocument(): Document { + val list = mutableListOf<MarkdownBlock>() + while (true) { + val block = readChildBlock() ?: break + list.add(block) + } + return Document(list) + } + + fun addDefaultParsers() { + blockParsers.add(CodeBlockParser) + blockParsers.add(HeaderParser) + inlineParsers.add(ItalicsParser) + } +} + diff --git a/src/main/kotlin/moe/nea/blog/md/Paragraph.kt b/src/main/kotlin/moe/nea/blog/md/Paragraph.kt new file mode 100644 index 0000000..54f688b --- /dev/null +++ b/src/main/kotlin/moe/nea/blog/md/Paragraph.kt @@ -0,0 +1,12 @@ +package moe.nea.blog.md + +import moe.nea.blog.util.indent +import java.io.PrintStream + +data class Paragraph(val format: MarkdownFormat) : MarkdownBlock { + override fun debugFormat(indent: Int, printStream: PrintStream) { + printStream.indent(indent) + format.debugFormat(printStream) + printStream.println() + } +}
\ No newline at end of file diff --git a/src/main/kotlin/moe/nea/blog/md/ParagraphParser.kt b/src/main/kotlin/moe/nea/blog/md/ParagraphParser.kt new file mode 100644 index 0000000..328c49b --- /dev/null +++ b/src/main/kotlin/moe/nea/blog/md/ParagraphParser.kt @@ -0,0 +1,31 @@ +package moe.nea.blog.md + +object ParagraphParser : BlockParser { + override fun detect(line: String): Boolean { + return true + } + + override fun parse(parser: MarkdownParser): MarkdownBlock { + var text = "" + var emptyLineCount = 0 + while (true) { + val line = parser.peekLine() ?: break + if (parser.findParserFor(line) != null) break + val trimmedLine = parser.consumeLine()!!.trim() + if (trimmedLine == "") { + emptyLineCount++ + } else { + emptyLineCount = 0 + } + if (emptyLineCount == 2) { + break + } + text += " $trimmedLine" + } + return Paragraph(parser.parseInlineText(text)) + } + + override val prio: Int + get() = -10 + +}
\ No newline at end of file diff --git a/src/main/kotlin/moe/nea/blog/md/Text.kt b/src/main/kotlin/moe/nea/blog/md/Text.kt new file mode 100644 index 0000000..fb89ff3 --- /dev/null +++ b/src/main/kotlin/moe/nea/blog/md/Text.kt @@ -0,0 +1,9 @@ +package moe.nea.blog.md + +import java.io.PrintStream + +data class Text(val text: String) : MarkdownFormat { + override fun debugFormat(printStream: PrintStream) { + printStream.print(printStream) + } +}
\ No newline at end of file diff --git a/src/main/kotlin/moe/nea/blog/md/Whitespace.kt b/src/main/kotlin/moe/nea/blog/md/Whitespace.kt new file mode 100644 index 0000000..6a44152 --- /dev/null +++ b/src/main/kotlin/moe/nea/blog/md/Whitespace.kt @@ -0,0 +1,9 @@ +package moe.nea.blog.md + +import java.io.PrintStream + +class Whitespace : MarkdownFormat { + override fun debugFormat(printStream: PrintStream) { + printStream.print(" ") + } +}
\ No newline at end of file diff --git a/src/main/kotlin/moe/nea/blog/md/Word.kt b/src/main/kotlin/moe/nea/blog/md/Word.kt new file mode 100644 index 0000000..ff89af5 --- /dev/null +++ b/src/main/kotlin/moe/nea/blog/md/Word.kt @@ -0,0 +1,9 @@ +package moe.nea.blog.md + +import java.io.PrintStream + +data class Word(val text: String) : MarkdownFormat { + override fun debugFormat(printStream: PrintStream) { + printStream.print(text) + } +}
\ No newline at end of file diff --git a/src/main/kotlin/moe/nea/blog/util/Indent.kt b/src/main/kotlin/moe/nea/blog/util/Indent.kt new file mode 100644 index 0000000..5a61a48 --- /dev/null +++ b/src/main/kotlin/moe/nea/blog/util/Indent.kt @@ -0,0 +1,5 @@ +package moe.nea.blog.util + +fun Appendable.indent(indent: Int) { + append(" ".repeat(indent)) +}
\ No newline at end of file diff --git a/src/main/kotlin/moe/nea/blog/util/IndentSize.kt b/src/main/kotlin/moe/nea/blog/util/IndentSize.kt new file mode 100644 index 0000000..de6a91a --- /dev/null +++ b/src/main/kotlin/moe/nea/blog/util/IndentSize.kt @@ -0,0 +1,10 @@ +package moe.nea.blog.util + +fun String.indentSize(): Int? { + var i = 0 + while (i in indices) { + if (this[i] != ' ') return i + i++ + } + return null +}
\ No newline at end of file |