markdown.php 82 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934
  1. <?php
  2. #
  3. # Markdown Extra - A text-to-HTML conversion tool for web writers
  4. #
  5. # PHP Markdown & Extra
  6. # Copyright (c) 2004-2012 Michel Fortin
  7. # <http://michelf.com/projects/php-markdown/>
  8. #
  9. # Original Markdown
  10. # Copyright (c) 2004-2006 John Gruber
  11. # <http://daringfireball.net/projects/markdown/>
  12. #
  13. define( 'MARKDOWN_VERSION', "1.0.1o" ); # Sun 8 Jan 2012
  14. define( 'MARKDOWNEXTRA_VERSION', "1.2.5" ); # Sun 8 Jan 2012
  15. #
  16. # Global default settings:
  17. #
  18. # Change to ">" for HTML output
  19. @define( 'MARKDOWN_EMPTY_ELEMENT_SUFFIX', " />");
  20. # Define the width of a tab for code blocks.
  21. @define( 'MARKDOWN_TAB_WIDTH', 4 );
  22. # Optional title attribute for footnote links and backlinks.
  23. @define( 'MARKDOWN_FN_LINK_TITLE', "" );
  24. @define( 'MARKDOWN_FN_BACKLINK_TITLE', "" );
  25. # Optional class attribute for footnote links and backlinks.
  26. @define( 'MARKDOWN_FN_LINK_CLASS', "" );
  27. @define( 'MARKDOWN_FN_BACKLINK_CLASS', "" );
  28. #
  29. # WordPress settings:
  30. #
  31. # Change to false to remove Markdown from posts and/or comments.
  32. @define( 'MARKDOWN_WP_POSTS', true );
  33. @define( 'MARKDOWN_WP_COMMENTS', true );
  34. ### Standard Function Interface ###
  35. @define( 'MARKDOWN_PARSER_CLASS', 'MarkdownExtra_Parser' );
  36. function Markdown($text) {
  37. #
  38. # Initialize the parser and return the result of its transform method.
  39. #
  40. # Setup static parser variable.
  41. static $parser;
  42. if (!isset($parser)) {
  43. $parser_class = MARKDOWN_PARSER_CLASS;
  44. $parser = new $parser_class;
  45. }
  46. # Transform text using parser.
  47. return $parser->transform($text);
  48. }
  49. ### WordPress Plugin Interface ###
  50. /*
  51. Plugin Name: Markdown Extra
  52. Plugin URI: http://michelf.com/projects/php-markdown/
  53. Description: <a href="http://daringfireball.net/projects/markdown/syntax">Markdown syntax</a> allows you to write using an easy-to-read, easy-to-write plain text format. Based on the original Perl version by <a href="http://daringfireball.net/">John Gruber</a>. <a href="http://michelf.com/projects/php-markdown/">More...</a>
  54. Version: 1.2.5
  55. Author: Michel Fortin
  56. Author URI: http://michelf.com/
  57. */
  58. if (isset($wp_version)) {
  59. # More details about how it works here:
  60. # <http://michelf.com/weblog/2005/wordpress-text-flow-vs-markdown/>
  61. # Post content and excerpts
  62. # - Remove WordPress paragraph generator.
  63. # - Run Markdown on excerpt, then remove all tags.
  64. # - Add paragraph tag around the excerpt, but remove it for the excerpt rss.
  65. if (MARKDOWN_WP_POSTS) {
  66. remove_filter('the_content', 'wpautop');
  67. remove_filter('the_content_rss', 'wpautop');
  68. remove_filter('the_excerpt', 'wpautop');
  69. add_filter('the_content', 'mdwp_MarkdownPost', 6);
  70. add_filter('the_content_rss', 'mdwp_MarkdownPost', 6);
  71. add_filter('get_the_excerpt', 'mdwp_MarkdownPost', 6);
  72. add_filter('get_the_excerpt', 'trim', 7);
  73. add_filter('the_excerpt', 'mdwp_add_p');
  74. add_filter('the_excerpt_rss', 'mdwp_strip_p');
  75. remove_filter('content_save_pre', 'balanceTags', 50);
  76. remove_filter('excerpt_save_pre', 'balanceTags', 50);
  77. add_filter('the_content', 'balanceTags', 50);
  78. add_filter('get_the_excerpt', 'balanceTags', 9);
  79. }
  80. # Add a footnote id prefix to posts when inside a loop.
  81. function mdwp_MarkdownPost($text) {
  82. static $parser;
  83. if (!$parser) {
  84. $parser_class = MARKDOWN_PARSER_CLASS;
  85. $parser = new $parser_class;
  86. }
  87. if (is_single() || is_page() || is_feed()) {
  88. $parser->fn_id_prefix = "";
  89. } else {
  90. $parser->fn_id_prefix = get_the_ID() . ".";
  91. }
  92. return $parser->transform($text);
  93. }
  94. # Comments
  95. # - Remove WordPress paragraph generator.
  96. # - Remove WordPress auto-link generator.
  97. # - Scramble important tags before passing them to the kses filter.
  98. # - Run Markdown on excerpt then remove paragraph tags.
  99. if (MARKDOWN_WP_COMMENTS) {
  100. remove_filter('comment_text', 'wpautop', 30);
  101. remove_filter('comment_text', 'make_clickable');
  102. add_filter('pre_comment_content', 'Markdown', 6);
  103. add_filter('pre_comment_content', 'mdwp_hide_tags', 8);
  104. add_filter('pre_comment_content', 'mdwp_show_tags', 12);
  105. add_filter('get_comment_text', 'Markdown', 6);
  106. add_filter('get_comment_excerpt', 'Markdown', 6);
  107. add_filter('get_comment_excerpt', 'mdwp_strip_p', 7);
  108. global $mdwp_hidden_tags, $mdwp_placeholders;
  109. $mdwp_hidden_tags = explode(' ',
  110. '<p> </p> <pre> </pre> <ol> </ol> <ul> </ul> <li> </li>');
  111. $mdwp_placeholders = explode(' ', str_rot13(
  112. 'pEj07ZbbBZ U1kqgh4w4p pre2zmeN6K QTi31t9pre ol0MP1jzJR '.
  113. 'ML5IjmbRol ulANi1NsGY J7zRLJqPul liA8ctl16T K9nhooUHli'));
  114. }
  115. function mdwp_add_p($text) {
  116. if (!preg_match('{^$|^<(p|ul|ol|dl|pre|blockquote)>}i', $text)) {
  117. $text = '<p>'.$text.'</p>';
  118. $text = preg_replace('{\n{2,}}', "</p>\n\n<p>", $text);
  119. }
  120. return $text;
  121. }
  122. function mdwp_strip_p($t) { return preg_replace('{</?p>}i', '', $t); }
  123. function mdwp_hide_tags($text) {
  124. global $mdwp_hidden_tags, $mdwp_placeholders;
  125. return str_replace($mdwp_hidden_tags, $mdwp_placeholders, $text);
  126. }
  127. function mdwp_show_tags($text) {
  128. global $mdwp_hidden_tags, $mdwp_placeholders;
  129. return str_replace($mdwp_placeholders, $mdwp_hidden_tags, $text);
  130. }
  131. }
  132. ### bBlog Plugin Info ###
  133. function identify_modifier_markdown() {
  134. return array(
  135. 'name' => 'markdown',
  136. 'type' => 'modifier',
  137. 'nicename' => 'PHP Markdown Extra',
  138. 'description' => 'A text-to-HTML conversion tool for web writers',
  139. 'authors' => 'Michel Fortin and John Gruber',
  140. 'licence' => 'GPL',
  141. 'version' => MARKDOWNEXTRA_VERSION,
  142. 'help' => '<a href="http://daringfireball.net/projects/markdown/syntax">Markdown syntax</a> allows you to write using an easy-to-read, easy-to-write plain text format. Based on the original Perl version by <a href="http://daringfireball.net/">John Gruber</a>. <a href="http://michelf.com/projects/php-markdown/">More...</a>',
  143. );
  144. }
  145. ### Smarty Modifier Interface ###
  146. function smarty_modifier_markdown($text) {
  147. return Markdown($text);
  148. }
  149. ### Textile Compatibility Mode ###
  150. # Rename this file to "classTextile.php" and it can replace Textile everywhere.
  151. if (strcasecmp(substr(__FILE__, -16), "classTextile.php") == 0) {
  152. # Try to include PHP SmartyPants. Should be in the same directory.
  153. @include_once 'smartypants.php';
  154. # Fake Textile class. It calls Markdown instead.
  155. class Textile {
  156. function TextileThis($text, $lite='', $encode='') {
  157. if ($lite == '' && $encode == '') $text = Markdown($text);
  158. if (function_exists('SmartyPants')) $text = SmartyPants($text);
  159. return $text;
  160. }
  161. # Fake restricted version: restrictions are not supported for now.
  162. function TextileRestricted($text, $lite='', $noimage='') {
  163. return $this->TextileThis($text, $lite);
  164. }
  165. # Workaround to ensure compatibility with TextPattern 4.0.3.
  166. function blockLite($text) { return $text; }
  167. }
  168. }
  169. #
  170. # Markdown Parser Class
  171. #
  172. class Markdown_Parser {
  173. # Regex to match balanced [brackets].
  174. # Needed to insert a maximum bracked depth while converting to PHP.
  175. var $nested_brackets_depth = 6;
  176. var $nested_brackets_re;
  177. var $nested_url_parenthesis_depth = 4;
  178. var $nested_url_parenthesis_re;
  179. # Table of hash values for escaped characters:
  180. var $escape_chars = '\`*_{}[]()>#+-.!';
  181. var $escape_chars_re;
  182. # Change to ">" for HTML output.
  183. var $empty_element_suffix = MARKDOWN_EMPTY_ELEMENT_SUFFIX;
  184. var $tab_width = MARKDOWN_TAB_WIDTH;
  185. # Change to `true` to disallow markup or entities.
  186. var $no_markup = false;
  187. var $no_entities = false;
  188. # Predefined urls and titles for reference links and images.
  189. var $predef_urls = array();
  190. var $predef_titles = array();
  191. function Markdown_Parser() {
  192. #
  193. # Constructor function. Initialize appropriate member variables.
  194. #
  195. $this->_initDetab();
  196. $this->prepareItalicsAndBold();
  197. $this->nested_brackets_re =
  198. str_repeat('(?>[^\[\]]+|\[', $this->nested_brackets_depth).
  199. str_repeat('\])*', $this->nested_brackets_depth);
  200. $this->nested_url_parenthesis_re =
  201. str_repeat('(?>[^()\s]+|\(', $this->nested_url_parenthesis_depth).
  202. str_repeat('(?>\)))*', $this->nested_url_parenthesis_depth);
  203. $this->escape_chars_re = '['.preg_quote($this->escape_chars).']';
  204. # Sort document, block, and span gamut in ascendent priority order.
  205. asort($this->document_gamut);
  206. asort($this->block_gamut);
  207. asort($this->span_gamut);
  208. }
  209. # Internal hashes used during transformation.
  210. var $urls = array();
  211. var $titles = array();
  212. var $html_hashes = array();
  213. # Status flag to avoid invalid nesting.
  214. var $in_anchor = false;
  215. function setup() {
  216. #
  217. # Called before the transformation process starts to setup parser
  218. # states.
  219. #
  220. # Clear global hashes.
  221. $this->urls = $this->predef_urls;
  222. $this->titles = $this->predef_titles;
  223. $this->html_hashes = array();
  224. $in_anchor = false;
  225. }
  226. function teardown() {
  227. #
  228. # Called after the transformation process to clear any variable
  229. # which may be taking up memory unnecessarly.
  230. #
  231. $this->urls = array();
  232. $this->titles = array();
  233. $this->html_hashes = array();
  234. }
  235. function transform($text) {
  236. #
  237. # Main function. Performs some preprocessing on the input text
  238. # and pass it through the document gamut.
  239. #
  240. $this->setup();
  241. # Remove UTF-8 BOM and marker character in input, if present.
  242. $text = preg_replace('{^\xEF\xBB\xBF|\x1A}', '', $text);
  243. # Standardize line endings:
  244. # DOS to Unix and Mac to Unix
  245. $text = preg_replace('{\r\n?}', "\n", $text);
  246. # Make sure $text ends with a couple of newlines:
  247. $text .= "\n\n";
  248. # Convert all tabs to spaces.
  249. $text = $this->detab($text);
  250. # Turn block-level HTML blocks into hash entries
  251. $text = $this->hashHTMLBlocks($text);
  252. # Strip any lines consisting only of spaces and tabs.
  253. # This makes subsequent regexen easier to write, because we can
  254. # match consecutive blank lines with /\n+/ instead of something
  255. # contorted like /[ ]*\n+/ .
  256. $text = preg_replace('/^[ ]+$/m', '', $text);
  257. # Run document gamut methods.
  258. foreach ($this->document_gamut as $method => $priority) {
  259. $text = $this->$method($text);
  260. }
  261. $this->teardown();
  262. return $text . "\n";
  263. }
  264. var $document_gamut = array(
  265. # Strip link definitions, store in hashes.
  266. "stripLinkDefinitions" => 20,
  267. "runBasicBlockGamut" => 30,
  268. );
  269. function stripLinkDefinitions($text) {
  270. #
  271. # Strips link definitions from text, stores the URLs and titles in
  272. # hash references.
  273. #
  274. $less_than_tab = $this->tab_width - 1;
  275. # Link defs are in the form: ^[id]: url "optional title"
  276. $text = preg_replace_callback('{
  277. ^[ ]{0,'.$less_than_tab.'}\[(.+)\][ ]?: # id = $1
  278. [ ]*
  279. \n? # maybe *one* newline
  280. [ ]*
  281. (?:
  282. <(.+?)> # url = $2
  283. |
  284. (\S+?) # url = $3
  285. )
  286. [ ]*
  287. \n? # maybe one newline
  288. [ ]*
  289. (?:
  290. (?<=\s) # lookbehind for whitespace
  291. ["(]
  292. (.*?) # title = $4
  293. [")]
  294. [ ]*
  295. )? # title is optional
  296. (?:\n+|\Z)
  297. }xm',
  298. array(&$this, '_stripLinkDefinitions_callback'),
  299. $text);
  300. return $text;
  301. }
  302. function _stripLinkDefinitions_callback($matches) {
  303. $link_id = strtolower($matches[1]);
  304. $url = $matches[2] == '' ? $matches[3] : $matches[2];
  305. $this->urls[$link_id] = $url;
  306. $this->titles[$link_id] =& $matches[4];
  307. return ''; # String that will replace the block
  308. }
  309. function hashHTMLBlocks($text) {
  310. if ($this->no_markup) return $text;
  311. $less_than_tab = $this->tab_width - 1;
  312. # Hashify HTML blocks:
  313. # We only want to do this for block-level HTML tags, such as headers,
  314. # lists, and tables. That's because we still want to wrap <p>s around
  315. # "paragraphs" that are wrapped in non-block-level tags, such as anchors,
  316. # phrase emphasis, and spans. The list of tags we're looking for is
  317. # hard-coded:
  318. #
  319. # * List "a" is made of tags which can be both inline or block-level.
  320. # These will be treated block-level when the start tag is alone on
  321. # its line, otherwise they're not matched here and will be taken as
  322. # inline later.
  323. # * List "b" is made of tags which are always block-level;
  324. #
  325. $block_tags_a_re = 'ins|del';
  326. $block_tags_b_re = 'p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|address|'.
  327. 'script|noscript|form|fieldset|iframe|math';
  328. # Regular expression for the content of a block tag.
  329. $nested_tags_level = 4;
  330. $attr = '
  331. (?> # optional tag attributes
  332. \s # starts with whitespace
  333. (?>
  334. [^>"/]+ # text outside quotes
  335. |
  336. /+(?!>) # slash not followed by ">"
  337. |
  338. "[^"]*" # text inside double quotes (tolerate ">")
  339. |
  340. \'[^\']*\' # text inside single quotes (tolerate ">")
  341. )*
  342. )?
  343. ';
  344. $content =
  345. str_repeat('
  346. (?>
  347. [^<]+ # content without tag
  348. |
  349. <\2 # nested opening tag
  350. '.$attr.' # attributes
  351. (?>
  352. />
  353. |
  354. >', $nested_tags_level). # end of opening tag
  355. '.*?'. # last level nested tag content
  356. str_repeat('
  357. </\2\s*> # closing nested tag
  358. )
  359. |
  360. <(?!/\2\s*> # other tags with a different name
  361. )
  362. )*',
  363. $nested_tags_level);
  364. $content2 = str_replace('\2', '\3', $content);
  365. # First, look for nested blocks, e.g.:
  366. # <div>
  367. # <div>
  368. # tags for inner block must be indented.
  369. # </div>
  370. # </div>
  371. #
  372. # The outermost tags must start at the left margin for this to match, and
  373. # the inner nested divs must be indented.
  374. # We need to do this before the next, more liberal match, because the next
  375. # match will start at the first `<div>` and stop at the first `</div>`.
  376. $text = preg_replace_callback('{(?>
  377. (?>
  378. (?<=\n\n) # Starting after a blank line
  379. | # or
  380. \A\n? # the beginning of the doc
  381. )
  382. ( # save in $1
  383. # Match from `\n<tag>` to `</tag>\n`, handling nested tags
  384. # in between.
  385. [ ]{0,'.$less_than_tab.'}
  386. <('.$block_tags_b_re.')# start tag = $2
  387. '.$attr.'> # attributes followed by > and \n
  388. '.$content.' # content, support nesting
  389. </\2> # the matching end tag
  390. [ ]* # trailing spaces/tabs
  391. (?=\n+|\Z) # followed by a newline or end of document
  392. | # Special version for tags of group a.
  393. [ ]{0,'.$less_than_tab.'}
  394. <('.$block_tags_a_re.')# start tag = $3
  395. '.$attr.'>[ ]*\n # attributes followed by >
  396. '.$content2.' # content, support nesting
  397. </\3> # the matching end tag
  398. [ ]* # trailing spaces/tabs
  399. (?=\n+|\Z) # followed by a newline or end of document
  400. | # Special case just for <hr />. It was easier to make a special
  401. # case than to make the other regex more complicated.
  402. [ ]{0,'.$less_than_tab.'}
  403. <(hr) # start tag = $2
  404. '.$attr.' # attributes
  405. /?> # the matching end tag
  406. [ ]*
  407. (?=\n{2,}|\Z) # followed by a blank line or end of document
  408. | # Special case for standalone HTML comments:
  409. [ ]{0,'.$less_than_tab.'}
  410. (?s:
  411. <!-- .*? -->
  412. )
  413. [ ]*
  414. (?=\n{2,}|\Z) # followed by a blank line or end of document
  415. | # PHP and ASP-style processor instructions (<? and <%)
  416. [ ]{0,'.$less_than_tab.'}
  417. (?s:
  418. <([?%]) # $2
  419. .*?
  420. \2>
  421. )
  422. [ ]*
  423. (?=\n{2,}|\Z) # followed by a blank line or end of document
  424. )
  425. )}Sxmi',
  426. array(&$this, '_hashHTMLBlocks_callback'),
  427. $text);
  428. return $text;
  429. }
  430. function _hashHTMLBlocks_callback($matches) {
  431. $text = $matches[1];
  432. $key = $this->hashBlock($text);
  433. return "\n\n$key\n\n";
  434. }
  435. function hashPart($text, $boundary = 'X') {
  436. #
  437. # Called whenever a tag must be hashed when a function insert an atomic
  438. # element in the text stream. Passing $text to through this function gives
  439. # a unique text-token which will be reverted back when calling unhash.
  440. #
  441. # The $boundary argument specify what character should be used to surround
  442. # the token. By convension, "B" is used for block elements that needs not
  443. # to be wrapped into paragraph tags at the end, ":" is used for elements
  444. # that are word separators and "X" is used in the general case.
  445. #
  446. # Swap back any tag hash found in $text so we do not have to `unhash`
  447. # multiple times at the end.
  448. $text = $this->unhash($text);
  449. # Then hash the block.
  450. static $i = 0;
  451. $key = "$boundary\x1A" . ++$i . $boundary;
  452. $this->html_hashes[$key] = $text;
  453. return $key; # String that will replace the tag.
  454. }
  455. function hashBlock($text) {
  456. #
  457. # Shortcut function for hashPart with block-level boundaries.
  458. #
  459. return $this->hashPart($text, 'B');
  460. }
  461. var $block_gamut = array(
  462. #
  463. # These are all the transformations that form block-level
  464. # tags like paragraphs, headers, and list items.
  465. #
  466. "doHeaders" => 10,
  467. "doHorizontalRules" => 20,
  468. "doLists" => 40,
  469. "doCodeBlocks" => 50,
  470. "doBlockQuotes" => 60,
  471. );
  472. function runBlockGamut($text) {
  473. #
  474. # Run block gamut tranformations.
  475. #
  476. # We need to escape raw HTML in Markdown source before doing anything
  477. # else. This need to be done for each block, and not only at the
  478. # begining in the Markdown function since hashed blocks can be part of
  479. # list items and could have been indented. Indented blocks would have
  480. # been seen as a code block in a previous pass of hashHTMLBlocks.
  481. $text = $this->hashHTMLBlocks($text);
  482. return $this->runBasicBlockGamut($text);
  483. }
  484. function runBasicBlockGamut($text) {
  485. #
  486. # Run block gamut tranformations, without hashing HTML blocks. This is
  487. # useful when HTML blocks are known to be already hashed, like in the first
  488. # whole-document pass.
  489. #
  490. foreach ($this->block_gamut as $method => $priority) {
  491. $text = $this->$method($text);
  492. }
  493. # Finally form paragraph and restore hashed blocks.
  494. $text = $this->formParagraphs($text);
  495. return $text;
  496. }
  497. function doHorizontalRules($text) {
  498. # Do Horizontal Rules:
  499. return preg_replace(
  500. '{
  501. ^[ ]{0,3} # Leading space
  502. ([-*_]) # $1: First marker
  503. (?> # Repeated marker group
  504. [ ]{0,2} # Zero, one, or two spaces.
  505. \1 # Marker character
  506. ){2,} # Group repeated at least twice
  507. [ ]* # Tailing spaces
  508. $ # End of line.
  509. }mx',
  510. "\n".$this->hashBlock("<hr$this->empty_element_suffix")."\n",
  511. $text);
  512. }
  513. var $span_gamut = array(
  514. #
  515. # These are all the transformations that occur *within* block-level
  516. # tags like paragraphs, headers, and list items.
  517. #
  518. # Process character escapes, code spans, and inline HTML
  519. # in one shot.
  520. "parseSpan" => -30,
  521. # Process anchor and image tags. Images must come first,
  522. # because ![foo][f] looks like an anchor.
  523. "doImages" => 10,
  524. "doAnchors" => 20,
  525. # Make links out of things like `<http://example.com/>`
  526. # Must come after doAnchors, because you can use < and >
  527. # delimiters in inline links like [this](<url>).
  528. "doAutoLinks" => 30,
  529. "encodeAmpsAndAngles" => 40,
  530. "doItalicsAndBold" => 50,
  531. "doHardBreaks" => 60,
  532. );
  533. function runSpanGamut($text) {
  534. #
  535. # Run span gamut tranformations.
  536. #
  537. foreach ($this->span_gamut as $method => $priority) {
  538. $text = $this->$method($text);
  539. }
  540. return $text;
  541. }
  542. function doHardBreaks($text) {
  543. # Do hard breaks:
  544. return preg_replace_callback('/ {2,}\n/',
  545. array(&$this, '_doHardBreaks_callback'), $text);
  546. }
  547. function _doHardBreaks_callback($matches) {
  548. return $this->hashPart("<br$this->empty_element_suffix\n");
  549. }
  550. function doAnchors($text) {
  551. #
  552. # Turn Markdown link shortcuts into XHTML <a> tags.
  553. #
  554. if ($this->in_anchor) return $text;
  555. $this->in_anchor = true;
  556. #
  557. # First, handle reference-style links: [link text] [id]
  558. #
  559. $text = preg_replace_callback('{
  560. ( # wrap whole match in $1
  561. \[
  562. ('.$this->nested_brackets_re.') # link text = $2
  563. \]
  564. [ ]? # one optional space
  565. (?:\n[ ]*)? # one optional newline followed by spaces
  566. \[
  567. (.*?) # id = $3
  568. \]
  569. )
  570. }xs',
  571. array(&$this, '_doAnchors_reference_callback'), $text);
  572. #
  573. # Next, inline-style links: [link text](url "optional title")
  574. #
  575. $text = preg_replace_callback('{
  576. ( # wrap whole match in $1
  577. \[
  578. ('.$this->nested_brackets_re.') # link text = $2
  579. \]
  580. \( # literal paren
  581. [ \n]*
  582. (?:
  583. <(.+?)> # href = $3
  584. |
  585. ('.$this->nested_url_parenthesis_re.') # href = $4
  586. )
  587. [ \n]*
  588. ( # $5
  589. ([\'"]) # quote char = $6
  590. (.*?) # Title = $7
  591. \6 # matching quote
  592. [ \n]* # ignore any spaces/tabs between closing quote and )
  593. )? # title is optional
  594. \)
  595. )
  596. }xs',
  597. array(&$this, '_doAnchors_inline_callback'), $text);
  598. #
  599. # Last, handle reference-style shortcuts: [link text]
  600. # These must come last in case you've also got [link text][1]
  601. # or [link text](/foo)
  602. #
  603. $text = preg_replace_callback('{
  604. ( # wrap whole match in $1
  605. \[
  606. ([^\[\]]+) # link text = $2; can\'t contain [ or ]
  607. \]
  608. )
  609. }xs',
  610. array(&$this, '_doAnchors_reference_callback'), $text);
  611. $this->in_anchor = false;
  612. return $text;
  613. }
  614. function _doAnchors_reference_callback($matches) {
  615. $whole_match = $matches[1];
  616. $link_text = $matches[2];
  617. $link_id =& $matches[3];
  618. if ($link_id == "") {
  619. # for shortcut links like [this][] or [this].
  620. $link_id = $link_text;
  621. }
  622. # lower-case and turn embedded newlines into spaces
  623. $link_id = strtolower($link_id);
  624. $link_id = preg_replace('{[ ]?\n}', ' ', $link_id);
  625. if (isset($this->urls[$link_id])) {
  626. $url = $this->urls[$link_id];
  627. $url = URL::to($url);
  628. $url = $this->encodeAttribute($url);
  629. $result = "<a href=\"$url\"";
  630. if ( isset( $this->titles[$link_id] ) ) {
  631. $title = $this->titles[$link_id];
  632. $title = $this->encodeAttribute($title);
  633. $result .= " title=\"$title\"";
  634. }
  635. $link_text = $this->runSpanGamut($link_text);
  636. $result .= ">$link_text</a>";
  637. $result = $this->hashPart($result);
  638. }
  639. else {
  640. $result = $whole_match;
  641. }
  642. return $result;
  643. }
  644. function _doAnchors_inline_callback($matches) {
  645. $whole_match = $matches[1];
  646. $link_text = $this->runSpanGamut($matches[2]);
  647. $url = $matches[3] == '' ? $matches[4] : $matches[3];
  648. $title =& $matches[7];
  649. $url = URL::to($url);
  650. $url = $this->encodeAttribute($url);
  651. $result = "<a href=\"$url\"";
  652. if (isset($title)) {
  653. $title = $this->encodeAttribute($title);
  654. $result .= " title=\"$title\"";
  655. }
  656. $link_text = $this->runSpanGamut($link_text);
  657. $result .= ">$link_text</a>";
  658. return $this->hashPart($result);
  659. }
  660. function doImages($text) {
  661. #
  662. # Turn Markdown image shortcuts into <img> tags.
  663. #
  664. #
  665. # First, handle reference-style labeled images: ![alt text][id]
  666. #
  667. $text = preg_replace_callback('{
  668. ( # wrap whole match in $1
  669. !\[
  670. ('.$this->nested_brackets_re.') # alt text = $2
  671. \]
  672. [ ]? # one optional space
  673. (?:\n[ ]*)? # one optional newline followed by spaces
  674. \[
  675. (.*?) # id = $3
  676. \]
  677. )
  678. }xs',
  679. array(&$this, '_doImages_reference_callback'), $text);
  680. #
  681. # Next, handle inline images: ![alt text](url "optional title")
  682. # Don't forget: encode * and _
  683. #
  684. $text = preg_replace_callback('{
  685. ( # wrap whole match in $1
  686. !\[
  687. ('.$this->nested_brackets_re.') # alt text = $2
  688. \]
  689. \s? # One optional whitespace character
  690. \( # literal paren
  691. [ \n]*
  692. (?:
  693. <(\S*)> # src url = $3
  694. |
  695. ('.$this->nested_url_parenthesis_re.') # src url = $4
  696. )
  697. [ \n]*
  698. ( # $5
  699. ([\'"]) # quote char = $6
  700. (.*?) # title = $7
  701. \6 # matching quote
  702. [ \n]*
  703. )? # title is optional
  704. \)
  705. )
  706. }xs',
  707. array(&$this, '_doImages_inline_callback'), $text);
  708. return $text;
  709. }
  710. function _doImages_reference_callback($matches) {
  711. $whole_match = $matches[1];
  712. $alt_text = $matches[2];
  713. $link_id = strtolower($matches[3]);
  714. if ($link_id == "") {
  715. $link_id = strtolower($alt_text); # for shortcut links like ![this][].
  716. }
  717. $alt_text = $this->encodeAttribute($alt_text);
  718. if (isset($this->urls[$link_id])) {
  719. $url = $this->encodeAttribute($this->urls[$link_id]);
  720. $result = "<img src=\"$url\" alt=\"$alt_text\"";
  721. if (isset($this->titles[$link_id])) {
  722. $title = $this->titles[$link_id];
  723. $title = $this->encodeAttribute($title);
  724. $result .= " title=\"$title\"";
  725. }
  726. $result .= $this->empty_element_suffix;
  727. $result = $this->hashPart($result);
  728. }
  729. else {
  730. # If there's no such link ID, leave intact:
  731. $result = $whole_match;
  732. }
  733. return $result;
  734. }
  735. function _doImages_inline_callback($matches) {
  736. $whole_match = $matches[1];
  737. $alt_text = $matches[2];
  738. $url = $matches[3] == '' ? $matches[4] : $matches[3];
  739. $title =& $matches[7];
  740. $alt_text = $this->encodeAttribute($alt_text);
  741. $url = $this->encodeAttribute($url);
  742. $result = "<img src=\"$url\" alt=\"$alt_text\"";
  743. if (isset($title)) {
  744. $title = $this->encodeAttribute($title);
  745. $result .= " title=\"$title\""; # $title already quoted
  746. }
  747. $result .= $this->empty_element_suffix;
  748. return $this->hashPart($result);
  749. }
  750. function doHeaders($text) {
  751. # Setext-style headers:
  752. # Header 1
  753. # ========
  754. #
  755. # Header 2
  756. # --------
  757. #
  758. $text = preg_replace_callback('{ ^(.+?)[ ]*\n(=+|-+)[ ]*\n+ }mx',
  759. array(&$this, '_doHeaders_callback_setext'), $text);
  760. # atx-style headers:
  761. # # Header 1
  762. # ## Header 2
  763. # ## Header 2 with closing hashes ##
  764. # ...
  765. # ###### Header 6
  766. #
  767. $text = preg_replace_callback('{
  768. ^(\#{1,6}) # $1 = string of #\'s
  769. [ ]*
  770. (.+?) # $2 = Header text
  771. [ ]*
  772. \#* # optional closing #\'s (not counted)
  773. \n+
  774. }xm',
  775. array(&$this, '_doHeaders_callback_atx'), $text);
  776. return $text;
  777. }
  778. function _doHeaders_callback_setext($matches) {
  779. # Terrible hack to check we haven't found an empty list item.
  780. if ($matches[2] == '-' && preg_match('{^-(?: |$)}', $matches[1]))
  781. return $matches[0];
  782. $level = $matches[2]{0} == '=' ? 1 : 2;
  783. $block = "<h$level>".$this->runSpanGamut($matches[1])."</h$level>";
  784. return "\n" . $this->hashBlock($block) . "\n\n";
  785. }
  786. function _doHeaders_callback_atx($matches) {
  787. $level = strlen($matches[1]);
  788. $block = "<h$level>".$this->runSpanGamut($matches[2])."</h$level>";
  789. return "\n" . $this->hashBlock($block) . "\n\n";
  790. }
  791. function doLists($text) {
  792. #
  793. # Form HTML ordered (numbered) and unordered (bulleted) lists.
  794. #
  795. $less_than_tab = $this->tab_width - 1;
  796. # Re-usable patterns to match list item bullets and number markers:
  797. $marker_ul_re = '[*+-]';
  798. $marker_ol_re = '\d+[\.]';
  799. $marker_any_re = "(?:$marker_ul_re|$marker_ol_re)";
  800. $markers_relist = array(
  801. $marker_ul_re => $marker_ol_re,
  802. $marker_ol_re => $marker_ul_re,
  803. );
  804. foreach ($markers_relist as $marker_re => $other_marker_re) {
  805. # Re-usable pattern to match any entirel ul or ol list:
  806. $whole_list_re = '
  807. ( # $1 = whole list
  808. ( # $2
  809. ([ ]{0,'.$less_than_tab.'}) # $3 = number of spaces
  810. ('.$marker_re.') # $4 = first list item marker
  811. [ ]+
  812. )
  813. (?s:.+?)
  814. ( # $5
  815. \z
  816. |
  817. \n{2,}
  818. (?=\S)
  819. (?! # Negative lookahead for another list item marker
  820. [ ]*
  821. '.$marker_re.'[ ]+
  822. )
  823. |
  824. (?= # Lookahead for another kind of list
  825. \n
  826. \3 # Must have the same indentation
  827. '.$other_marker_re.'[ ]+
  828. )
  829. )
  830. )
  831. '; // mx
  832. # We use a different prefix before nested lists than top-level lists.
  833. # See extended comment in _ProcessListItems().
  834. if ($this->list_level) {
  835. $text = preg_replace_callback('{
  836. ^
  837. '.$whole_list_re.'
  838. }mx',
  839. array(&$this, '_doLists_callback'), $text);
  840. }
  841. else {
  842. $text = preg_replace_callback('{
  843. (?:(?<=\n)\n|\A\n?) # Must eat the newline
  844. '.$whole_list_re.'
  845. }mx',
  846. array(&$this, '_doLists_callback'), $text);
  847. }
  848. }
  849. return $text;
  850. }
  851. function _doLists_callback($matches) {
  852. # Re-usable patterns to match list item bullets and number markers:
  853. $marker_ul_re = '[*+-]';
  854. $marker_ol_re = '\d+[\.]';
  855. $marker_any_re = "(?:$marker_ul_re|$marker_ol_re)";
  856. $list = $matches[1];
  857. $list_type = preg_match("/$marker_ul_re/", $matches[4]) ? "ul" : "ol";
  858. $marker_any_re = ( $list_type == "ul" ? $marker_ul_re : $marker_ol_re );
  859. $list .= "\n";
  860. $result = $this->processListItems($list, $marker_any_re);
  861. $result = $this->hashBlock("<$list_type>\n" . $result . "</$list_type>");
  862. return "\n". $result ."\n\n";
  863. }
  864. var $list_level = 0;
  865. function processListItems($list_str, $marker_any_re) {
  866. #
  867. # Process the contents of a single ordered or unordered list, splitting it
  868. # into individual list items.
  869. #
  870. # The $this->list_level global keeps track of when we're inside a list.
  871. # Each time we enter a list, we increment it; when we leave a list,
  872. # we decrement. If it's zero, we're not in a list anymore.
  873. #
  874. # We do this because when we're not inside a list, we want to treat
  875. # something like this:
  876. #
  877. # I recommend upgrading to version
  878. # 8. Oops, now this line is treated
  879. # as a sub-list.
  880. #
  881. # As a single paragraph, despite the fact that the second line starts
  882. # with a digit-period-space sequence.
  883. #
  884. # Whereas when we're inside a list (or sub-list), that line will be
  885. # treated as the start of a sub-list. What a kludge, huh? This is
  886. # an aspect of Markdown's syntax that's hard to parse perfectly
  887. # without resorting to mind-reading. Perhaps the solution is to
  888. # change the syntax rules such that sub-lists must start with a
  889. # starting cardinal number; e.g. "1." or "a.".
  890. $this->list_level++;
  891. # trim trailing blank lines:
  892. $list_str = preg_replace("/\n{2,}\\z/", "\n", $list_str);
  893. $list_str = preg_replace_callback('{
  894. (\n)? # leading line = $1
  895. (^[ ]*) # leading whitespace = $2
  896. ('.$marker_any_re.' # list marker and space = $3
  897. (?:[ ]+|(?=\n)) # space only required if item is not empty
  898. )
  899. ((?s:.*?)) # list item text = $4
  900. (?:(\n+(?=\n))|\n) # tailing blank line = $5
  901. (?= \n* (\z | \2 ('.$marker_any_re.') (?:[ ]+|(?=\n))))
  902. }xm',
  903. array(&$this, '_processListItems_callback'), $list_str);
  904. $this->list_level--;
  905. return $list_str;
  906. }
  907. function _processListItems_callback($matches) {
  908. $item = $matches[4];
  909. $leading_line =& $matches[1];
  910. $leading_space =& $matches[2];
  911. $marker_space = $matches[3];
  912. $tailing_blank_line =& $matches[5];
  913. if ($leading_line || $tailing_blank_line ||
  914. preg_match('/\n{2,}/', $item))
  915. {
  916. # Replace marker with the appropriate whitespace indentation
  917. $item = $leading_space . str_repeat(' ', strlen($marker_space)) . $item;
  918. $item = $this->runBlockGamut($this->outdent($item)."\n");
  919. }
  920. else {
  921. # Recursion for sub-lists:
  922. $item = $this->doLists($this->outdent($item));
  923. $item = preg_replace('/\n+$/', '', $item);
  924. $item = $this->runSpanGamut($item);
  925. }
  926. return "<li>" . $item . "</li>\n";
  927. }
  928. function doCodeBlocks($text) {
  929. #
  930. # Process Markdown `<pre><code>` blocks.
  931. #
  932. $text = preg_replace_callback('{
  933. (?:\n\n|\A\n?)
  934. ( # $1 = the code block -- one or more lines, starting with a space/tab
  935. (?>
  936. [ ]{'.$this->tab_width.'} # Lines must start with a tab or a tab-width of spaces
  937. .*\n+
  938. )+
  939. )
  940. ((?=^[ ]{0,'.$this->tab_width.'}\S)|\Z) # Lookahead for non-space at line-start, or end of doc
  941. }xm',
  942. array(&$this, '_doCodeBlocks_callback'), $text);
  943. return $text;
  944. }
  945. function _doCodeBlocks_callback($matches) {
  946. $codeblock = $matches[1];
  947. $codeblock = $this->outdent($codeblock);
  948. $codeblock = htmlspecialchars($codeblock, ENT_NOQUOTES);
  949. # trim leading newlines and trailing newlines
  950. $codeblock = preg_replace('/\A\n+|\n+\z/', '', $codeblock);
  951. $codeblock = "<pre class=\"prettyprint linenums\">$codeblock\n</pre>";
  952. return "\n\n".$this->hashBlock($codeblock)."\n\n";
  953. }
  954. function makeCodeSpan($code) {
  955. #
  956. # Create a code span markup for $code. Called from handleSpanToken.
  957. #
  958. $code = htmlspecialchars(trim($code), ENT_NOQUOTES);
  959. return $this->hashPart("<code>$code</code>");
  960. }
  961. var $em_relist = array(
  962. '' => '(?:(?<!\*)\*(?!\*)|(?<!_)_(?!_))(?=\S|$)(?![\.,:;]\s)',
  963. '*' => '(?<=\S|^)(?<!\*)\*(?!\*)',
  964. '_' => '(?<=\S|^)(?<!_)_(?!_)',
  965. );
  966. var $strong_relist = array(
  967. '' => '(?:(?<!\*)\*\*(?!\*)|(?<!_)__(?!_))(?=\S|$)(?![\.,:;]\s)',
  968. '**' => '(?<=\S|^)(?<!\*)\*\*(?!\*)',
  969. '__' => '(?<=\S|^)(?<!_)__(?!_)',
  970. );
  971. var $em_strong_relist = array(
  972. '' => '(?:(?<!\*)\*\*\*(?!\*)|(?<!_)___(?!_))(?=\S|$)(?![\.,:;]\s)',
  973. '***' => '(?<=\S|^)(?<!\*)\*\*\*(?!\*)',
  974. '___' => '(?<=\S|^)(?<!_)___(?!_)',
  975. );
  976. var $em_strong_prepared_relist;
  977. function prepareItalicsAndBold() {
  978. #
  979. # Prepare regular expressions for searching emphasis tokens in any
  980. # context.
  981. #
  982. foreach ($this->em_relist as $em => $em_re) {
  983. foreach ($this->strong_relist as $strong => $strong_re) {
  984. # Construct list of allowed token expressions.
  985. $token_relist = array();
  986. if (isset($this->em_strong_relist["$em$strong"])) {
  987. $token_relist[] = $this->em_strong_relist["$em$strong"];
  988. }
  989. $token_relist[] = $em_re;
  990. $token_relist[] = $strong_re;
  991. # Construct master expression from list.
  992. $token_re = '{('. implode('|', $token_relist) .')}';
  993. $this->em_strong_prepared_relist["$em$strong"] = $token_re;
  994. }
  995. }
  996. }
  997. function doItalicsAndBold($text) {
  998. $token_stack = array('');
  999. $text_stack = array('');
  1000. $em = '';
  1001. $strong = '';
  1002. $tree_char_em = false;
  1003. while (1) {
  1004. #
  1005. # Get prepared regular expression for seraching emphasis tokens
  1006. # in current context.
  1007. #
  1008. $token_re = $this->em_strong_prepared_relist["$em$strong"];
  1009. #
  1010. # Each loop iteration search for the next emphasis token.
  1011. # Each token is then passed to handleSpanToken.
  1012. #
  1013. $parts = preg_split($token_re, $text, 2, PREG_SPLIT_DELIM_CAPTURE);
  1014. $text_stack[0] .= $parts[0];
  1015. $token =& $parts[1];
  1016. $text =& $parts[2];
  1017. if (empty($token)) {
  1018. # Reached end of text span: empty stack without emitting.
  1019. # any more emphasis.
  1020. while ($token_stack[0]) {
  1021. $text_stack[1] .= array_shift($token_stack);
  1022. $text_stack[0] .= array_shift($text_stack);
  1023. }
  1024. break;
  1025. }
  1026. $token_len = strlen($token);
  1027. if ($tree_char_em) {
  1028. # Reached closing marker while inside a three-char emphasis.
  1029. if ($token_len == 3) {
  1030. # Three-char closing marker, close em and strong.
  1031. array_shift($token_stack);
  1032. $span = array_shift($text_stack);
  1033. $span = $this->runSpanGamut($span);
  1034. $span = "<strong><em>$span</em></strong>";
  1035. $text_stack[0] .= $this->hashPart($span);
  1036. $em = '';
  1037. $strong = '';
  1038. } else {
  1039. # Other closing marker: close one em or strong and
  1040. # change current token state to match the other
  1041. $token_stack[0] = str_repeat($token{0}, 3-$token_len);
  1042. $tag = $token_len == 2 ? "strong" : "em";
  1043. $span = $text_stack[0];
  1044. $span = $this->runSpanGamut($span);
  1045. $span = "<$tag>$span</$tag>";
  1046. $text_stack[0] = $this->hashPart($span);
  1047. $$tag = ''; # $$tag stands for $em or $strong
  1048. }
  1049. $tree_char_em = false;
  1050. } else if ($token_len == 3) {
  1051. if ($em) {
  1052. # Reached closing marker for both em and strong.
  1053. # Closing strong marker:
  1054. for ($i = 0; $i < 2; ++$i) {
  1055. $shifted_token = array_shift($token_stack);
  1056. $tag = strlen($shifted_token) == 2 ? "strong" : "em";
  1057. $span = array_shift($text_stack);
  1058. $span = $this->runSpanGamut($span);
  1059. $span = "<$tag>$span</$tag>";
  1060. $text_stack[0] .= $this->hashPart($span);
  1061. $$tag = ''; # $$tag stands for $em or $strong
  1062. }
  1063. } else {
  1064. # Reached opening three-char emphasis marker. Push on token
  1065. # stack; will be handled by the special condition above.
  1066. $em = $token{0};
  1067. $strong = "$em$em";
  1068. array_unshift($token_stack, $token);
  1069. array_unshift($text_stack, '');
  1070. $tree_char_em = true;
  1071. }
  1072. } else if ($token_len == 2) {
  1073. if ($strong) {
  1074. # Unwind any dangling emphasis marker:
  1075. if (strlen($token_stack[0]) == 1) {
  1076. $text_stack[1] .= array_shift($token_stack);
  1077. $text_stack[0] .= array_shift($text_stack);
  1078. }
  1079. # Closing strong marker:
  1080. array_shift($token_stack);
  1081. $span = array_shift($text_stack);
  1082. $span = $this->runSpanGamut($span);
  1083. $span = "<strong>$span</strong>";
  1084. $text_stack[0] .= $this->hashPart($span);
  1085. $strong = '';
  1086. } else {
  1087. array_unshift($token_stack, $token);
  1088. array_unshift($text_stack, '');
  1089. $strong = $token;
  1090. }
  1091. } else {
  1092. # Here $token_len == 1
  1093. if ($em) {
  1094. if (strlen($token_stack[0]) == 1) {
  1095. # Closing emphasis marker:
  1096. array_shift($token_stack);
  1097. $span = array_shift($text_stack);
  1098. $span = $this->runSpanGamut($span);
  1099. $span = "<em>$span</em>";
  1100. $text_stack[0] .= $this->hashPart($span);
  1101. $em = '';
  1102. } else {
  1103. $text_stack[0] .= $token;
  1104. }
  1105. } else {
  1106. array_unshift($token_stack, $token);
  1107. array_unshift($text_stack, '');
  1108. $em = $token;
  1109. }
  1110. }
  1111. }
  1112. return $text_stack[0];
  1113. }
  1114. function doBlockQuotes($text) {
  1115. $text = preg_replace_callback('/
  1116. ( # Wrap whole match in $1
  1117. (?>
  1118. ^[ ]*>[ ]? # ">" at the start of a line
  1119. .+\n # rest of the first line
  1120. (.+\n)* # subsequent consecutive lines
  1121. \n* # blanks
  1122. )+
  1123. )
  1124. /xm',
  1125. array(&$this, '_doBlockQuotes_callback'), $text);
  1126. return $text;
  1127. }
  1128. function _doBlockQuotes_callback($matches) {
  1129. $bq = $matches[1];
  1130. # trim one level of quoting - trim whitespace-only lines
  1131. $bq = preg_replace('/^[ ]*>[ ]?|^[ ]+$/m', '', $bq);
  1132. $bq = $this->runBlockGamut($bq); # recurse
  1133. $bq = preg_replace('/^/m', " ", $bq);
  1134. # These leading spaces cause problem with <pre> content,
  1135. # so we need to fix that:
  1136. $bq = preg_replace_callback('{(\s*<pre>.+?</pre>)}sx',
  1137. array(&$this, '_doBlockQuotes_callback2'), $bq);
  1138. return "\n". $this->hashBlock("<blockquote>\n$bq\n</blockquote>")."\n\n";
  1139. }
  1140. function _doBlockQuotes_callback2($matches) {
  1141. $pre = $matches[1];
  1142. $pre = preg_replace('/^ /m', '', $pre);
  1143. return $pre;
  1144. }
  1145. function formParagraphs($text) {
  1146. #
  1147. # Params:
  1148. # $text - string to process with html <p> tags
  1149. #
  1150. # Strip leading and trailing lines:
  1151. $text = preg_replace('/\A\n+|\n+\z/', '', $text);
  1152. $grafs = preg_split('/\n{2,}/', $text, -1, PREG_SPLIT_NO_EMPTY);
  1153. #
  1154. # Wrap <p> tags and unhashify HTML blocks
  1155. #
  1156. foreach ($grafs as $key => $value) {
  1157. if (!preg_match('/^B\x1A[0-9]+B$/', $value)) {
  1158. # Is a paragraph.
  1159. $value = $this->runSpanGamut($value);
  1160. $value = preg_replace('/^([ ]*)/', "<p>", $value);
  1161. $value .= "</p>";
  1162. $grafs[$key] = $this->unhash($value);
  1163. }
  1164. else {
  1165. # Is a block.
  1166. # Modify elements of @grafs in-place...
  1167. $graf = $value;
  1168. $block = $this->html_hashes[$graf];
  1169. $graf = $block;
  1170. // if (preg_match('{
  1171. // \A
  1172. // ( # $1 = <div> tag
  1173. // <div \s+
  1174. // [^>]*
  1175. // \b
  1176. // markdown\s*=\s* ([\'"]) # $2 = attr quote char
  1177. // 1
  1178. // \2
  1179. // [^>]*
  1180. // >
  1181. // )
  1182. // ( # $3 = contents
  1183. // .*
  1184. // )
  1185. // (</div>) # $4 = closing tag
  1186. // \z
  1187. // }xs', $block, $matches))
  1188. // {
  1189. // list(, $div_open, , $div_content, $div_close) = $matches;
  1190. //
  1191. // # We can't call Markdown(), because that resets the hash;
  1192. // # that initialization code should be pulled into its own sub, though.
  1193. // $div_content = $this->hashHTMLBlocks($div_content);
  1194. //
  1195. // # Run document gamut methods on the content.
  1196. // foreach ($this->document_gamut as $method => $priority) {
  1197. // $div_content = $this->$method($div_content);
  1198. // }
  1199. //
  1200. // $div_open = preg_replace(
  1201. // '{\smarkdown\s*=\s*([\'"]).+?\1}', '', $div_open);
  1202. //
  1203. // $graf = $div_open . "\n" . $div_content . "\n" . $div_close;
  1204. // }
  1205. $grafs[$key] = $graf;
  1206. }
  1207. }
  1208. return implode("\n\n", $grafs);
  1209. }
  1210. function encodeAttribute($text) {
  1211. #
  1212. # Encode text for a double-quoted HTML attribute. This function
  1213. # is *not* suitable for attributes enclosed in single quotes.
  1214. #
  1215. $text = $this->encodeAmpsAndAngles($text);
  1216. $text = str_replace('"', '&quot;', $text);
  1217. return $text;
  1218. }
  1219. function encodeAmpsAndAngles($text) {
  1220. #
  1221. # Smart processing for ampersands and angle brackets that need to
  1222. # be encoded. Valid character entities are left alone unless the
  1223. # no-entities mode is set.
  1224. #
  1225. if ($this->no_entities) {
  1226. $text = str_replace('&', '&amp;', $text);
  1227. } else {
  1228. # Ampersand-encoding based entirely on Nat Irons's Amputator
  1229. # MT plugin: <http://bumppo.net/projects/amputator/>
  1230. $text = preg_replace('/&(?!#?[xX]?(?:[0-9a-fA-F]+|\w+);)/',
  1231. '&amp;', $text);;
  1232. }
  1233. # Encode remaining <'s
  1234. $text = str_replace('<', '&lt;', $text);
  1235. return $text;
  1236. }
  1237. function doAutoLinks($text) {
  1238. $text = preg_replace_callback('{<((https?|ftp|dict):[^\'">\s]+)>}i',
  1239. array(&$this, '_doAutoLinks_url_callback'), $text);
  1240. # Email addresses: <address@domain.foo>
  1241. $text = preg_replace_callback('{
  1242. <
  1243. (?:mailto:)?
  1244. (
  1245. (?:
  1246. [-!#$%&\'*+/=?^_`.{|}~\w\x80-\xFF]+
  1247. |
  1248. ".*?"
  1249. )
  1250. \@
  1251. (?:
  1252. [-a-z0-9\x80-\xFF]+(\.[-a-z0-9\x80-\xFF]+)*\.[a-z]+
  1253. |
  1254. \[[\d.a-fA-F:]+\] # IPv4 & IPv6
  1255. )
  1256. )
  1257. >
  1258. }xi',
  1259. array(&$this, '_doAutoLinks_email_callback'), $text);
  1260. return $text;
  1261. }
  1262. function _doAutoLinks_url_callback($matches) {
  1263. $url = $this->encodeAttribute($matches[1]);
  1264. $link = "<a href=\"$url\">$url</a>";
  1265. return $this->hashPart($link);
  1266. }
  1267. function _doAutoLinks_email_callback($matches) {
  1268. $address = $matches[1];
  1269. $link = $this->encodeEmailAddress($address);
  1270. return $this->hashPart($link);
  1271. }
  1272. function encodeEmailAddress($addr) {
  1273. #
  1274. # Input: an email address, e.g. "foo@example.com"
  1275. #
  1276. # Output: the email address as a mailto link, with each character
  1277. # of the address encoded as either a decimal or hex entity, in
  1278. # the hopes of foiling most address harvesting spam bots. E.g.:
  1279. #
  1280. # <p><a href="&#109;&#x61;&#105;&#x6c;&#116;&#x6f;&#58;&#x66;o&#111;
  1281. # &#x40;&#101;&#x78;&#97;&#x6d;&#112;&#x6c;&#101;&#46;&#x63;&#111;
  1282. # &#x6d;">&#x66;o&#111;&#x40;&#101;&#x78;&#97;&#x6d;&#112;&#x6c;
  1283. # &#101;&#46;&#x63;&#111;&#x6d;</a></p>
  1284. #
  1285. # Based by a filter by Matthew Wickline, posted to BBEdit-Talk.
  1286. # With some optimizations by Milian Wolff.
  1287. #
  1288. $addr = "mailto:" . $addr;
  1289. $chars = preg_split('/(?<!^)(?!$)/', $addr);
  1290. $seed = (int)abs(crc32($addr) / strlen($addr)); # Deterministic seed.
  1291. foreach ($chars as $key => $char) {
  1292. $ord = ord($char);
  1293. # Ignore non-ascii chars.
  1294. if ($ord < 128) {
  1295. $r = ($seed * (1 + $key)) % 100; # Pseudo-random function.
  1296. # roughly 10% raw, 45% hex, 45% dec
  1297. # '@' *must* be encoded. I insist.
  1298. if ($r > 90 && $char != '@') /* do nothing */;
  1299. else if ($r < 45) $chars[$key] = '&#x'.dechex($ord).';';
  1300. else $chars[$key] = '&#'.$ord.';';
  1301. }
  1302. }
  1303. $addr = implode('', $chars);
  1304. $text = implode('', array_slice($chars, 7)); # text without `mailto:`
  1305. $addr = "<a href=\"$addr\">$text</a>";
  1306. return $addr;
  1307. }
  1308. function parseSpan($str) {
  1309. #
  1310. # Take the string $str and parse it into tokens, hashing embeded HTML,
  1311. # escaped characters and handling code spans.
  1312. #
  1313. $output = '';
  1314. $span_re = '{
  1315. (
  1316. \\\\'.$this->escape_chars_re.'
  1317. |
  1318. (?<![`\\\\])
  1319. `+ # code span marker
  1320. '.( $this->no_markup ? '' : '
  1321. |
  1322. <!-- .*? --> # comment
  1323. |
  1324. <\?.*?\?> | <%.*?%> # processing instruction
  1325. |
  1326. <[/!$]?[-a-zA-Z0-9:_]+ # regular tags
  1327. (?>
  1328. \s
  1329. (?>[^"\'>]+|"[^"]*"|\'[^\']*\')*
  1330. )?
  1331. >
  1332. ').'
  1333. )
  1334. }xs';
  1335. while (1) {
  1336. #
  1337. # Each loop iteration seach for either the next tag, the next
  1338. # openning code span marker, or the next escaped character.
  1339. # Each token is then passed to handleSpanToken.
  1340. #
  1341. $parts = preg_split($span_re, $str, 2, PREG_SPLIT_DELIM_CAPTURE);
  1342. # Create token from text preceding tag.
  1343. if ($parts[0] != "") {
  1344. $output .= $parts[0];
  1345. }
  1346. # Check if we reach the end.
  1347. if (isset($parts[1])) {
  1348. $output .= $this->handleSpanToken($parts[1], $parts[2]);
  1349. $str = $parts[2];
  1350. }
  1351. else {
  1352. break;
  1353. }
  1354. }
  1355. return $output;
  1356. }
  1357. function handleSpanToken($token, &$str) {
  1358. #
  1359. # Handle $token provided by parseSpan by determining its nature and
  1360. # returning the corresponding value that should replace it.
  1361. #
  1362. switch ($token{0}) {
  1363. case "\\":
  1364. return $this->hashPart("&#". ord($token{1}). ";");
  1365. case "`":
  1366. # Search for end marker in remaining text.
  1367. if (preg_match('/^(.*?[^`])'.preg_quote($token).'(?!`)(.*)$/sm',
  1368. $str, $matches))
  1369. {
  1370. $str = $matches[2];
  1371. $codespan = $this->makeCodeSpan($matches[1]);
  1372. return $this->hashPart($codespan);
  1373. }
  1374. return $token; // return as text since no ending marker found.
  1375. default:
  1376. return $this->hashPart($token);
  1377. }
  1378. }
  1379. function outdent($text) {
  1380. #
  1381. # Remove one level of line-leading tabs or spaces
  1382. #
  1383. return preg_replace('/^(\t|[ ]{1,'.$this->tab_width.'})/m', '', $text);
  1384. }
  1385. # String length function for detab. `_initDetab` will create a function to
  1386. # hanlde UTF-8 if the default function does not exist.
  1387. var $utf8_strlen = 'mb_strlen';
  1388. function detab($text) {
  1389. #
  1390. # Replace tabs with the appropriate amount of space.
  1391. #
  1392. # For each line we separate the line in blocks delemited by
  1393. # tab characters. Then we reconstruct every line by adding the
  1394. # appropriate number of space between each blocks.
  1395. $text = preg_replace_callback('/^.*\t.*$/m',
  1396. array(&$this, '_detab_callback'), $text);
  1397. return $text;
  1398. }
  1399. function _detab_callback($matches) {
  1400. $line = $matches[0];
  1401. $strlen = $this->utf8_strlen; # strlen function for UTF-8.
  1402. # Split in blocks.
  1403. $blocks = explode("\t", $line);
  1404. # Add each blocks to the line.
  1405. $line = $blocks[0];
  1406. unset($blocks[0]); # Do not add first block twice.
  1407. foreach ($blocks as $block) {
  1408. # Calculate amount of space, insert spaces, insert block.
  1409. $amount = $this->tab_width -
  1410. $strlen($line, 'UTF-8') % $this->tab_width;
  1411. $line .= str_repeat(" ", $amount) . $block;
  1412. }
  1413. return $line;
  1414. }
  1415. function _initDetab() {
  1416. #
  1417. # Check for the availability of the function in the `utf8_strlen` property
  1418. # (initially `mb_strlen`). If the function is not available, create a
  1419. # function that will loosely count the number of UTF-8 characters with a
  1420. # regular expression.
  1421. #
  1422. if (function_exists($this->utf8_strlen)) return;
  1423. $this->utf8_strlen = create_function('$text', 'return preg_match_all(
  1424. "/[\\\\x00-\\\\xBF]|[\\\\xC0-\\\\xFF][\\\\x80-\\\\xBF]*/",
  1425. $text, $m);');
  1426. }
  1427. function unhash($text) {
  1428. #
  1429. # Swap back in all the tags hashed by _HashHTMLBlocks.
  1430. #
  1431. return preg_replace_callback('/(.)\x1A[0-9]+\1/',
  1432. array(&$this, '_unhash_callback'), $text);
  1433. }
  1434. function _unhash_callback($matches) {
  1435. return $this->html_hashes[$matches[0]];
  1436. }
  1437. }
  1438. #
  1439. # Markdown Extra Parser Class
  1440. #
  1441. class MarkdownExtra_Parser extends Markdown_Parser {
  1442. # Prefix for footnote ids.
  1443. var $fn_id_prefix = "";
  1444. # Optional title attribute for footnote links and backlinks.
  1445. var $fn_link_title = MARKDOWN_FN_LINK_TITLE;
  1446. var $fn_backlink_title = MARKDOWN_FN_BACKLINK_TITLE;
  1447. # Optional class attribute for footnote links and backlinks.
  1448. var $fn_link_class = MARKDOWN_FN_LINK_CLASS;
  1449. var $fn_backlink_class = MARKDOWN_FN_BACKLINK_CLASS;
  1450. # Predefined abbreviations.
  1451. var $predef_abbr = array();
  1452. function MarkdownExtra_Parser() {
  1453. #
  1454. # Constructor function. Initialize the parser object.
  1455. #
  1456. # Add extra escapable characters before parent constructor
  1457. # initialize the table.
  1458. $this->escape_chars .= ':|';
  1459. # Insert extra document, block, and span transformations.
  1460. # Parent constructor will do the sorting.
  1461. $this->document_gamut += array(
  1462. "doFencedCodeBlocks" => 5,
  1463. "stripFootnotes" => 15,
  1464. "stripAbbreviations" => 25,
  1465. "appendFootnotes" => 50,
  1466. );
  1467. $this->block_gamut += array(
  1468. "doFencedCodeBlocks" => 5,
  1469. "doTables" => 15,
  1470. "doDefLists" => 45,
  1471. );
  1472. $this->span_gamut += array(
  1473. "doFootnotes" => 5,
  1474. "doAbbreviations" => 70,
  1475. );
  1476. parent::Markdown_Parser();
  1477. }
  1478. # Extra variables used during extra transformations.
  1479. var $footnotes = array();
  1480. var $footnotes_ordered = array();
  1481. var $abbr_desciptions = array();
  1482. var $abbr_word_re = '';
  1483. # Give the current footnote number.
  1484. var $footnote_counter = 1;
  1485. function setup() {
  1486. #
  1487. # Setting up Extra-specific variables.
  1488. #
  1489. parent::setup();
  1490. $this->footnotes = array();
  1491. $this->footnotes_ordered = array();
  1492. $this->abbr_desciptions = array();
  1493. $this->abbr_word_re = '';
  1494. $this->footnote_counter = 1;
  1495. foreach ($this->predef_abbr as $abbr_word => $abbr_desc) {
  1496. if ($this->abbr_word_re)
  1497. $this->abbr_word_re .= '|';
  1498. $this->abbr_word_re .= preg_quote($abbr_word);
  1499. $this->abbr_desciptions[$abbr_word] = trim($abbr_desc);
  1500. }
  1501. }
  1502. function teardown() {
  1503. #
  1504. # Clearing Extra-specific variables.
  1505. #
  1506. $this->footnotes = array();
  1507. $this->footnotes_ordered = array();
  1508. $this->abbr_desciptions = array();
  1509. $this->abbr_word_re = '';
  1510. parent::teardown();
  1511. }
  1512. ### HTML Block Parser ###
  1513. # Tags that are always treated as block tags:
  1514. var $block_tags_re = 'p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|address|form|fieldset|iframe|hr|legend';
  1515. # Tags treated as block tags only if the opening tag is alone on it's line:
  1516. var $context_block_tags_re = 'script|noscript|math|ins|del';
  1517. # Tags where markdown="1" default to span mode:
  1518. var $contain_span_tags_re = 'p|h[1-6]|li|dd|dt|td|th|legend|address';
  1519. # Tags which must not have their contents modified, no matter where
  1520. # they appear:
  1521. var $clean_tags_re = 'script|math';
  1522. # Tags that do not need to be closed.
  1523. var $auto_close_tags_re = 'hr|img';
  1524. function hashHTMLBlocks($text) {
  1525. #
  1526. # Hashify HTML Blocks and "clean tags".
  1527. #
  1528. # We only want to do this for block-level HTML tags, such as headers,
  1529. # lists, and tables. That's because we still want to wrap <p>s around
  1530. # "paragraphs" that are wrapped in non-block-level tags, such as anchors,
  1531. # phrase emphasis, and spans. The list of tags we're looking for is
  1532. # hard-coded.
  1533. #
  1534. # This works by calling _HashHTMLBlocks_InMarkdown, which then calls
  1535. # _HashHTMLBlocks_InHTML when it encounter block tags. When the markdown="1"
  1536. # attribute is found whitin a tag, _HashHTMLBlocks_InHTML calls back
  1537. # _HashHTMLBlocks_InMarkdown to handle the Markdown syntax within the tag.
  1538. # These two functions are calling each other. It's recursive!
  1539. #
  1540. #
  1541. # Call the HTML-in-Markdown hasher.
  1542. #
  1543. list($text, ) = $this->_hashHTMLBlocks_inMarkdown($text);
  1544. return $text;
  1545. }
  1546. function _hashHTMLBlocks_inMarkdown($text, $indent = 0,
  1547. $enclosing_tag_re = '', $span = false)
  1548. {
  1549. #
  1550. # Parse markdown text, calling _HashHTMLBlocks_InHTML for block tags.
  1551. #
  1552. # * $indent is the number of space to be ignored when checking for code
  1553. # blocks. This is important because if we don't take the indent into
  1554. # account, something like this (which looks right) won't work as expected:
  1555. #
  1556. # <div>
  1557. # <div markdown="1">
  1558. # Hello World. <-- Is this a Markdown code block or text?
  1559. # </div> <-- Is this a Markdown code block or a real tag?
  1560. # <div>
  1561. #
  1562. # If you don't like this, just don't indent the tag on which
  1563. # you apply the markdown="1" attribute.
  1564. #
  1565. # * If $enclosing_tag_re is not empty, stops at the first unmatched closing
  1566. # tag with that name. Nested tags supported.
  1567. #
  1568. # * If $span is true, text inside must treated as span. So any double
  1569. # newline will be replaced by a single newline so that it does not create
  1570. # paragraphs.
  1571. #
  1572. # Returns an array of that form: ( processed text , remaining text )
  1573. #
  1574. if ($text === '') return array('', '');
  1575. # Regex to check for the presense of newlines around a block tag.
  1576. $newline_before_re = '/(?:^\n?|\n\n)*$/';
  1577. $newline_after_re =
  1578. '{
  1579. ^ # Start of text following the tag.
  1580. (?>[ ]*<!--.*?-->)? # Optional comment.
  1581. [ ]*\n # Must be followed by newline.
  1582. }xs';
  1583. # Regex to match any tag.
  1584. $block_tag_re =
  1585. '{
  1586. ( # $2: Capture hole tag.
  1587. </? # Any opening or closing tag.
  1588. (?> # Tag name.
  1589. '.$this->block_tags_re.' |
  1590. '.$this->context_block_tags_re.' |
  1591. '.$this->clean_tags_re.' |
  1592. (?!\s)'.$enclosing_tag_re.'
  1593. )
  1594. (?:
  1595. (?=[\s"\'/a-zA-Z0-9]) # Allowed characters after tag name.
  1596. (?>
  1597. ".*?" | # Double quotes (can contain `>`)
  1598. \'.*?\' | # Single quotes (can contain `>`)
  1599. .+? # Anything but quotes and `>`.
  1600. )*?
  1601. )?
  1602. > # End of tag.
  1603. |
  1604. <!-- .*? --> # HTML Comment
  1605. |
  1606. <\?.*?\?> | <%.*?%> # Processing instruction
  1607. |
  1608. <!\[CDATA\[.*?\]\]> # CData Block
  1609. |
  1610. # Code span marker
  1611. `+
  1612. '. ( !$span ? ' # If not in span.
  1613. |
  1614. # Indented code block
  1615. (?: ^[ ]*\n | ^ | \n[ ]*\n )
  1616. [ ]{'.($indent+4).'}[^\n]* \n
  1617. (?>
  1618. (?: [ ]{'.($indent+4).'}[^\n]* | [ ]* ) \n
  1619. )*
  1620. |
  1621. # Fenced code block marker
  1622. (?> ^ | \n )
  1623. [ ]{0,'.($indent).'}~~~+[ ]*\n
  1624. ' : '' ). ' # End (if not is span).
  1625. )
  1626. }xs';
  1627. $depth = 0; # Current depth inside the tag tree.
  1628. $parsed = ""; # Parsed text that will be returned.
  1629. #
  1630. # Loop through every tag until we find the closing tag of the parent
  1631. # or loop until reaching the end of text if no parent tag specified.
  1632. #
  1633. do {
  1634. #
  1635. # Split the text using the first $tag_match pattern found.
  1636. # Text before pattern will be first in the array, text after
  1637. # pattern will be at the end, and between will be any catches made
  1638. # by the pattern.
  1639. #
  1640. $parts = preg_split($block_tag_re, $text, 2,
  1641. PREG_SPLIT_DELIM_CAPTURE);
  1642. # If in Markdown span mode, add a empty-string span-level hash
  1643. # after each newline to prevent triggering any block element.
  1644. if ($span) {
  1645. $void = $this->hashPart("", ':');
  1646. $newline = "$void\n";
  1647. $parts[0] = $void . str_replace("\n", $newline, $parts[0]) . $void;
  1648. }
  1649. $parsed .= $parts[0]; # Text before current tag.
  1650. # If end of $text has been reached. Stop loop.
  1651. if (count($parts) < 3) {
  1652. $text = "";
  1653. break;
  1654. }
  1655. $tag = $parts[1]; # Tag to handle.
  1656. $text = $parts[2]; # Remaining text after current tag.
  1657. $tag_re = preg_quote($tag); # For use in a regular expression.
  1658. #
  1659. # Check for: Code span marker
  1660. #
  1661. if ($tag{0} == "`") {
  1662. # Find corresponding end marker.
  1663. $tag_re = preg_quote($tag);
  1664. if (preg_match('{^(?>.+?|\n(?!\n))*?(?<!`)'.$tag_re.'(?!`)}',
  1665. $text, $matches))
  1666. {
  1667. # End marker found: pass text unchanged until marker.
  1668. $parsed .= $tag . $matches[0];
  1669. $text = substr($text, strlen($matches[0]));
  1670. }
  1671. else {
  1672. # Unmatched marker: just skip it.
  1673. $parsed .= $tag;
  1674. }
  1675. }
  1676. #
  1677. # Check for: Fenced code block marker.
  1678. #
  1679. else if (preg_match('{^\n?[ ]{0,'.($indent+3).'}~}', $tag)) {
  1680. # Fenced code block marker: find matching end marker.
  1681. $tag_re = preg_quote(trim($tag));
  1682. if (preg_match('{^(?>.*\n)+?[ ]{0,'.($indent).'}'.$tag_re.'[ ]*\n}', $text,
  1683. $matches))
  1684. {
  1685. # End marker found: pass text unchanged until marker.
  1686. $parsed .= $tag . $matches[0];
  1687. $text = substr($text, strlen($matches[0]));
  1688. }
  1689. else {
  1690. # No end marker: just skip it.
  1691. $parsed .= $tag;
  1692. }
  1693. }
  1694. #
  1695. # Check for: Indented code block.
  1696. #
  1697. else if ($tag{0} == "\n" || $tag{0} == " ") {
  1698. # Indented code block: pass it unchanged, will be handled
  1699. # later.
  1700. $parsed .= $tag;
  1701. }
  1702. #
  1703. # Check for: Opening Block level tag or
  1704. # Opening Context Block tag (like ins and del)
  1705. # used as a block tag (tag is alone on it's line).
  1706. #
  1707. else if (preg_match('{^<(?:'.$this->block_tags_re.')\b}', $tag) ||
  1708. ( preg_match('{^<(?:'.$this->context_block_tags_re.')\b}', $tag) &&
  1709. preg_match($newline_before_re, $parsed) &&
  1710. preg_match($newline_after_re, $text) )
  1711. )
  1712. {
  1713. # Need to parse tag and following text using the HTML parser.
  1714. list($block_text, $text) =
  1715. $this->_hashHTMLBlocks_inHTML($tag . $text, "hashBlock", true);
  1716. # Make sure it stays outside of any paragraph by adding newlines.
  1717. $parsed .= "\n\n$block_text\n\n";
  1718. }
  1719. #
  1720. # Check for: Clean tag (like script, math)
  1721. # HTML Comments, processing instructions.
  1722. #
  1723. else if (preg_match('{^<(?:'.$this->clean_tags_re.')\b}', $tag) ||
  1724. $tag{1} == '!' || $tag{1} == '?')
  1725. {
  1726. # Need to parse tag and following text using the HTML parser.
  1727. # (don't check for markdown attribute)
  1728. list($block_text, $text) =
  1729. $this->_hashHTMLBlocks_inHTML($tag . $text, "hashClean", false);
  1730. $parsed .= $block_text;
  1731. }
  1732. #
  1733. # Check for: Tag with same name as enclosing tag.
  1734. #
  1735. else if ($enclosing_tag_re !== '' &&
  1736. # Same name as enclosing tag.
  1737. preg_match('{^</?(?:'.$enclosing_tag_re.')\b}', $tag))
  1738. {
  1739. #
  1740. # Increase/decrease nested tag count.
  1741. #
  1742. if ($tag{1} == '/') $depth--;
  1743. else if ($tag{strlen($tag)-2} != '/') $depth++;
  1744. if ($depth < 0) {
  1745. #
  1746. # Going out of parent element. Clean up and break so we
  1747. # return to the calling function.
  1748. #
  1749. $text = $tag . $text;
  1750. break;
  1751. }
  1752. $parsed .= $tag;
  1753. }
  1754. else {
  1755. $parsed .= $tag;
  1756. }
  1757. } while ($depth >= 0);
  1758. return array($parsed, $text);
  1759. }
  1760. function _hashHTMLBlocks_inHTML($text, $hash_method, $md_attr) {
  1761. #
  1762. # Parse HTML, calling _HashHTMLBlocks_InMarkdown for block tags.
  1763. #
  1764. # * Calls $hash_method to convert any blocks.
  1765. # * Stops when the first opening tag closes.
  1766. # * $md_attr indicate if the use of the `markdown="1"` attribute is allowed.
  1767. # (it is not inside clean tags)
  1768. #
  1769. # Returns an array of that form: ( processed text , remaining text )
  1770. #
  1771. if ($text === '') return array('', '');
  1772. # Regex to match `markdown` attribute inside of a tag.
  1773. $markdown_attr_re = '
  1774. {
  1775. \s* # Eat whitespace before the `markdown` attribute
  1776. markdown
  1777. \s*=\s*
  1778. (?>
  1779. (["\']) # $1: quote delimiter
  1780. (.*?) # $2: attribute value
  1781. \1 # matching delimiter
  1782. |
  1783. ([^\s>]*) # $3: unquoted attribute value
  1784. )
  1785. () # $4: make $3 always defined (avoid warnings)
  1786. }xs';
  1787. # Regex to match any tag.
  1788. $tag_re = '{
  1789. ( # $2: Capture hole tag.
  1790. </? # Any opening or closing tag.
  1791. [\w:$]+ # Tag name.
  1792. (?:
  1793. (?=[\s"\'/a-zA-Z0-9]) # Allowed characters after tag name.
  1794. (?>
  1795. ".*?" | # Double quotes (can contain `>`)
  1796. \'.*?\' | # Single quotes (can contain `>`)
  1797. .+? # Anything but quotes and `>`.
  1798. )*?
  1799. )?
  1800. > # End of tag.
  1801. |
  1802. <!-- .*? --> # HTML Comment
  1803. |
  1804. <\?.*?\?> | <%.*?%> # Processing instruction
  1805. |
  1806. <!\[CDATA\[.*?\]\]> # CData Block
  1807. )
  1808. }xs';
  1809. $original_text = $text; # Save original text in case of faliure.
  1810. $depth = 0; # Current depth inside the tag tree.
  1811. $block_text = ""; # Temporary text holder for current text.
  1812. $parsed = ""; # Parsed text that will be returned.
  1813. #
  1814. # Get the name of the starting tag.
  1815. # (This pattern makes $base_tag_name_re safe without quoting.)
  1816. #
  1817. if (preg_match('/^<([\w:$]*)\b/', $text, $matches))
  1818. $base_tag_name_re = $matches[1];
  1819. #
  1820. # Loop through every tag until we find the corresponding closing tag.
  1821. #
  1822. do {
  1823. #
  1824. # Split the text using the first $tag_match pattern found.
  1825. # Text before pattern will be first in the array, text after
  1826. # pattern will be at the end, and between will be any catches made
  1827. # by the pattern.
  1828. #
  1829. $parts = preg_split($tag_re, $text, 2, PREG_SPLIT_DELIM_CAPTURE);
  1830. if (count($parts) < 3) {
  1831. #
  1832. # End of $text reached with unbalenced tag(s).
  1833. # In that case, we return original text unchanged and pass the
  1834. # first character as filtered to prevent an infinite loop in the
  1835. # parent function.
  1836. #
  1837. return array($original_text{0}, substr($original_text, 1));
  1838. }
  1839. $block_text .= $parts[0]; # Text before current tag.
  1840. $tag = $parts[1]; # Tag to handle.
  1841. $text = $parts[2]; # Remaining text after current tag.
  1842. #
  1843. # Check for: Auto-close tag (like <hr/>)
  1844. # Comments and Processing Instructions.
  1845. #
  1846. if (preg_match('{^</?(?:'.$this->auto_close_tags_re.')\b}', $tag) ||
  1847. $tag{1} == '!' || $tag{1} == '?')
  1848. {
  1849. # Just add the tag to the block as if it was text.
  1850. $block_text .= $tag;
  1851. }
  1852. else {
  1853. #
  1854. # Increase/decrease nested tag count. Only do so if
  1855. # the tag's name match base tag's.
  1856. #
  1857. if (preg_match('{^</?'.$base_tag_name_re.'\b}', $tag)) {
  1858. if ($tag{1} == '/') $depth--;
  1859. else if ($tag{strlen($tag)-2} != '/') $depth++;
  1860. }
  1861. #
  1862. # Check for `markdown="1"` attribute and handle it.
  1863. #
  1864. if ($md_attr &&
  1865. preg_match($markdown_attr_re, $tag, $attr_m) &&
  1866. preg_match('/^1|block|span$/', $attr_m[2] . $attr_m[3]))
  1867. {
  1868. # Remove `markdown` attribute from opening tag.
  1869. $tag = preg_replace($markdown_attr_re, '', $tag);
  1870. # Check if text inside this tag must be parsed in span mode.
  1871. $this->mode = $attr_m[2] . $attr_m[3];
  1872. $span_mode = $this->mode == 'span' || $this->mode != 'block' &&
  1873. preg_match('{^<(?:'.$this->contain_span_tags_re.')\b}', $tag);
  1874. # Calculate indent before tag.
  1875. if (preg_match('/(?:^|\n)( *?)(?! ).*?$/', $block_text, $matches)) {
  1876. $strlen = $this->utf8_strlen;
  1877. $indent = $strlen($matches[1], 'UTF-8');
  1878. } else {
  1879. $indent = 0;
  1880. }
  1881. # End preceding block with this tag.
  1882. $block_text .= $tag;
  1883. $parsed .= $this->$hash_method($block_text);
  1884. # Get enclosing tag name for the ParseMarkdown function.
  1885. # (This pattern makes $tag_name_re safe without quoting.)
  1886. preg_match('/^<([\w:$]*)\b/', $tag, $matches);
  1887. $tag_name_re = $matches[1];
  1888. # Parse the content using the HTML-in-Markdown parser.
  1889. list ($block_text, $text)
  1890. = $this->_hashHTMLBlocks_inMarkdown($text, $indent,
  1891. $tag_name_re, $span_mode);
  1892. # Outdent markdown text.
  1893. if ($indent > 0) {
  1894. $block_text = preg_replace("/^[ ]{1,$indent}/m", "",
  1895. $block_text);
  1896. }
  1897. # Append tag content to parsed text.
  1898. if (!$span_mode) $parsed .= "\n\n$block_text\n\n";
  1899. else $parsed .= "$block_text";
  1900. # Start over a new block.
  1901. $block_text = "";
  1902. }
  1903. else $block_text .= $tag;
  1904. }
  1905. } while ($depth > 0);
  1906. #
  1907. # Hash last block text that wasn't processed inside the loop.
  1908. #
  1909. $parsed .= $this->$hash_method($block_text);
  1910. return array($parsed, $text);
  1911. }
  1912. function hashClean($text) {
  1913. #
  1914. # Called whenever a tag must be hashed when a function insert a "clean" tag
  1915. # in $text, it pass through this function and is automaticaly escaped,
  1916. # blocking invalid nested overlap.
  1917. #
  1918. return $this->hashPart($text, 'C');
  1919. }
  1920. function doHeaders($text) {
  1921. #
  1922. # Redefined to add id attribute support.
  1923. #
  1924. # Setext-style headers:
  1925. # Header 1 {#header1}
  1926. # ========
  1927. #
  1928. # Header 2 {#header2}
  1929. # --------
  1930. #
  1931. $text = preg_replace_callback(
  1932. '{
  1933. (^.+?) # $1: Header text
  1934. (?:[ ]+\{\#([-_:a-zA-Z0-9]+)\})? # $2: Id attribute
  1935. [ ]*\n(=+|-+)[ ]*\n+ # $3: Header footer
  1936. }mx',
  1937. array(&$this, '_doHeaders_callback_setext'), $text);
  1938. # atx-style headers:
  1939. # # Header 1 {#header1}
  1940. # ## Header 2 {#header2}
  1941. # ## Header 2 with closing hashes ## {#header3}
  1942. # ...
  1943. # ###### Header 6 {#header2}
  1944. #
  1945. $text = preg_replace_callback('{
  1946. ^(\#{1,6}) # $1 = string of #\'s
  1947. [ ]*
  1948. (.+?) # $2 = Header text
  1949. [ ]*
  1950. \#* # optional closing #\'s (not counted)
  1951. (?:[ ]+\{\#([-_:a-zA-Z0-9]+)\})? # id attribute
  1952. [ ]*
  1953. \n+
  1954. }xm',
  1955. array(&$this, '_doHeaders_callback_atx'), $text);
  1956. return $text;
  1957. }
  1958. function _doHeaders_attr($attr) {
  1959. if (empty($attr)) return "";
  1960. return " id=\"$attr\"";
  1961. }
  1962. function _doHeaders_callback_setext($matches) {
  1963. if ($matches[3] == '-' && preg_match('{^- }', $matches[1]))
  1964. return $matches[0];
  1965. $level = $matches[3]{0} == '=' ? 1 : 2;
  1966. $attr = $this->_doHeaders_attr($id =& $matches[2]);
  1967. $block = "<h$level$attr>".$this->runSpanGamut($matches[1])."</h$level>";
  1968. return "\n" . $this->hashBlock($block) . "\n\n";
  1969. }
  1970. function _doHeaders_callback_atx($matches) {
  1971. $level = strlen($matches[1]);
  1972. $attr = $this->_doHeaders_attr($id =& $matches[3]);
  1973. $block = "<h$level$attr>".$this->runSpanGamut($matches[2])."</h$level>";
  1974. return "\n" . $this->hashBlock($block) . "\n\n";
  1975. }
  1976. function doTables($text) {
  1977. #
  1978. # Form HTML tables.
  1979. #
  1980. $less_than_tab = $this->tab_width - 1;
  1981. #
  1982. # Find tables with leading pipe.
  1983. #
  1984. # | Header 1 | Header 2
  1985. # | -------- | --------
  1986. # | Cell 1 | Cell 2
  1987. # | Cell 3 | Cell 4
  1988. #
  1989. $text = preg_replace_callback('
  1990. {
  1991. ^ # Start of a line
  1992. [ ]{0,'.$less_than_tab.'} # Allowed whitespace.
  1993. [|] # Optional leading pipe (present)
  1994. (.+) \n # $1: Header row (at least one pipe)
  1995. [ ]{0,'.$less_than_tab.'} # Allowed whitespace.
  1996. [|] ([ ]*[-:]+[-| :]*) \n # $2: Header underline
  1997. ( # $3: Cells
  1998. (?>
  1999. [ ]* # Allowed whitespace.
  2000. [|] .* \n # Row content.
  2001. )*
  2002. )
  2003. (?=\n|\Z) # Stop at final double newline.
  2004. }xm',
  2005. array(&$this, '_doTable_leadingPipe_callback'), $text);
  2006. #
  2007. # Find tables without leading pipe.
  2008. #
  2009. # Header 1 | Header 2
  2010. # -------- | --------
  2011. # Cell 1 | Cell 2
  2012. # Cell 3 | Cell 4
  2013. #
  2014. $text = preg_replace_callback('
  2015. {
  2016. ^ # Start of a line
  2017. [ ]{0,'.$less_than_tab.'} # Allowed whitespace.
  2018. (\S.*[|].*) \n # $1: Header row (at least one pipe)
  2019. [ ]{0,'.$less_than_tab.'} # Allowed whitespace.
  2020. ([-:]+[ ]*[|][-| :]*) \n # $2: Header underline
  2021. ( # $3: Cells
  2022. (?>
  2023. .* [|] .* \n # Row content
  2024. )*
  2025. )
  2026. (?=\n|\Z) # Stop at final double newline.
  2027. }xm',
  2028. array(&$this, '_DoTable_callback'), $text);
  2029. return $text;
  2030. }
  2031. function _doTable_leadingPipe_callback($matches) {
  2032. $head = $matches[1];
  2033. $underline = $matches[2];
  2034. $content = $matches[3];
  2035. # Remove leading pipe for each row.
  2036. $content = preg_replace('/^ *[|]/m', '', $content);
  2037. return $this->_doTable_callback(array($matches[0], $head, $underline, $content));
  2038. }
  2039. function _doTable_callback($matches) {
  2040. $head = $matches[1];
  2041. $underline = $matches[2];
  2042. $content = $matches[3];
  2043. # Remove any tailing pipes for each line.
  2044. $head = preg_replace('/[|] *$/m', '', $head);
  2045. $underline = preg_replace('/[|] *$/m', '', $underline);
  2046. $content = preg_replace('/[|] *$/m', '', $content);
  2047. # Reading alignement from header underline.
  2048. $separators = preg_split('/ *[|] */', $underline);
  2049. foreach ($separators as $n => $s) {
  2050. if (preg_match('/^ *-+: *$/', $s)) $attr[$n] = ' align="right"';
  2051. else if (preg_match('/^ *:-+: *$/', $s))$attr[$n] = ' align="center"';
  2052. else if (preg_match('/^ *:-+ *$/', $s)) $attr[$n] = ' align="left"';
  2053. else $attr[$n] = '';
  2054. }
  2055. # Parsing span elements, including code spans, character escapes,
  2056. # and inline HTML tags, so that pipes inside those gets ignored.
  2057. $head = $this->parseSpan($head);
  2058. $headers = preg_split('/ *[|] */', $head);
  2059. $col_count = count($headers);
  2060. # Write column headers.
  2061. $text = "<table>\n";
  2062. $text .= "<thead>\n";
  2063. $text .= "<tr>\n";
  2064. foreach ($headers as $n => $header)
  2065. $text .= " <th$attr[$n]>".$this->runSpanGamut(trim($header))."</th>\n";
  2066. $text .= "</tr>\n";
  2067. $text .= "</thead>\n";
  2068. # Split content by row.
  2069. $rows = explode("\n", trim($content, "\n"));
  2070. $text .= "<tbody>\n";
  2071. foreach ($rows as $row) {
  2072. # Parsing span elements, including code spans, character escapes,
  2073. # and inline HTML tags, so that pipes inside those gets ignored.
  2074. $row = $this->parseSpan($row);
  2075. # Split row by cell.
  2076. $row_cells = preg_split('/ *[|] */', $row, $col_count);
  2077. $row_cells = array_pad($row_cells, $col_count, '');
  2078. $text .= "<tr>\n";
  2079. foreach ($row_cells as $n => $cell)
  2080. $text .= " <td$attr[$n]>".$this->runSpanGamut(trim($cell))."</td>\n";
  2081. $text .= "</tr>\n";
  2082. }
  2083. $text .= "</tbody>\n";
  2084. $text .= "</table>";
  2085. return $this->hashBlock($text) . "\n";
  2086. }
  2087. function doDefLists($text) {
  2088. #
  2089. # Form HTML definition lists.
  2090. #
  2091. $less_than_tab = $this->tab_width - 1;
  2092. # Re-usable pattern to match any entire dl list:
  2093. $whole_list_re = '(?>
  2094. ( # $1 = whole list
  2095. ( # $2
  2096. [ ]{0,'.$less_than_tab.'}
  2097. ((?>.*\S.*\n)+) # $3 = defined term
  2098. \n?
  2099. [ ]{0,'.$less_than_tab.'}:[ ]+ # colon starting definition
  2100. )
  2101. (?s:.+?)
  2102. ( # $4
  2103. \z
  2104. |
  2105. \n{2,}
  2106. (?=\S)
  2107. (?! # Negative lookahead for another term
  2108. [ ]{0,'.$less_than_tab.'}
  2109. (?: \S.*\n )+? # defined term
  2110. \n?
  2111. [ ]{0,'.$less_than_tab.'}:[ ]+ # colon starting definition
  2112. )
  2113. (?! # Negative lookahead for another definition
  2114. [ ]{0,'.$less_than_tab.'}:[ ]+ # colon starting definition
  2115. )
  2116. )
  2117. )
  2118. )'; // mx
  2119. $text = preg_replace_callback('{
  2120. (?>\A\n?|(?<=\n\n))
  2121. '.$whole_list_re.'
  2122. }mx',
  2123. array(&$this, '_doDefLists_callback'), $text);
  2124. return $text;
  2125. }
  2126. function _doDefLists_callback($matches) {
  2127. # Re-usable patterns to match list item bullets and number markers:
  2128. $list = $matches[1];
  2129. # Turn double returns into triple returns, so that we can make a
  2130. # paragraph for the last item in a list, if necessary:
  2131. $result = trim($this->processDefListItems($list));
  2132. $result = "<dl>\n" . $result . "\n</dl>";
  2133. return $this->hashBlock($result) . "\n\n";
  2134. }
  2135. function processDefListItems($list_str) {
  2136. #
  2137. # Process the contents of a single definition list, splitting it
  2138. # into individual term and definition list items.
  2139. #
  2140. $less_than_tab = $this->tab_width - 1;
  2141. # trim trailing blank lines:
  2142. $list_str = preg_replace("/\n{2,}\\z/", "\n", $list_str);
  2143. # Process definition terms.
  2144. $list_str = preg_replace_callback('{
  2145. (?>\A\n?|\n\n+) # leading line
  2146. ( # definition terms = $1
  2147. [ ]{0,'.$less_than_tab.'} # leading whitespace
  2148. (?![:][ ]|[ ]) # negative lookahead for a definition
  2149. # mark (colon) or more whitespace.
  2150. (?> \S.* \n)+? # actual term (not whitespace).
  2151. )
  2152. (?=\n?[ ]{0,3}:[ ]) # lookahead for following line feed
  2153. # with a definition mark.
  2154. }xm',
  2155. array(&$this, '_processDefListItems_callback_dt'), $list_str);
  2156. # Process actual definitions.
  2157. $list_str = preg_replace_callback('{
  2158. \n(\n+)? # leading line = $1
  2159. ( # marker space = $2
  2160. [ ]{0,'.$less_than_tab.'} # whitespace before colon
  2161. [:][ ]+ # definition mark (colon)
  2162. )
  2163. ((?s:.+?)) # definition text = $3
  2164. (?= \n+ # stop at next definition mark,
  2165. (?: # next term or end of text
  2166. [ ]{0,'.$less_than_tab.'} [:][ ] |
  2167. <dt> | \z
  2168. )
  2169. )
  2170. }xm',
  2171. array(&$this, '_processDefListItems_callback_dd'), $list_str);
  2172. return $list_str;
  2173. }
  2174. function _processDefListItems_callback_dt($matches) {
  2175. $terms = explode("\n", trim($matches[1]));
  2176. $text = '';
  2177. foreach ($terms as $term) {
  2178. $term = $this->runSpanGamut(trim($term));
  2179. $text .= "\n<dt>" . $term . "</dt>";
  2180. }
  2181. return $text . "\n";
  2182. }
  2183. function _processDefListItems_callback_dd($matches) {
  2184. $leading_line = $matches[1];
  2185. $marker_space = $matches[2];
  2186. $def = $matches[3];
  2187. if ($leading_line || preg_match('/\n{2,}/', $def)) {
  2188. # Replace marker with the appropriate whitespace indentation
  2189. $def = str_repeat(' ', strlen($marker_space)) . $def;
  2190. $def = $this->runBlockGamut($this->outdent($def . "\n\n"));
  2191. $def = "\n". $def ."\n";
  2192. }
  2193. else {
  2194. $def = rtrim($def);
  2195. $def = $this->runSpanGamut($this->outdent($def));
  2196. }
  2197. return "\n<dd>" . $def . "</dd>\n";
  2198. }
  2199. function doFencedCodeBlocks($text) {
  2200. #
  2201. # Adding the fenced code block syntax to regular Markdown:
  2202. #
  2203. # ~~~
  2204. # Code block
  2205. # ~~~
  2206. #
  2207. $less_than_tab = $this->tab_width;
  2208. $text = preg_replace_callback('{
  2209. (?:\n|\A)
  2210. # 1: Opening marker
  2211. (
  2212. ~{3,} # Marker: three tilde or more.
  2213. )
  2214. [ ]* \n # Whitespace and newline following marker.
  2215. # 2: Content
  2216. (
  2217. (?>
  2218. (?!\1 [ ]* \n) # Not a closing marker.
  2219. .*\n+
  2220. )+
  2221. )
  2222. # Closing marker.
  2223. \1 [ ]* \n
  2224. }xm',
  2225. array(&$this, '_doFencedCodeBlocks_callback'), $text);
  2226. return $text;
  2227. }
  2228. function _doFencedCodeBlocks_callback($matches) {
  2229. $codeblock = $matches[2];
  2230. $codeblock = htmlspecialchars($codeblock, ENT_NOQUOTES);
  2231. $codeblock = preg_replace_callback('/^\n+/',
  2232. array(&$this, '_doFencedCodeBlocks_newlines'), $codeblock);
  2233. $codeblock = "<pre><code>$codeblock</code></pre>";
  2234. return "\n\n".$this->hashBlock($codeblock)."\n\n";
  2235. }
  2236. function _doFencedCodeBlocks_newlines($matches) {
  2237. return str_repeat("<br$this->empty_element_suffix",
  2238. strlen($matches[0]));
  2239. }
  2240. #
  2241. # Redefining emphasis markers so that emphasis by underscore does not
  2242. # work in the middle of a word.
  2243. #
  2244. var $em_relist = array(
  2245. '' => '(?:(?<!\*)\*(?!\*)|(?<![a-zA-Z0-9_])_(?!_))(?=\S|$)(?![\.,:;]\s)',
  2246. '*' => '(?<=\S|^)(?<!\*)\*(?!\*)',
  2247. '_' => '(?<=\S|^)(?<!_)_(?![a-zA-Z0-9_])',
  2248. );
  2249. var $strong_relist = array(
  2250. '' => '(?:(?<!\*)\*\*(?!\*)|(?<![a-zA-Z0-9_])__(?!_))(?=\S|$)(?![\.,:;]\s)',
  2251. '**' => '(?<=\S|^)(?<!\*)\*\*(?!\*)',
  2252. '__' => '(?<=\S|^)(?<!_)__(?![a-zA-Z0-9_])',
  2253. );
  2254. var $em_strong_relist = array(
  2255. '' => '(?:(?<!\*)\*\*\*(?!\*)|(?<![a-zA-Z0-9_])___(?!_))(?=\S|$)(?![\.,:;]\s)',
  2256. '***' => '(?<=\S|^)(?<!\*)\*\*\*(?!\*)',
  2257. '___' => '(?<=\S|^)(?<!_)___(?![a-zA-Z0-9_])',
  2258. );
  2259. function formParagraphs($text) {
  2260. #
  2261. # Params:
  2262. # $text - string to process with html <p> tags
  2263. #
  2264. # Strip leading and trailing lines:
  2265. $text = preg_replace('/\A\n+|\n+\z/', '', $text);
  2266. $grafs = preg_split('/\n{2,}/', $text, -1, PREG_SPLIT_NO_EMPTY);
  2267. #
  2268. # Wrap <p> tags and unhashify HTML blocks
  2269. #
  2270. foreach ($grafs as $key => $value) {
  2271. $value = trim($this->runSpanGamut($value));
  2272. # Check if this should be enclosed in a paragraph.
  2273. # Clean tag hashes & block tag hashes are left alone.
  2274. $is_p = !preg_match('/^B\x1A[0-9]+B|^C\x1A[0-9]+C$/', $value);
  2275. if ($is_p) {
  2276. $value = "<p>$value</p>";
  2277. }
  2278. $grafs[$key] = $value;
  2279. }
  2280. # Join grafs in one text, then unhash HTML tags.
  2281. $text = implode("\n\n", $grafs);
  2282. # Finish by removing any tag hashes still present in $text.
  2283. $text = $this->unhash($text);
  2284. return $text;
  2285. }
  2286. ### Footnotes
  2287. function stripFootnotes($text) {
  2288. #
  2289. # Strips link definitions from text, stores the URLs and titles in
  2290. # hash references.
  2291. #
  2292. $less_than_tab = $this->tab_width - 1;
  2293. # Link defs are in the form: [^id]: url "optional title"
  2294. $text = preg_replace_callback('{
  2295. ^[ ]{0,'.$less_than_tab.'}\[\^(.+?)\][ ]?: # note_id = $1
  2296. [ ]*
  2297. \n? # maybe *one* newline
  2298. ( # text = $2 (no blank lines allowed)
  2299. (?:
  2300. .+ # actual text
  2301. |
  2302. \n # newlines but
  2303. (?!\[\^.+?\]:\s)# negative lookahead for footnote marker.
  2304. (?!\n+[ ]{0,3}\S)# ensure line is not blank and followed
  2305. # by non-indented content
  2306. )*
  2307. )
  2308. }xm',
  2309. array(&$this, '_stripFootnotes_callback'),
  2310. $text);
  2311. return $text;
  2312. }
  2313. function _stripFootnotes_callback($matches) {
  2314. $note_id = $this->fn_id_prefix . $matches[1];
  2315. $this->footnotes[$note_id] = $this->outdent($matches[2]);
  2316. return ''; # String that will replace the block
  2317. }
  2318. function doFootnotes($text) {
  2319. #
  2320. # Replace footnote references in $text [^id] with a special text-token
  2321. # which will be replaced by the actual footnote marker in appendFootnotes.
  2322. #
  2323. if (!$this->in_anchor) {
  2324. $text = preg_replace('{\[\^(.+?)\]}', "F\x1Afn:\\1\x1A:", $text);
  2325. }
  2326. return $text;
  2327. }
  2328. function appendFootnotes($text) {
  2329. #
  2330. # Append footnote list to text.
  2331. #
  2332. $text = preg_replace_callback('{F\x1Afn:(.*?)\x1A:}',
  2333. array(&$this, '_appendFootnotes_callback'), $text);
  2334. if (!empty($this->footnotes_ordered)) {
  2335. $text .= "\n\n";
  2336. $text .= "<div class=\"footnotes\">\n";
  2337. $text .= "<hr". $this->empty_element_suffix ."\n";
  2338. $text .= "<ol>\n\n";
  2339. $attr = " rev=\"footnote\"";
  2340. if ($this->fn_backlink_class != "") {
  2341. $class = $this->fn_backlink_class;
  2342. $class = $this->encodeAttribute($class);
  2343. $attr .= " class=\"$class\"";
  2344. }
  2345. if ($this->fn_backlink_title != "") {
  2346. $title = $this->fn_backlink_title;
  2347. $title = $this->encodeAttribute($title);
  2348. $attr .= " title=\"$title\"";
  2349. }
  2350. $num = 0;
  2351. while (!empty($this->footnotes_ordered)) {
  2352. $footnote = reset($this->footnotes_ordered);
  2353. $note_id = key($this->footnotes_ordered);
  2354. unset($this->footnotes_ordered[$note_id]);
  2355. $footnote .= "\n"; # Need to append newline before parsing.
  2356. $footnote = $this->runBlockGamut("$footnote\n");
  2357. $footnote = preg_replace_callback('{F\x1Afn:(.*?)\x1A:}',
  2358. array(&$this, '_appendFootnotes_callback'), $footnote);
  2359. $attr = str_replace("%%", ++$num, $attr);
  2360. $note_id = $this->encodeAttribute($note_id);
  2361. # Add backlink to last paragraph; create new paragraph if needed.
  2362. $backlink = "<a href=\"#fnref:$note_id\"$attr>&#8617;</a>";
  2363. if (preg_match('{</p>$}', $footnote)) {
  2364. $footnote = substr($footnote, 0, -4) . "&#160;$backlink</p>";
  2365. } else {
  2366. $footnote .= "\n\n<p>$backlink</p>";
  2367. }
  2368. $text .= "<li id=\"fn:$note_id\">\n";
  2369. $text .= $footnote . "\n";
  2370. $text .= "</li>\n\n";
  2371. }
  2372. $text .= "</ol>\n";
  2373. $text .= "</div>";
  2374. }
  2375. return $text;
  2376. }
  2377. function _appendFootnotes_callback($matches) {
  2378. $node_id = $this->fn_id_prefix . $matches[1];
  2379. # Create footnote marker only if it has a corresponding footnote *and*
  2380. # the footnote hasn't been used by another marker.
  2381. if (isset($this->footnotes[$node_id])) {
  2382. # Transfert footnote content to the ordered list.
  2383. $this->footnotes_ordered[$node_id] = $this->footnotes[$node_id];
  2384. unset($this->footnotes[$node_id]);
  2385. $num = $this->footnote_counter++;
  2386. $attr = " rel=\"footnote\"";
  2387. if ($this->fn_link_class != "") {
  2388. $class = $this->fn_link_class;
  2389. $class = $this->encodeAttribute($class);
  2390. $attr .= " class=\"$class\"";
  2391. }
  2392. if ($this->fn_link_title != "") {
  2393. $title = $this->fn_link_title;
  2394. $title = $this->encodeAttribute($title);
  2395. $attr .= " title=\"$title\"";
  2396. }
  2397. $attr = str_replace("%%", $num, $attr);
  2398. $node_id = $this->encodeAttribute($node_id);
  2399. return
  2400. "<sup id=\"fnref:$node_id\">".
  2401. "<a href=\"#fn:$node_id\"$attr>$num</a>".
  2402. "</sup>";
  2403. }
  2404. return "[^".$matches[1]."]";
  2405. }
  2406. ### Abbreviations ###
  2407. function stripAbbreviations($text) {
  2408. #
  2409. # Strips abbreviations from text, stores titles in hash references.
  2410. #
  2411. $less_than_tab = $this->tab_width - 1;
  2412. # Link defs are in the form: [id]*: url "optional title"
  2413. $text = preg_replace_callback('{
  2414. ^[ ]{0,'.$less_than_tab.'}\*\[(.+?)\][ ]?: # abbr_id = $1
  2415. (.*) # text = $2 (no blank lines allowed)
  2416. }xm',
  2417. array(&$this, '_stripAbbreviations_callback'),
  2418. $text);
  2419. return $text;
  2420. }
  2421. function _stripAbbreviations_callback($matches) {
  2422. $abbr_word = $matches[1];
  2423. $abbr_desc = $matches[2];
  2424. if ($this->abbr_word_re)
  2425. $this->abbr_word_re .= '|';
  2426. $this->abbr_word_re .= preg_quote($abbr_word);
  2427. $this->abbr_desciptions[$abbr_word] = trim($abbr_desc);
  2428. return ''; # String that will replace the block
  2429. }
  2430. function doAbbreviations($text) {
  2431. #
  2432. # Find defined abbreviations in text and wrap them in <abbr> elements.
  2433. #
  2434. if ($this->abbr_word_re) {
  2435. // cannot use the /x modifier because abbr_word_re may
  2436. // contain significant spaces:
  2437. $text = preg_replace_callback('{'.
  2438. '(?<![\w\x1A])'.
  2439. '(?:'.$this->abbr_word_re.')'.
  2440. '(?![\w\x1A])'.
  2441. '}',
  2442. array(&$this, '_doAbbreviations_callback'), $text);
  2443. }
  2444. return $text;
  2445. }
  2446. function _doAbbreviations_callback($matches) {
  2447. $abbr = $matches[0];
  2448. if (isset($this->abbr_desciptions[$abbr])) {
  2449. $desc = $this->abbr_desciptions[$abbr];
  2450. if (empty($desc)) {
  2451. return $this->hashPart("<abbr>$abbr</abbr>");
  2452. } else {
  2453. $desc = $this->encodeAttribute($desc);
  2454. return $this->hashPart("<abbr title=\"$desc\">$abbr</abbr>");
  2455. }
  2456. } else {
  2457. return $matches[0];
  2458. }
  2459. }
  2460. }
  2461. /*
  2462. PHP Markdown Extra
  2463. ==================
  2464. Description
  2465. -----------
  2466. This is a PHP port of the original Markdown formatter written in Perl
  2467. by John Gruber. This special "Extra" version of PHP Markdown features
  2468. further enhancements to the syntax for making additional constructs
  2469. such as tables and definition list.
  2470. Markdown is a text-to-HTML filter; it translates an easy-to-read /
  2471. easy-to-write structured text format into HTML. Markdown's text format
  2472. is most similar to that of plain text email, and supports features such
  2473. as headers, *emphasis*, code blocks, blockquotes, and links.
  2474. Markdown's syntax is designed not as a generic markup language, but
  2475. specifically to serve as a front-end to (X)HTML. You can use span-level
  2476. HTML tags anywhere in a Markdown document, and you can use block level
  2477. HTML tags (like <div> and <table> as well).
  2478. For more information about Markdown's syntax, see:
  2479. <http://daringfireball.net/projects/markdown/>
  2480. Bugs
  2481. ----
  2482. To file bug reports please send email to:
  2483. <michel.fortin@michelf.com>
  2484. Please include with your report: (1) the example input; (2) the output you
  2485. expected; (3) the output Markdown actually produced.
  2486. Version History
  2487. ---------------
  2488. See the readme file for detailed release notes for this version.
  2489. Copyright and License
  2490. ---------------------
  2491. PHP Markdown & Extra
  2492. Copyright (c) 2004-2009 Michel Fortin
  2493. <http://michelf.com/>
  2494. All rights reserved.
  2495. Based on Markdown
  2496. Copyright (c) 2003-2006 John Gruber
  2497. <http://daringfireball.net/>
  2498. All rights reserved.
  2499. Redistribution and use in source and binary forms, with or without
  2500. modification, are permitted provided that the following conditions are
  2501. met:
  2502. * Redistributions of source code must retain the above copyright notice,
  2503. this list of conditions and the following disclaimer.
  2504. * Redistributions in binary form must reproduce the above copyright
  2505. notice, this list of conditions and the following disclaimer in the
  2506. documentation and/or other materials provided with the distribution.
  2507. * Neither the name "Markdown" nor the names of its contributors may
  2508. be used to endorse or promote products derived from this software
  2509. without specific prior written permission.
  2510. This software is provided by the copyright holders and contributors "as
  2511. is" and any express or implied warranties, including, but not limited
  2512. to, the implied warranties of merchantability and fitness for a
  2513. particular purpose are disclaimed. In no event shall the copyright owner
  2514. or contributors be liable for any direct, indirect, incidental, special,
  2515. exemplary, or consequential damages (including, but not limited to,
  2516. procurement of substitute goods or services; loss of use, data, or
  2517. profits; or business interruption) however caused and on any theory of
  2518. liability, whether in contract, strict liability, or tort (including
  2519. negligence or otherwise) arising in any way out of the use of this
  2520. software, even if advised of the possibility of such damage.
  2521. */
  2522. ?>