Skip to content

Instantly share code, notes, and snippets.

@fumokmm
Last active December 16, 2015 03:09
Show Gist options
  • Save fumokmm/5367413 to your computer and use it in GitHub Desktop.
Save fumokmm/5367413 to your computer and use it in GitHub Desktop.
「GroovyでMarkdownパーサーを作ろう」 http://npnl.hatenablog.jp/entry/series/fumomarkdowng
// 第一引数の内容を読み込む
def lines = new File(args[0]).readLines()
// Markdown形式をHTMLに変換
def md = new Markdown()
def contents = lines.collect {
md.headerAtx(it)
}.join('\n')
// 読み込んだ内容をHTMLのテンプレートに流し込む
println """<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>fumomarkdowng</title>
</head>
<body>
${contents}
</body>
</html>"""
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>fumomarkdowng</title>
</head>
<body>
<h1>level1</h1>
<h2>level2</h2>
<h3>level3</h3>
</body>
</html>

level1

level2

level3

class Markdown {
/** 見出し:Atx形式 */
String headerAtx(String md) {
def sharpSize = md.find(/^#+/).size()
if (sharpSize in 1..6) {
def tags = [ "<h${sharpSize}>",
"</h${sharpSize}>" ]
//def contents = md.replaceAll(/^#+\s*|\s*#+$/, '').trim()
def contents = md.replaceAll(/(?x) # enable whitespace and comments
^\#+ # 先頭からはじまるシャープ
| # または
\#+$ # 最後のシャープ
/, '').trim()
return "${tags.first()}${contents}${tags.last()}"
} else {
return md
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment