我用Obj-c和Swfit實現了一個簡單的markdown解析器,源代碼放在github上了。
Objective-C 版本: https://github.com/marknote/MarkNoteParserObjC
Swift 版本: https://github.com/marknote/MarknoteParser
緣由
我有一個小應用 MarkNote ,這是一個使用markdown語法來記筆記的小工具。
最開始的時候, 我使用 marked 來把 markdown 渲染為HTML。marked使用起來簡單。不過,一個native的應用居然用基于javascript的引擎來做解析,心里總覺得有點不爽 :)
找了找沒找到合適的
基于Swfit/Object-c實現的 markdown解析起 , 我決定自己輪子一個。于是就有了這個項目。
一開始我只是實現了Swfit版本,后來xcode升級到7.0之后,swift的應用文件生成很大,很多時候都大于40m(當然,app store最后會優化,尺寸大大減少)。于是覺得obj-c也很有必要,就又一口氣擼了一個 obj-c版本的。
使用方法
swift 版本
直接拷貝以下2個文件到你的工程中:
-- StringExtensions.swift , String 類擴展;
-- MarkNoteParser.swift, 這是解析器類;在你的代碼中就直接可以調用
MarkNoteParser.toHtml()
把markdown文本轉為HTML 字符, 用法如下:
func markdown(input :String)->String{
let result = MarkNoteParser.toHtml(input)
println("input: \(input) result:\(result)")
return result
}
objective-c 版本
- 把 "MarkNoteParserOC" 目錄下的所有文件拷貝到你的工程中 , 然后在你的代碼中引入頭文件:
#import "MarkNoteParser.h"
-然后你就可以使用 MarkNoteParser 來解析markdown了,示例如下:
NSString* result = [MarkNoteParser toHtml:input];
return result;
特點
標題支持
# H1
## H2
### H3
轉換為:
<h1>H1</h1><h2>H2</h2><h3>H3</h3>
粗體斜體Emphasis支持
Emphasis, aka italics, with *asterisks* or _underscores_.
Strong emphasis, aka bold, with **asterisks** or __underscores__.
Strikethrough uses two tildes. ~~Scratch this.~~
轉換為:
<p>Emphasis, aka italics, with <em>asterisks</em> or <em>underscores</em>.<br/></p>
<p>Strong emphasis, aka bold, with <strong>asterisks</strong> or <strong>underscores</strong>.<br/></p>
<p>Strikethrough uses two tildes. <u>Scratch this.</u><br/></p>
鏈接支持
[I'm an inline-style link](https://www.google.com)
[I'm an inline-style link with title](https://www.google.com "Google's Homepage")
轉換為:
<p><a m an inline-style link</a><br/></p>
<p><a title="Google's Homepage">I'm an inline-style link with title</a><br/></p>
圖片支持

轉換為:
<img src="https://avatars3.githubusercontent.com/u/12975088?v=3&s=40" title="Logo Title" alt="alt text" />
代碼支持
<pre class="lang-markdown">
var s = "JavaScript syntax highlighting";
alert(s);
</pre>
轉換為:
<pre class="lang-javascript">
var s = "JavaScript syntax highlighting";
alert(s);
</pre>
表格支持
| Tables | Are | Cool |
| ------------- |:-------------:| -----:|
| col 3 is | right-aligned | $1600 |
| col 2 is | centered | $12 |
| zebra stripes | are neat | $1 |
轉換為:
<table><tr><th> Tables </th><th> Are </th><th style="text-align: center;"> Cool </th></tr><tr><td> col 3 is </td><td> right-aligned </td><td style="text-align: center;"> $1600 </td></tr><tr><td> col 2 is </td><td> centered </td><td style="text-align: center;"> $12 </td></tr><tr><td> zebra stripes </td><td> are neat </td><td style="text-align: center;"> $1 </td></tr></table><p>The outer pipes (|) are optional, and you don't need to make the raw Markdown line up prettily. You can also use inline Markdown.<br/></p>
問題反饋
如果你有任何問題或者建議,可以在這里給我反饋。謝謝!