5űvX žxYžxY ŞFFFF000000060001001777AA000000000065000000001001710000001-7FFB6FBE1800000‚‚4800480611200-1‚0Â6‚11222FFFF0‚‚10‚‚3‚3300001000000330000000103340840‚‚6‚11222028E0006‚1110800002000000380000000033,Proof of concept tool for Markdown markup of posts.000400000009000000020350000500000009000000020350000600000031000000010Á920‚‚ÁFFFF0‚900000 20ÂÁ ‚‚Á‚000700000019000000010Â‚20180‚Á‚00080000009A0000000140,Verdana40,401C230 10000900000015000000023‚9C17D3‚9C17D000A00000015000000026‚112226‚11222000B00000005000000020Â000C000000150000000133‚‚91080102‚0000F0000005200000000400 10 ‚ÂÁÂÁ‚‚ÁÂ4,77A4,ËŢ`4,Ce4,8|Ô+4,8h4,8XÔ+4,8H;000130000007E00000000DA91F8CE1C1D1E1F7F1B044,-.Śš°­­.'"ÔŐŇÓÉÉFFFF0FFFF0FFFE000000060001001777AA˝ô˝ĹA338âČ&ŞţúV˝ňüžxY ( 4K Wc os x„žxY ˜authorAndy Fragen & Patrick Ritchie authorEmailandy@thefragens.com description„ homePageUrlnameMarkdown releaseDateversion0.83ţ›Verdana ˝ňü˝ňü'?ďŔLAND˙˙˙˙˙˙mac This script runs every hour. „›Verdana ˝ňű˝ňü'?ďŔLAND˙˙˙˙˙˙mac This script runs every minute. „œVerdana ˝ňü˝ňü'?ďŔLAND˙˙˙˙˙˙mac This script runs every night. „œ{w.˝ňű˝ňü  ". 9 everyHourpD everyMinutepë everyNightp”{ ˝ňü˝ňü ×N Arial ˝Łž%Y*YŃ]ĘLAND˙˙˙˙˙˙mac on editItem (adrPost, editText) Changes 10/27/04; 5:18:14 PM by AJF Had to rearrange the script a bit. It was returning 'true' instead of the text 25/10/04; 7:20:17 PM by PR created. reset the text on edit if MarkdownData.prefs.flRenderedNonrendered if defined (adrPost^.markdownData.preRenderText) editText = string (adrPost^.markdownData.preRenderText) return (string (adrPost^.markdownData.preRenderText)) return (editText) bundle // test dialog.alert (editItem (@weblogData.posts.["00000001"], "blah")) €„€€„€€€€„€„€×H]Arial ˝‘™?˝”ř%ÓęlŞLAND˙˙˙˙˙˙mac on postItem (adrPost) Changes 14/10/04; 11:25:37 AM by PR use a sub-table of the post so we don't interfere with future Radio data if MarkdownData.prefs.flRenderedNonrendered store markdown text in a seperate wp local (adrMarkdownData = @adrPost^.markdowndData) if !defined (adrMarkdownData^) // 14/10/04; 11:25:39 AM by PR init a table to store our data in the post new (tableType, adrMarkdownData) if defined (adrMarkdownData^.markdownText) delete (@adrMarkdownData^.markdownText) wp.newTextObject (MarkdownSuite.markdown (string (adrPost^.text)), @adrMarkdownData^.markdownText) €„€€€„€€€€€€œBâArial ˝‘™ƒ˝”ž+ˆ›ËLAND˙˙˙˙˙˙mac on publishItem (adrPost) Changes 14/10/04; 11:25:37 AM by PR use a sub-table of the post so we don't interfere with future Radio data if MarkdownData.prefs.flRenderedNonrendered swap in our markdown text for publishing local (adrMarkdownData = @adrPost^.markdowndData) if defined (adrMarkdownData^.markdownText) if !defined (adrMarkdownData^.backupText) adrMarkdownData^.backupText = adrPost^.text table.assign (@adrPost^.text, adrMarkdownData^.markdownText) €„€„€€€€€œS˝Verdana ˝ E˝Ą€!ă2qGLAND˙˙˙˙˙˙mac on render(itemtext) local (starticks = clock.ticks()) itemtext = MarkdownSuite.markdown (itemtext) MarkdownSuite.log (starticks, "Post item rendered from callback.") return (itemtext) €€€€€S?l[Verdana žLÓžU_ĘiirLAND˙˙˙˙˙˙mac on renderStory(adrpage, filetext) local (starticks = clock.ticks(), directivesText) on add(s) directivesText = directivesText + s + cr; itemtext = string(filetext) if not MarkdownData.prefs.flRenderedNonrendered while ((string.firstWord (itemtext)) beginsWith "#") add (string.nthField (itemtext, '\r', 1)) directiveLines = string.nthField (itemtext, '\r', 1) + "\r" itemtext = string.replace (itemtext, directiveLines, "") if not (string.firstWord (itemtext) beginsWith "<") //don't want to markup system pages itemtext = MarkdownSuite.markdown (itemtext) itemtext = directivesText + itemtext MarkdownSuite.log (starticks, "Story rendered from callback.") return (itemtext) bundle //test dialog.notify (renderStory (@system.temp, MarkdownSuite.testOutline)) dialog.notify (renderStory (@system.temp, MarkdownSuite.testStory)) €€€€€€€€€€€€€€€?Đ`řVerdana žLӞѲ‹’1%LAND˙˙˙˙˙˙mac on renderStory(adrpage, itemtext) on add(s) directivesText = directivesText + s + cr; if not MarkdownData.prefs.flRenderedNonrendered local (starticks = clock.ticks(), directivesText) while ((string.firstWord (itemtext)) beginsWith "#") add (string.nthField (itemtext, '\r', 1)) directiveLines = string.nthField (itemtext, '\r', 1) + "\r" itemtext = string.replace (itemtext, directiveLines, "") if not (string.firstWord (itemtext) beginsWith "<") //don't want to markup system pages itemtext = MarkdownSuite.markdown (itemtext) itemtext = directivesText + itemtext MarkdownSuite.log (starticks, "Story rendered from callback.") return (itemtext) bundle //test dialog.notify (renderStory (@system.temp, MarkdownSuite.testStory)) €€€€€€€€€€€€€€€Đ×ücArial ˝‘w˝”-ˆĘęLAND˙˙˙˙˙˙mac on upstream (filelist) Changes 14/10/04; 11:25:37 AM by PR use a sub-table of the post so we don't interfere with future Radio data if MarkdownData.prefs.flRenderedNonrendered restore our pre-Markdown text for all posts in the files that were just upstreamed local (posts = {}) local (adrWeblog = radio.weblog.init ()) local (adrPosts = @adrWeblog^.posts) for f in filelist // get our post list local (adrTable, x, flArchive, flHomepage) radio.file.getfileattributes (f, @adrtable) if defined (adrTable^.flArchivePage) flArchive = adrTable^.flArchivePage if defined (adrTable^.flHomePage) flHomepage = adrTable^.flHomePage if flArchive || flHomepage // we have a valid post page local (dtstart) if flArchive dtStart = adrtable^.archiveDate else dtStart = adrtable^.modified bundle // the following was written by Simon Fell in pingback.upstreamed if flArchive // dtStart isn't in standard date format its in yyyy/mm/dd, we need to convert it local ( yy = string.nthField ( dtStart, "/", 1 ), mm = string.nthField(dtStart, "/", 2), dd = string.nthField(dtStart,"/",3)) dtStart = date.set ( dd, mm, yy, 00, 00, 00 ) local (dtEnd = date.tomorrow (dtStart)) for x = sizeOf (adrPosts^) downto 1 // run through all the posts until their date is later than this archive date local (adrPost = @adrPosts^ [x]) if adrPost^.when < dtStart break; if adrPost^.when < dtEnd if !(posts contains x) posts[sizeOf(posts)+1] = x for post in posts local (adrPost = @adrPosts^.[string.padWithZeros(post, 8)]) local (adrMarkdownData = @adrPost^.markdowndData) if defined (adrMarkdownData^.backupText) table.assign (@adrPost^.text, adrMarkdownData^.backupText) delete (@adrMarkdownData^.backupText) upstream ({"C:\\Program Files\\Radio UserLand\\www\\index.txt"}) €„€€€„€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€„×2ŘL˝”!žQ$  !- 4@ LX gs |postItem0 Ň publishItem0űrender0Ł renderStory0renderStoryOld0Mupstream0)VVerdana Ź„2@8ÖČ2p~z Arial ˝‘™?˝˘řM@0šęLAND˙˙˙˙˙˙mac on postItem (adrPost) Changes 10/25/04; 6:34:24 PM by AJF Added log handling to this script 25/10/04; 7:18:57 PM by PR sets us up to use the new edtItem callback 14/10/04; 11:25:37 AM by PR use a sub-table of the post so we don't interfere with future Radio data if MarkdownData.prefs.flRenderedNonrendered local (starticks = clock.ticks()) store pre-rendered text local (adrMarkdownData = @adrPost^.markdownData) if !defined (adrMarkdownData^) // 14/10/04; 11:25:39 AM by PR init a table to store our data in the post new (tableType, adrMarkdownData) local (text = adrPost^.text) table.assign (@adrMarkdownData^.preRenderText, text) delete (@adrPost^.text) wp.newTextObject (MarkdownSuite.markdown (string (text)), @adrPost^.text) MarkdownSuite.log(starticks, "Markdown rendering on Windows") bundle // text postItem (@weblogData.posts.["00000001"]) €„€€€€€€€€„€€€€€€€€„€p›$˙Verdana ˝ E˝˘Řˇ*œ8*MLAND˙˙˙˙˙˙mac on renderItem(adrpost, itemtext) if not MarkdownData.prefs.flRenderedNonrendered local (starticks = clock.ticks()) itemtext = MarkdownSuite.markdown (itemtext) MarkdownSuite.log (starticks, "Post item rendered from callback.") return (itemtext) €€€€€€›ZrpVerdana žLÓž6rÂ`ÍŐLAND˙˙˙˙˙˙mac on renderStory(filetext) local (starticks = clock.ticks(), directives = "", directiveLine) itemtext = string(filetext^) on add (s) directives = directives + s + "\r"; if not MarkdownData.prefs.flRenderedNonrendered while ((string.firstWord (itemtext)) beginsWith "#") add (string.nthField (itemtext, '\r', 1)) directiveLine = string.nthField (itemtext, '\r', 1) + "\r" itemtext = string.replace (itemtext, directiveLine, "") if not (string.firstWord (itemtext) beginsWith "<") //don't want to markup system pages itemtext = MarkdownSuite.markdown (itemtext) itemtext = directives + itemtext; MarkdownSuite.log (starticks, "Story rendered from callback.") table.assign (filetext, itemtext) return (filetext^) bundle //destructivetest dialog.notify (renderStory (@ MarkdownSuite.testOutline)) dialog.notify (renderStory (@MarkdownSuite.testStory)) €€€€€€€€€€€€€€€€„€Zź¸B˝ňüžŐ6  ". 7C NZ feditItemPď oldCallbacksP$ postItemP%J renderItemP)Ć renderStoryP+mź”$řVerdana ˝ EžP4 +LAND˙˙˙˙˙˙mac on renderNode(itemtext) if not MarkdownData.prefs.flRenderedNonrendered local (starticks = clock.ticks()) itemtext^ = MarkdownSuite.markdown (itemtext^) MarkdownSuite.log (starticks, "Post node rendered from callback.") return (itemtext) €€€€€€”W–IGeneva ž îž[Ř:mLAND˙˙˙˙˙˙mac on renderOpml (opml) local (directives = "", ol = @temp.ol) op.xmlToOutline (opml^, ol) bundle //strip directives for processing, add back later target.set (ol) op.firstSummit() while op.getLineText() beginsWith "#" directives = directives + op.getLineText() + "\r" op.deleteLine() myOpml = string (ol^) bundle//convert tabs to something prior to markdown myOpml = string.replaceAll (myOpml, "\t[","[") myOpml = string.replaceAll (myOpml, "\t", "[tab]") myOpml = MarkdownSuite.markdown (myOpml) myOpml = string.replaceAll (myOpml, "[tab]", "\t") //convert tabs back myOpml = string.replace (myOpml, "

", "") myOpml = string.replace (myOpml, "

", "") myOpml = directives + myOpml bundle //hocus-pocus so Radio converts string to outline without crashing wp.newTextObject(myOpml, @temp.activeRenderer.aRwP) table.assign(@temp.activeRenderer.aRstring, string (temp.activeRenderer.aRwP)) op.newOutlineObject (temp.activeRenderer.aRstring, @temp.activeRenderer.outline) table.assign (ol, temp.activeRenderer.outline) opml^ = op.outlineToXml (ol) return (opml) €€€€€€€€€€€€€€€€€€€€€W°V$žđžOö  " renderNode00› renderOpml02;VGeneva ʁ5@8ÖȰ=9˝ňüž activeRendererP7ž=wf™ Verdana ˝rpžő¨,útO˜LAND˙˙˙˙˙˙mac on rssFilterDescription (itemtext, adrPost) local (starticks = clock.ticks()) if MarkdownData.prefs.flRenderedNonrendered replace the description with our markdown version if defined (adrPost^.markdownText) itemtext = string (adrPost^.markdownText) else itemtext = (MarkdownSuite.markdown (itemtext)) MarkdownSuite.log(starticks, "Rendering RSS") return (itemtext) bundle //test local (s, starticks = clock.ticks()) s = "1. test\r2. test\r3. test\r\rparagraph\r\r\"quoted\"" s = rssFilterDescription (s, @temp.unixShellcommand) MarkdownSuite.log(starticks, "Test RSS") wp.newTextObject (s, @temp.unixShellCommand) edit (@temp.unixShellCommand) €€€„€€€€€€€w™?˝‘ˇŃ˝‘ˇŰ rssFilterDescriptionP8ŁVVerdana Ź„2@8Öș‹8˝ňü˝ŚW~  ' ,8 CfileMenupĂradiop/Óuserp8Z weblogDatap<& gP Ÿ%Verdana ˝ó1ž!Näú%LAND˙˙˙˙˙˙mac #renderOutlineWith "pikerenderer" #pikeRendererDriver "html" 20 Changes Version: <%MarkdownInfo.version%> This is a quick proof of concept tool. You must be using Mac OS X or Windows with ActivePerl to make it work. You will also have to download your own copy of Markdown to use if you are using OS X. Does not write a file. Uses the command line command. % echo "string to process" | perl Markdown.pl Lots of thanks and work by Patrick Ritchie. He did all the Windows stuff as well as his method. 10/12/04; 9:08:33 PM by AJF I updated the init script to copy a callback to weblogData.callbacks.rssFilterDescription. I would still like this to be done automatically if I have a callback table named weblogData and put a script named rssFilterDescription in it. 10/12/04; 10:56:26 PM by AJF Updated markdown script to incorporate Patrick Ritchie's Windows stuff Added Patrick's scripts. Added flag to use my method or Patrick's method. Added Menu item "Store Rendered & Non-Rendered" if checked this will use Patrick's callbacks. My method doesn't change anything in weblogData.root. All rendering gets intercepted by a callback for RSS rendering and a single item entry in radio.weblog.render. Hopefully a callback will be created here. Patrick's method creates a markdownText entry in each weblogData.post entry returning either the rendered or unrendered version as appropriate. 10/13/04; 10:28:50 AM by PR Instructions for ActivePerl. 1. Go here: http://www.activestate.com/Products/ActivePerl/ 2. Download the MSI package 3. Run the installer 4. That's it! 10/14/04; 12:00:13 PM by PR Updated callbacks from Patrick 10/14/04; 3:28:57 PM by AJF Added callback running to radio.weblog.render and now run Markdown from callbacks. To use, you need to get special version of radio.weblog.render in gems folder. Added Event logging. 10/15/04; 3:32:26 PM by AJF Created new userDocs and renamed this outline to changes. 10/24/04; 4:40:41 PM by AJF Updated renderItem callback for Patrick's new callback to radio.weblog.render 10/25/04; 6:44:02 PM by AJF Installed Patrick's updated scripts for new callbacks. 11/22/04; 3:32:38 PM by AJF Wrapped some of init in try block while waiting for root update to add the specific callback. Wrapped the markdown script in try block as error in Markdown markup would make all items not marked up. 12/23/04; 10:16:40 AM by AJF Added Markdown 1.0.1 to perlScript 01/04/05; 7:28:55 PM by AJF Added support for markup of stories Needs callback in radio.webServer.buildPage 01/08/05; 9:50:45 PM by AJF Fixed init. 01/10/05; 7:10:43 PM by AJF Added a bundle before doing Markdown to escape certain markup, initially (`) back-tick. 01/18/05; 8:24:19 PM by AF Made callbacks to work with activeRender, still in testing mode. €€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€ gŕ<,Arial ˝“š˝”I ŻĘMÁLAND˙˙˙˙˙˙mac on cleanup () 13/10/04; 5:32:50 PM by PR cleans up the posts table on uninstall local (adrWeblog = radio.weblog.init ()) for adrPost in @adrWeblog^.posts local (adrMarkdownData = @adrPost^.markdowndData) if defined (adrMarkdownData^) delete (@adrMarkdownData) bundle //test cleanup () €„€€€€€€€€ŕ~‰ Verdana ˝†íž: '?OőLAND˙˙˙˙˙˙mac Changes Created from installCodeFreshener script by AJF on 10/11/2004; 6:52:29 PM. 9/26/02; 12:23:22 AM by AJF Add new tool tables. 1/15/02; 5:21:20 PM by DW Runs on the user's machine, when refreshing. local (adrtable = @system.temp.MarkdownSnapshot) MarkdownData = adrtable^.data MarkdownInfo = adrtable^.info MarkdownSuite = adrtable^.suite MarkdownThread = adrtable^.thread MarkdownWebsite = adrtable^.website filemenu.savemyroot (@MarkdownSuite) local (x=string.parseAddress (@MarkdownSuite), f = x[1]) frontier.tools.install (f) dialog.notify ("Thanks for updating to version " + MarkdownInfo.version + " of Markdown.root Tool!") „€€€€€€€€€€€€€€€€€€€€ĆN Verdana ˝†î˝†ď'?ďŔLAND˙˙˙˙˙˙mac Changes Created from installCodeFreshener script by AJF on 10/11/2004; 6:52:31 PM. 1/15/02; 5:18:06 PM by DW This is the Refresh menu command. local (url = "http://radio.weblogs.com/0001017/publicTools/Markdown/codeFreshener.fttb") local (urllist = string.urlsplit (url)) local (s = tcp.httpclient (server:urllist [2], path:urllist [3])) local (f=frontier.pathstring + "codeFreshener.fttb") file.writewholefile (f, s) fatpages.importfatfile (f) thread.callscript (@system.temp.MarkdownSnapshot.loader, {}) „€€€€€€€€€€€€Ćń mVerdana ˝†đ˝†đ'?ďŔLAND˙˙˙˙˙˙mac if dialog.confirm ("Get the newest code for Markdown.root Tool?") MarkdownSuite.codeFreshener.refreshCode() €€ńÝĚ™!Verdana  ˝†đ˝†ň'?LčLAND˙˙˙˙˙˙mac Changes Created from installCodeFreshener script by AJF on 10/11/2004; 6:52:33 PM. 1/15/02; 5:08:55 PM by DW Created. I run this on my machine to create a package for refreshCode to load. Talk about a Mobius Strip. It's really simple code, but it's fun to walk your mind through it. local (oldMarkdownData) bundle //get MarkdownData ready for ship oldMarkdownData = MarkdownData new (tabletype, @MarkdownData) MarkdownThread.enabled = true MarkdownThread.ct = 0 MarkdownInfo.releaseDate = clock.now() local (adrtable = @system.temp.MarkdownSnapshot) new (tabletype, adrtable) adrtable^.data = MarkdownData adrtable^.info = MarkdownInfo adrtable^.suite = MarkdownSuite adrtable^.thread = MarkdownThread adrtable^.website = MarkdownWebsite adrtable^.loader = MarkdownSuite.codeFreshener.loadNewCode local (f = radio.file.getSubFolder ("publicTools/Markdown") + "codeFreshener.fttb") file.surefilepath (f) export.sendobject (adrtable, f) f = radio.file.getSubFolder ("publicTools/Markdown") + "Markdown.root" target.set (this) fileMenu.saveCopy (f) MarkdownData = oldMarkdownData dialog.alert (file.filefrompath (f) + " is " + string.megabytestring (file.size (f))) „€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€ݧŁ8˝†í˝†đ  $0 @L [ loadNewCodepLĹ refreshCodepPPrefreshCodeMenupS"releaseNewCodepT§ ěü xVerdana ˝öëžPSŤÍň›ALAND˙˙˙˙˙˙mac local (adrWeblog = radio.weblog.init()) local (mdPl, mdPath, homePath) if not defined (MarkdownData.prefs) new (tabletype, @MarkdownData.prefs) if system.environment.isMac if defined (system.environment.isCarbon) and system.environment.isCarbon if not defined (MarkdownData.prefs.mdPl) file.getFolderDialog("Select your OS X Home folder.", @MarkdownData.prefs.homePath) bundle //get path to Markdown.pl file.getFolderDialog("Please locate the folder containing 'Markdown.pl'.", @MarkdownData.prefs.mdPath) mdPath = MarkdownData.prefs.mdPath mdPath = string.replace(mdPath, MarkdownData.prefs.homePath, "~:") mdPath = MarkdownSuite.makeUnixPath(mdPath) MarkdownData.prefs.mdPath = mdPath bundle //get current name of Markdown.pl, not needed if file named 'Markdown.pl' file.getFileDialog("Please locate the 'Markdown.pl' file.", @MarkdownData.prefs.mdPl, 0) mdPl = file.fileFromPath(MarkdownData.prefs.mdPl) mdPl = MarkdownSuite.makeUnixPath (mdPl) MarkdownData.prefs.mdPl = mdPl if not defined (MarkdownData.prefs.flRenderedNonrendered) MarkdownData.prefs.flRenderedNonrendered = false if not defined (MarkdownData.prefs.flLog) MarkdownData.prefs.flLog = false if not defined (MarkdownData.prefs.flMarkdown) MarkdownData.prefs.flMarkdown = true bundle //radio.init stuff if not defined (user.radio.callbacks.renderItem) new (tabletype, @user.radio.callbacks.renderItem) if not defined (user.radio.callbacks.renderStory) new (tabletype, @user.radio.callbacks.renderStory) if not defined (user.radio.callbacks.editItem) new (tabletype, @user.radio.callbacks.editItem) bundle//init callbacks adrWeblog^.callbacks.rssFilterDescription.Markdown = @MarkdownSuite.callbacks.weblogData.rssFilterDescription user.radio.callbacks.renderItem.markdown = @MarkdownSuite.callbacks.radio.renderItem user.radio.callbacks.renderStory.markdown = @MarkdownSuite.callbacks.radio.renderStory user.radio.callbacks.postItem.markdown = @MarkdownSuite.callbacks.radio.postItem user.radio.callbacks.editItem.markdown = @MarkdownSuite.callbacks.radio.editItem bundle//init activeRenderer callbacks if defined (user.activeRenderer.callbacks) user.activeRenderer.callbacks.renderOpml.processNode.markdown = @MarkdownSuite.callbacks.user.activeRenderer.renderNode user.activeRenderer.callbacks.renderOpml.preProcess.markdown = @MarkdownSuite.callbacks.user.activeRenderer.renderOpml €€€€€€€€€€€€€€€€€€€„€ ěřnVerdana ˝”/O˝”0cm< őLAND˙˙˙˙˙˙mac on log(starticks, logMessage) if MarkdownData.prefs.flLog radio.log.add("Markdown", logMessage, starticks) €€€ř{Verdana ˝2ü˝3'?ďŔLAND˙˙˙˙˙˙mac on makeUnixPath(s) s = string (s) s = string.replaceAll (s, ":", "/") s = string.replaceAll (s, " ", "\\ ") return (s) €€€€€ Verdana ˝ô‡žw'ů8"É‹LAND˙˙˙˙˙˙mac on markdown(posttext) Changes 01/10/05; 11:45:15 PM by AJF Added bundle to escape special characters 10/25/04; 6:33:09 PM by AJF Incorporated Patrick's new changes. Moved his log handling to callback script. if MarkdownData.prefs.flMarkdown local (starticks = clock.ticks()) bundle //escape some special characters posttext = string.replaceAll (posttext, "\\", "\\\\") //escape backslash posttext = string.replaceAll (posttext, "`", "\\`") //escape backtick posttext = string.replaceAll ( posttext, "\"", "\\\"") //escape double quotes if system.environment.isMac if defined (system.environment.isCarbon) and system.environment.isCarbon bundle //old code for creating temp file with posttext local (f, fPath) fPath = file.getPath () f = fPath + "preMarkdown.text" Make posttext into temp file at f file.writeTextFile (f, posttext, lineEnding:"unix", characterSet:"utf-8") f = string.replace(f, MarkdownData.prefs.homePath, "~:") f = MarkdownSuite.makeUnixPath(f) posttext = string.replaceAll (posttext, "$", "\\$") //workaround bug in OS X shell markdownCmdLine = "cd " + MarkdownData.prefs.mdPath + ";echo \"" + posttext + "\" | perl " + MarkdownData.prefs.mdPl try {posttext = sys.unixShellCommand(markdownCmdLine)} return (posttext) else return ("You need to be running Macintosh OS X for Markdown.root to run.") if system.environment.isWindows try local (newText = com.callscript (string (MarkdownSuite.perlScript), "PerlScript", "Markdown", {posttext})) return (newText) else return (postText) else return (posttext) bundle //test local (s, starticks = clock.ticks()) s = "1. test\r2. test\r3. test\r\rparagraph\r\r\"quoted\"\r\r`<%radio.macros.weblogUrl()%>`\rbackslash ( \\ )" s = markdown (s) MarkdownSuite.log(starticks, "Test") wp.newTextObject (s, @temp.unixShellCommand) edit (@temp.unixShellCommand) €„€€€€€„€€€€€€€€€€ ˝?Verdana žťŃžź:'?ďŔLAND˙˙˙˙˙˙mac MarkdownData.prefs.flMarkdown = !MarkdownData.prefs.flMarkdown €˝ÓUVerdana T˝’1˝’J'?ďŔLAND˙˙˙˙˙˙mac MarkdownData.prefs.flRenderedNonrendered = !MarkdownData.prefs.flRenderedNonrendered €Ół5Verdana ˝’1˝”#A'?ďŔLAND˙˙˙˙˙˙mac MarkdownData.prefs.flLog = !MarkdownData.prefs.flLog €łÔVVerdana ˝†ň˝†ň'?ďŔLAND˙˙˙˙˙˙mac if dialog.confirm ("Get the newest code?"){MarkdownSuite.codeFreshener.refreshCode()} €ÔäF&Verdana ˝ňüžźSž'?ďŔLAND˙˙˙˙˙˙mac Markdown =MarkdownSuite.menuCheckText("Render with Markdown", MarkdownData.prefs.flMarkdown) =MarkdownSuite.menuCheckText("Store Rendered & Non-Rendered Text", MarkdownData.prefs.flRenderedNonrendered) =MarkdownSuite.menuCheckText("Event logging", MarkdownData.prefs.flLog) Refresh Code... €€ pę€ qł€ r’€ sQäpt1GZť§Verdana ƒBdŽpÎ>Arial ¸ŐB¸ŐB&§1iŹLAND˙˙˙˙˙˙mac on menuCheckText (s, pref) if pref s = "!" + s return (s) €€€€Î’ŢFFFF000000060001001777AA000000000077000000001001710000001-76FB6FBE1800000‚‚480048063E5F200-1‚394139410Â6‚3E5F222FFFF0‚‚10‚‚3‚8B260000100000269000000090C1A40840‚‚6‚570222BDD02C8000565245701260C1A19A340840‚‚5706B1C222D7002C8000B1112B1C7A019A3280740840‚‚B1C610E9222E5E02C800010DE3610E94D02807370840840‚‚10E9617B3222EE002C800017A8FC17B317E03708466F40840‚‚17B361FC7222F5B02C80001FBC241FC75E0466F561640840‚‚1FC762594222F6702C800025891225941360561665D440840‚‚259462D5B222FA102C80002D50A22D5B112065D473E440840‚‚2D5B63451222DFF02C8000344612345156073E48B2640840‚‚345163E5F2221742028E0003E5463E5F60000200000C2000000000C1A,#!/usr/bin/perl # # Markdown -- A text-to-HTML conversion tool for web writers # # Copyright (c) 2004 John Gruber # # package Markdown; require 5.006_000; use strict; use warnings; use Digest::MD5 qw(md5_hex); use vars qw($VERSION); $VERSION = '1.0.1'; # Tue 14 Dec 2004 ## Disabled; causes problems under Perl 5.6.1: # use utf8; # binmode( STDOUT, ":utf8" ); # c.f.: http://acis.openlib.org/dev/perl-unicode-struggle.html # # Global default settings: # my $g_empty_element_suffix = " />"; # Change to ">" for HTML output my $g_tab_width = 4; # # Globals: # # Regex to match balanced [brackets]. See Friedl's # "Mastering Regular Expressions", 2nd Ed., pp. 328-331. my $g_nested_brackets; $g_nested_brackets = qr{ (?> # Atomic matching [^\[\]]+ # Anything other than brackets | \[ (??{ $g_nested_brackets }) # Recursive set of nested brackets \] )* }x; # Table of hash values for escaped characters: my %g_escape_table; foreach my $char (split //, '\\`*_{}[]()>#+-.!') { $g_escape_table{$char} = md5_hex($char); } # Global hashes, used by various utility routines my %g_urls; my %g_titles; my %g_html_blocks; # Used to track when we're inside an ordered or unordered list # (see _ProcessListItems() for details): my $g_list_level = 0; #### Blosxom plug-in interface ########################################## # Set $g_blosxom_use_meta to 1 to use Blosxom's meta plug-in to determine # which posts Markdown should process, using a "meta-markup: markdown" # header. If it's set to 0 (the default), Markdown will process all # entries. my $g_blosxom_use_meta = 0; sub start { 1; } sub story { my($pkg, $path, $filename, $story_ref, $title_ref, $body_ref) = @_; if ( (! $g_blosxom_use_meta) or (defined($meta::markup) and ($meta::markup =~ /^\s*markdown\s*$/i)) ){ $$body_ref = Markdown($$body_ref); } 1; } #### Movable Type plug-in interface ##################################### eval {require MT}; # Test to see if we're running in MT. unless ($@) { require MT; import MT; require MT::Template::Context; import MT::Template::Context; eval {require MT::Plugin}; # Test to see if we're running >= MT 3.0. unless ($@) { require MT::Plugin; import MT::Plugin; my $plugin = new MT::Plugin({ name => "Markdown", description => "A plain-text-to-HTML formatting plugin. (Version: $VERSION)", doc_link => 'http://daringfireball.net/projects/markdown/' }); MT->add_plugin( $plugin ); } MT::Template::Context->add_container_tag(MarkdownOptions => sub { my $ctx = shift; my $args = shift; my $builder = $ctx->stash('builder'); my $tokens = $ctx->stash('tokens'); if (defined ($args->{'output'}) ) { $ctx->stash('markdown_output', lc $args->{'output'}); } defined (my $str = $builder->build($ctx, $tokens) ) or return $ctx->error($builder->errstr); $str; # return value }); MT->add_text_filter('markdown' => { label => 'Markdown', docs => 'http://daringfireball.net/projects/markdown/', 000200000D8F00000C1AD89, on_format => sub { my $text = shift; my $ctx = shift; my $raw = 0; if (defined $ctx) { my $output = $ctx->stash('markdown_output'); if (defined $output && $output =~ m/^html/i) { $g_empty_element_suffix = ">"; $ctx->stash('markdown_output', ''); } elsif (defined $output && $output eq 'raw') { $raw = 1; $ctx->stash('markdown_output', ''); } else { $raw = 0; $g_empty_element_suffix = " />"; } } $text = $raw ? $text : Markdown($text); $text; }, }); # If SmartyPants is loaded, add a combo Markdown/SmartyPants text filter: my $smartypants; { no warnings "once"; $smartypants = $MT::Template::Context::Global_filters{'smarty_pants'}; } if ($smartypants) { MT->add_text_filter('markdown_with_smartypants' => { label => 'Markdown With SmartyPants', docs => 'http://daringfireball.net/projects/markdown/', on_format => sub { my $text = shift; my $ctx = shift; if (defined $ctx) { my $output = $ctx->stash('markdown_output'); if (defined $output && $output eq 'html') { $g_empty_element_suffix = ">"; } else { $g_empty_element_suffix = " />"; } } $text = Markdown($text); $text = $smartypants->($text, '1'); }, }); } } else { #### BBEdit/command-line text filter interface ########################## # Needs to be hidden from MT (and Blosxom when running in static mode). # We're only using $blosxom::version once; tell Perl not to warn us: no warnings 'once'; unless ( defined($blosxom::version) ) { use warnings; #### Check for command-line switches: ################# my %cli_opts; use Getopt::Long; Getopt::Long::Configure('pass_through'); GetOptions(\%cli_opts, 'version', 'shortversion', 'html4tags', ); if ($cli_opts{'version'}) { # Version info print "\nThis is Markdown, version $VERSION.\n"; print "Copyright 2004 John Gruber\n"; print "http://daringfireball.net/projects/markdown/\n\n"; exit 0; } if ($cli_opts{'shortversion'}) { # Just the version number string. print $VERSION; exit 0; } if ($cli_opts{'html4tags'}) { # Use HTML tag style instead of XHTML $g_empty_element_suffix = ">"; } #### Process incoming text: ########################### my $text; { local $/; # Slurp the whole file $text = <>; } print Markdown($text); } } sub Markdown { # # Main function. The order in which other subs are called here is # essential. Link and image substitutions need to happen before # _EscapeSpecialChars(), so that any *'s or _'s in the # and tags get encoded. # my $text = shift; # Clear the global hashes. If we don't clear these, you get conflicts # from other articles when generating a page which contains more than # one article (e.g. an index page that shows the N most recent # articles): %g_urls = (); %g_titles = (); %g_html_blocks = (); # Standardize line endings: $text =~ s{\r\n}{\n}g; # DOS to Unix $text =~ s{\r}{\n}g; # Mac to Unix # Make sure $text ends with a couple of newlines: $text .= "\n\n"; # Convert all tabs to spaces. $text = _Detab($text); # Strip any lines consisting only of spaces and tabs. # This makes subsequent regexen easier to write, because we can # match consecutive blank lines with /\n+/ instead of something # contorted like /[ \t]*\n+/ . $text =~ s/^[ \t]+$//mg; 000200000E6A000019A3E64, # Turn block-level HTML blocks into hash entries $text = _HashHTMLBlocks($text); # Strip link definitions, store in hashes. $text = _StripLinkDefinitions($text); $text = _RunBlockGamut($text); $text = _UnescapeSpecialChars($text); return $text . "\n"; } sub _StripLinkDefinitions { # # Strips link definitions from text, stores the URLs and titles in # hash references. # my $text = shift; my $less_than_tab = $g_tab_width - 1; # Link defs are in the form: ^[id]: url "optional title" while ($text =~ s{ ^[ ]{0,$less_than_tab}\[(.+)\]: # id = $1 [ \t]* \n? # maybe *one* newline [ \t]* ? # url = $2 [ \t]* \n? # maybe one newline [ \t]* (?: (?<=\s) # lookbehind for whitespace ["(] (.+?) # title = $3 [")] [ \t]* )? # title is optional (?:\n+|\Z) } {}mx) { $g_urls{lc $1} = _EncodeAmpsAndAngles( $2 ); # Link IDs are case-insensitive if ($3) { $g_titles{lc $1} = $3; $g_titles{lc $1} =~ s/"/"/g; } } return $text; } sub _HashHTMLBlocks { my $text = shift; my $less_than_tab = $g_tab_width - 1; # Hashify HTML blocks: # We only want to do this for block-level HTML tags, such as headers, # lists, and tables. That's because we still want to wrap

s around # "paragraphs" that are wrapped in non-block-level tags, such as anchors, # phrase emphasis, and spans. The list of tags we're looking for is # hard-coded: my $block_tags_a = qr/p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math|ins|del/; my $block_tags_b = qr/p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math/; # First, look for nested blocks, e.g.: #

#
# tags for inner block must be indented. #
#
# # The outermost tags must start at the left margin for this to match, and # the inner nested divs must be indented. # We need to do this before the next, more liberal match, because the next # match will start at the first `
` and stop at the first `
`. $text =~ s{ ( # save in $1 ^ # start of line (with /m) <($block_tags_a) # start tag = $2 \b # word break (.*\n)*? # any number of lines, minimally matching # the matching end tag [ \t]* # trailing spaces/tabs (?=\n+|\Z) # followed by a newline or end of document ) }{ my $key = md5_hex($1); $g_html_blocks{$key} = $1; "\n\n" . $key . "\n\n"; }egmx; # # Now match more liberally, simply from `\n` to `\n` # $text =~ s{ ( # save in $1 ^ # start of line (with /m) <($block_tags_b) # start tag = $2 \b # word break (.*\n)*? # any number of lines, minimally matching .* # the matching end tag [ \t]* # trailing spaces/tabs (?=\n+|\Z) # followed by a newline or end of document ) }{ my $key = md5_hex($1); $g_html_blocks{$key} = $1; "\n\n" . $key . "\n\n"; }egmx; # Special case just for
. It was easier to make a special case than # to make the other regex more complicated. $text =~ s{ (?: (?<=\n\n) # Starting after a blank line | # or \A\n? # the beginning of the doc ) ( # save in $1 [ ]{0,$less_than_tab} <(hr) # start tag = $2 \b # word break ([^<>])*? # /?> # the matching end tag [ \t]* (?=\n{2,}|\Z) # followed by a blank line or end of document ) }{ my $key = md5_hex($1); $g_html_blocks{$key} = $1; "\n\n" . $key . "\n\n"; }egx; 000200000F0700002807F01, # Special case for standalone HTML comments: $text =~ s{ (?: (?<=\n\n) # Starting after a blank line | # or \A\n? # the beginning of the doc ) ( # save in $1 [ ]{0,$less_than_tab} (?s: ) [ \t]* (?=\n{2,}|\Z) # followed by a blank line or end of document ) }{ my $key = md5_hex($1); $g_html_blocks{$key} = $1; "\n\n" . $key . "\n\n"; }egx; return $text; } sub _RunBlockGamut { # # These are all the transformations that form block-level # tags like paragraphs, headers, and list items. # my $text = shift; $text = _DoHeaders($text); # Do Horizontal Rules: $text =~ s{^[ ]{0,2}([ ]?\*[ ]?){3,}[ \t]*$}{\n tags around block-level tags. $text = _HashHTMLBlocks($text); $text = _FormParagraphs($text); return $text; } sub _RunSpanGamut { # # These are all the transformations that occur *within* block-level # tags like paragraphs, headers, and list items. # my $text = shift; $text = _DoCodeSpans($text); $text = _EscapeSpecialChars($text); # Process anchor and image tags. Images must come first, # because ![foo][f] looks like an anchor. $text = _DoImages($text); $text = _DoAnchors($text); # Make links out of things like `` # Must come after _DoAnchors(), because you can use < and > # delimiters in inline links like [this](). $text = _DoAutoLinks($text); $text = _EncodeAmpsAndAngles($text); $text = _DoItalicsAndBold($text); # Do hard breaks: $text =~ s/ {2,}\n/ or tags. # my $tags_to_skip = qr!<(/?)(?:pre|code|kbd|script|math)[\s>]!; foreach my $cur_token (@$tokens) { if ($cur_token->[0] eq "tag") { # Within tags, encode * and _ so they don't conflict # with their use in Markdown for italics and strong. # We're replacing each such character with its # corresponding MD5 checksum value; this is likely # overkill, but it should prevent us from colliding # with the escape values by accident. $cur_token->[1] =~ s! \* !$g_escape_table{'*'}!gx; $cur_token->[1] =~ s! _ !$g_escape_table{'_'}!gx; $text .= $cur_token->[1]; } else { my $t = $cur_token->[1]; $t = _EncodeBackslashEscapes($t); $text .= $t; } } return $text; } sub _DoAnchors { # # Turn Markdown link shortcuts into XHTML
tags. # my $text = shift; # # First, handle reference-style links: [link text] [id] # $text =~ s{ ( # wrap whole match in $1 \[ ($g_nested_brackets) # link text = $2 \] [ ]? # one optional space (?:\n[ ]*)? # one optional newline followed by spaces \[ (.*?) # id = $3 \] ) }{ my $result; my $whole_match = $1; my $link_text = $2; my $link_id = lc $3; if ($link_id eq "") { $link_id = lc $link_text; # for shortcut links like [this][]. } if (defined $g_urls{$link_id}) { my $url = $g_urls{$link_id}; $url =~ s! \* !$g_escape_table{'*'}!gx; # We've got to encode these to avoid $url =~ s! _ !$g_escape_table{'_'}!gx; # conflicting with italics/bold. 000200000F6D00003708F67, $result = "? # href = $3 [ \t]* ( # $4 (['"]) # quote char = $5 (.*?) # Title = $6 \5 # matching quote )? # title is optional \) ) }{ my $result; my $whole_match = $1; my $link_text = $2; my $url = $3; my $title = $6; $url =~ s! \* !$g_escape_table{'*'}!gx; # We've got to encode these to avoid $url =~ s! _ !$g_escape_table{'_'}!gx; # conflicting with italics/bold. $result = " tags. # my $text = shift; # # First, handle reference-style labeled images: ![alt text][id] # $text =~ s{ ( # wrap whole match in $1 !\[ (.*?) # alt text = $2 \] [ ]? # one optional space (?:\n[ ]*)? # one optional newline followed by spaces \[ (.*?) # id = $3 \] ) }{ my $result; my $whole_match = $1; my $alt_text = $2; my $link_id = lc $3; if ($link_id eq "") { $link_id = lc $alt_text; # for shortcut links like ![this][]. } $alt_text =~ s/"/"/g; if (defined $g_urls{$link_id}) { my $url = $g_urls{$link_id}; $url =~ s! \* !$g_escape_table{'*'}!gx; # We've got to encode these to avoid $url =~ s! _ !$g_escape_table{'_'}!gx; # conflicting with italics/bold. $result = "\"$alt_text\"";? # src url = $3 [ \t]* ( # $4 (['"]) # quote char = $5 (.*?) # title = $6 \5 # matching quote [ \t]* )? # title is optional \) ) }{ my $result; my $whole_match = $1; my $alt_text = $2; my $url = $3; my $title = ''; if (defined($6)) { $title = $6; } $alt_text =~ s/"/"/g; $title =~ s/"/"/g; $url =~ s! \* !$g_escape_table{'*'}!gx; # We've got to encode these to avoid $url =~ s! _ !$g_escape_table{'_'}!gx; # conflicting with italics/bold. $result = "\"$alt_text\"";" . _RunSpanGamut($1) . "\n\n"; }egmx; $text =~ s{ ^(.+)[ \t]*\n-+[ \t]*\n+ }{ "

" . _RunSpanGamut($1) . "

\n\n"; }egmx; # atx-style headers: # # Header 1 # ## Header 2 000200000FAD0000466FFA7, # ## Header 2 with closing hashes ## # ... # ###### Header 6 # $text =~ s{ ^(\#{1,6}) # $1 = string of #'s [ \t]* (.+?) # $2 = Header text [ \t]* \#* # optional closing #'s (not counted) \n+ }{ my $h_level = length($1); "" . _RunSpanGamut($2) . "\n\n"; }egmx; return $text; } sub _DoLists { # # Form HTML ordered (numbered) and unordered (bulleted) lists. # my $text = shift; my $less_than_tab = $g_tab_width - 1; # Re-usable patterns to match list item bullets and number markers: my $marker_ul = qr/[*+-]/; my $marker_ol = qr/\d+[.]/; my $marker_any = qr/(?:$marker_ul|$marker_ol)/; # Re-usable pattern to match any entirel ul or ol list: my $whole_list = qr{ ( # $1 = whole list ( # $2 [ ]{0,$less_than_tab} (${marker_any}) # $3 = first list item marker [ \t]+ ) (?s:.+?) ( # $4 \z | \n{2,} (?=\S) (?! # Negative lookahead for another list item marker [ \t]* ${marker_any}[ \t]+ ) ) ) }mx; # We use a different prefix before nested lists than top-level lists. # See extended comment in _ProcessListItems(). # # Note: There's a bit of duplication here. My original implementation # created a scalar regex pattern as the conditional result of the test on # $g_list_level, and then only ran the $text =~ s{...}{...}egmx # substitution once, using the scalar as the pattern. This worked, # everywhere except when running under MT on my hosting account at Pair # Networks. There, this caused all rebuilds to be killed by the reaper (or # perhaps they crashed, but that seems incredibly unlikely given that the # same script on the same server ran fine *except* under MT. I've spent # more time trying to figure out why this is happening than I'd like to # admit. My only guess, backed up by the fact that this workaround works, # is that Perl optimizes the substition when it can figure out that the # pattern will never change, and when this optimization isn't on, we run # afoul of the reaper. Thus, the slightly redundant code to that uses two # static s/// patterns rather than one conditional pattern. if ($g_list_level) { $text =~ s{ ^ $whole_list }{ my $list = $1; my $list_type = ($3 =~ m/$marker_ul/) ? "ul" : "ol"; # Turn double returns into triple returns, so that we can make a # paragraph for the last item in a list, if necessary: $list =~ s/\n{2,}/\n\n\n/g; my $result = _ProcessListItems($list, $marker_any); $result = "<$list_type>\n" . $result . "\n"; $result; }egmx; } else { $text =~ s{ (?:(?<=\n\n)|\A\n?) $whole_list }{ my $list = $1; my $list_type = ($3 =~ m/$marker_ul/) ? "ul" : "ol"; # Turn double returns into triple returns, so that we can make a # paragraph for the last item in a list, if necessary: $list =~ s/\n{2,}/\n\n\n/g; my $result = _ProcessListItems($list, $marker_any); $result = "<$list_type>\n" . $result . "\n"; $result; }egmx; } return $text; } sub _ProcessListItems { # # Process the contents of a single ordered or unordered list, splitting it # into individual list items. # my $list_str = shift; my $marker_any = shift; # The $g_list_level global keeps track of when we're inside a list. # Each time we enter a list, we increment it; when we leave a list, # we decrement. If it's zero, we're not in a list anymore. # # We do this because when we're not inside a list, we want to treat # something like this: # # I recommend upgrading to version # 8. Oops, now this line is treated # as a sub-list. # # As a single paragraph, despite the fact that the second line starts # with a digit-period-space sequence. # # Whereas when we're inside a list (or sub-list), that line will be # treated as the start of a sub-list. What a kludge, huh? This is # an aspect of Markdown's syntax that's hard to parse perfectly 000200000FC400005616FBE, # without resorting to mind-reading. Perhaps the solution is to # change the syntax rules such that sub-lists must start with a # starting cardinal number; e.g. "1." or "a.". $g_list_level++; # trim trailing blank lines: $list_str =~ s/\n{2,}\z/\n/; $list_str =~ s{ (\n)? # leading line = $1 (^[ \t]*) # leading whitespace = $2 ($marker_any) [ \t]+ # list marker = $3 ((?s:.+?) # list item text = $4 (\n{1,2})) (?= \n* (\z | \2 ($marker_any) [ \t]+)) }{ my $item = $4; my $leading_line = $1; my $leading_space = $2; if ($leading_line or ($item =~ m/\n{2,}/)) { $item = _RunBlockGamut(_Outdent($item)); } else { # Recursion for sub-lists: $item = _DoLists(_Outdent($item)); chomp $item; $item = _RunSpanGamut($item); } "
  • " . $item . "
  • \n"; }egmx; $g_list_level--; return $list_str; } sub _DoCodeBlocks { # # Process Markdown `
    ` blocks.
    #	
    
    	my $text = shift;
    
    	$text =~ s{
    			(?:\n\n|\A)
    			(	            # $1 = the code block -- one or more lines, starting with a space/tab
    			  (?:
    			    (?:[ ]{$g_tab_width} | \t)  # Lines must start with a tab or a tab-width of spaces
    			    .*\n+
    			  )+
    			)
    			((?=^[ ]{0,$g_tab_width}\S)|\Z)	# Lookahead for non-space at line-start, or end of doc
    		}{
    			my $codeblock = $1;
    			my $result; # return value
    
    			$codeblock = _EncodeCode(_Outdent($codeblock));
    			$codeblock = _Detab($codeblock);
    			$codeblock =~ s/\A\n+//; # trim leading newlines
    			$codeblock =~ s/\s+\z//; # trim trailing whitespace
    
    			$result = "\n\n
    " . $codeblock . "\n
    \n\n"; $result; }egmx; return $text; } sub _DoCodeSpans { # # * Backtick quotes are used for spans. # # * You can use multiple backticks as the delimiters if you want to # include literal backticks in the code span. So, this input: # # Just type ``foo `bar` baz`` at the prompt. # # Will translate to: # #

    Just type foo `bar` baz at the prompt.

    # # There's no arbitrary limit to the number of backticks you # can use as delimters. If you need three consecutive backticks # in your code, use four for delimiters, etc. # # * You can use spaces to get literal backticks at the edges: # # ... type `` `bar` `` ... # # Turns to: # # ... type `bar` ... # my $text = shift; $text =~ s@ (`+) # $1 = Opening run of ` (.+?) # $2 = The code block (?$c
    "; @egsx; return $text; } sub _EncodeCode { # # Encode/escape certain characters inside Markdown code runs. # The point is that in code, these characters are literals, # and lose their special Markdown meanings. # local $_ = shift; # Encode all ampersands; HTML entities are not # entities within a Markdown code span. s/&/&/g; # Encode $'s, but only if we're running under Blosxom. # (Blosxom interpolates Perl variables in article bodies.) { no warnings 'once'; if (defined($blosxom::version)) { s/\$/$/g; } } # Do the angle bracket song and dance: s! < !<!gx; s! > !>!gx; # Now, escape characters that are magic in Markdown: s! \* !$g_escape_table{'*'}!gx; s! _ !$g_escape_table{'_'}!gx; s! { !$g_escape_table{'{'}!gx; s! } !$g_escape_table{'}'}!gx; s! \[ !$g_escape_table{'['}!gx; s! \] !$g_escape_table{']'}!gx; s! \\ !$g_escape_table{'\\'}!gx; return $_; } sub _DoItalicsAndBold { my $text = shift; # must go first: $text =~ s{ (\*\*|__) (?=\S) (.+?[*_]*) (?<=\S) \1 } {$2}gsx; $text =~ s{ (\*|_) (?=\S) (.+?) (?<=\S) \1 } {$2}gsx; return $text; } sub _DoBlockQuotes { my $text = shift; $text =~ s{ ( # Wrap whole match in $1 ( ^[ \t]*>[ \t]? # '>' at the start of a line 000200000E16000065D4E10, .+\n # rest of the first line (.+\n)* # subsequent consecutive lines \n* # blanks )+ ) }{ my $bq = $1; $bq =~ s/^[ \t]*>[ \t]?//gm; # trim one level of quoting $bq =~ s/^[ \t]+$//mg; # trim whitespace-only lines $bq = _RunBlockGamut($bq); # recurse $bq =~ s/^/ /g; # These leading spaces screw with
     content, so we need to fix that:
    			$bq =~ s{
    					(\s*
    .+?
    ) }{ my $pre = $1; $pre =~ s/^ //mg; $pre; }egsx; "
    \n$bq\n
    \n\n"; }egmx; return $text; } sub _FormParagraphs { # # Params: # $text - string to process with html

    tags # my $text = shift; # Strip leading and trailing lines: $text =~ s/\A\n+//; $text =~ s/\n+\z//; my @grafs = split(/\n{2,}/, $text); # # Wrap

    tags. # foreach (@grafs) { unless (defined( $g_html_blocks{$_} )) { $_ = _RunSpanGamut($_); s/^([ \t]*)/

    /; $_ .= "

    "; } } # # Unhashify HTML blocks # foreach (@grafs) { if (defined( $g_html_blocks{$_} )) { $_ = $g_html_blocks{$_}; } } return join "\n\n", @grafs; } sub _EncodeAmpsAndAngles { # Smart processing for ampersands and angle brackets that need to be encoded. my $text = shift; # Ampersand-encoding based entirely on Nat Irons's Amputator MT plugin: # http://bumppo.net/projects/amputator/ $text =~ s/&(?!#?[xX]?(?:[0-9a-fA-F]+|\w+);)/&/g; # Encode naked <'s $text =~ s{<(?![a-z/?\$!])}{<}gi; return $text; } sub _EncodeBackslashEscapes { # # Parameter: String. # Returns: The string, with after processing the following backslash # escape sequences. # local $_ = shift; s! \\\\ !$g_escape_table{'\\'}!gx; # Must process escaped backslashes first. s! \\` !$g_escape_table{'`'}!gx; s! \\\* !$g_escape_table{'*'}!gx; s! \\_ !$g_escape_table{'_'}!gx; s! \\\{ !$g_escape_table{'{'}!gx; s! \\\} !$g_escape_table{'}'}!gx; s! \\\[ !$g_escape_table{'['}!gx; s! \\\] !$g_escape_table{']'}!gx; s! \\\( !$g_escape_table{'('}!gx; s! \\\) !$g_escape_table{')'}!gx; s! \\> !$g_escape_table{'>'}!gx; s! \\\# !$g_escape_table{'#'}!gx; s! \\\+ !$g_escape_table{'+'}!gx; s! \\\- !$g_escape_table{'-'}!gx; s! \\\. !$g_escape_table{'.'}!gx; s{ \\! }{$g_escape_table{'!'}}gx; return $_; } sub _DoAutoLinks { my $text = shift; $text =~ s{<((https?|ftp):[^'">\s]+)>}{
    $1}gi; # Email addresses: $text =~ s{ < (?:mailto:)? ( [-.\w]+ \@ [-a-z0-9]+(\.[-a-z0-9]+)*\.[a-z]+ ) > }{ _EncodeEmailAddress( _UnescapeSpecialChars($1) ); }egix; return $text; } sub _EncodeEmailAddress { # # Input: an email address, e.g. "foo@example.com" # # Output: the email address as a mailto link, with each character # of the address encoded as either a decimal or hex entity, in # the hopes of foiling most address harvesting spam bots. E.g.: # # foo # @example.com # # Based on a filter by Matthew Wickline, posted to the BBEdit-Talk # mailing list: # my $addr = shift; srand; my @encode = ( sub { '&#' . ord(shift) . ';' }, sub { '&#x' . sprintf( "%X", ord(shift) ) . ';' }, sub { shift }, ); $addr = "mailto:" . $addr; $addr =~ s{(.)}{ 000200001749000073E41742, my $char = $1; if ( $char eq '@' ) { # this *must* be encoded. I insist. $char = $encode[int rand 1]->($char); } elsif ( $char ne ':' ) { # leave ':' alone (to spot mailto: later) my $r = rand; # roughly 10% raw, 45% hex, 45% dec $char = ( $r > .9 ? $encode[2]->($char) : $r < .45 ? $encode[1]->($char) : $encode[0]->($char) ); } $char; }gex; $addr = qq{$addr}; $addr =~ s{">.+?:}{">}; # strip the mailto: from the visible part return $addr; } sub _UnescapeSpecialChars { # # Swap back in all the special characters we've hidden. # my $text = shift; while( my($char, $hash) = each(%g_escape_table) ) { $text =~ s/$hash/$char/g; } return $text; } sub _TokenizeHTML { # # Parameter: String containing HTML markup. # Returns: Reference to an array of the tokens comprising the input # string. Each token is either a tag (possibly with nested, # tags contained therein, such as , or a # run of text between tags. Each element of the array is a # two-element array; the first is either 'tag' or 'text'; # the second is the actual value. # # # Derived from the _tokenize() subroutine from Brad Choate's MTRegex plugin. # # my $str = shift; my $pos = 0; my $len = length $str; my @tokens; my $depth = 6; my $nested_tags = join('|', ('(?:<[a-z/!$](?:[^<>]') x $depth) . (')*>)' x $depth); my $match = qr/(?s: ) | # comment (?s: <\? .*? \?> ) | # processing instruction $nested_tags/ix; # nested tags while ($str =~ m/($match)/g) { my $whole_tag = $1; my $sec_start = pos $str; my $tag_start = $sec_start - length $whole_tag; if ($pos < $tag_start) { push @tokens, ['text', substr($str, $pos, $tag_start - $pos)]; } push @tokens, ['tag', $whole_tag]; $pos = pos $str; } push @tokens, ['text', substr($str, $pos, $len - $pos)] if $pos < $len; \@tokens; } sub _Outdent { # # Remove one level of line-leading tabs or spaces # my $text = shift; $text =~ s/^(\t|[ ]{1,$g_tab_width})//gm; return $text; } sub _Detab { # # Cribbed from a post by Bart Lateur: # # my $text = shift; $text =~ s{(.*?)\t}{$1.(' ' x ($g_tab_width - length($1) % $g_tab_width))}ge; return $text; } 1; __END__ =pod =head1 NAME B =head1 SYNOPSIS B [ B<--html4tags> ] [ B<--version> ] [ B<-shortversion> ] [ I ... ] =head1 DESCRIPTION Markdown is a text-to-HTML filter; it translates an easy-to-read / easy-to-write structured text format into HTML. Markdown's text format is most similar to that of plain text email, and supports features such as headers, *emphasis*, code blocks, blockquotes, and links. Markdown's syntax is designed not as a generic markup language, but specifically to serve as a front-end to (X)HTML. You can use span-level HTML tags anywhere in a Markdown document, and you can use block level HTML tags (like
    and as well). For more information about Markdown's syntax, see: http://daringfireball.net/projects/markdown/ =head1 OPTIONS Use "--" to end switch parsing. For example, to open a file named "-z", use: Markdown.pl -- -z =over 4 =item B<--html4tags> Use HTML 4 style for empty element tags, e.g.:
    instead of Markdown's default XHTML style tags, e.g.:
    =item B<-v>, B<--version> Display Markdown's version number and copyright information. =item B<-s>, B<--shortversion> Display the short-form version number. =back =head1 BUGS To file bug reports or feature requests (other than topics listed in the Caveats section above) please send email to: support@daringfireball.net Please include with your report: (1) the example input; (2) the output you expected; (3) the output Markdown actually produced. =head1 VERSION HISTORY See the readme file for detailed release notes for this version. 1.0.1 - 14 Dec 2004 1.0 - 28 Aug 2004 =head1 AUTHOR John Gruber http://daringfireball.net PHP port and other contributions by Michel Fortin http://michelf.com =head1 COPYRIGHT AND LICENSE Copyright (c) 2003-2004 John Gruber All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name "Markdown" nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. This software is provided by the copyright holders and contributors "as is" and any express or implied warranties, including, but not limited to, the implied warranties of merchantability and fitness for a particular purpose are disclaimed. In no event shall the copyright owner or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not limited to, procurement of substitute goods or services; loss of use, data, or profits; or business interruption) however caused and on any theory of liability, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of such damage. =cut 00040000000B0000000208B28000050000000B0000000208B280000600000031000000010Á920‚‚ÁFFFF0‚A00000 D0ÂÁ ‚‚Á‚000700000019000000010Â‚20120‚Á‚0008000000B90000000140,Arial40,10407D104E44000321‚400400080‚1010000900000017000000023‚11B27E3‚11B27E000A00000019000000026‚3E5F2226‚3E5F222000B00000005000000020Â000C0000001300000001F‚‚E1AE03F‚2000F0000005200000000400 10 ‚ÂÁÂÁ‚‚ÁÂ4,4,77A4,4,0D4,E1D4,4,Œ00130000007E00000000DA91F8CE1C1D1E1F7F1B044,-.Śš°­­.'"ÔŐŇÓÉÉFFFF0FFFF0FFFE000000060001001777AA˝‘cÄ˝đKM6‹&BŞ’Z’Ţ ‚Verdana ˝ňüž%¤'?ďŔLAND˙˙˙˙˙˙mac This script returns a string which appears in the Status Center on the Radio UserLand home page. return ("I'm a very cool Tool!") „€.<zVerdana žŠržŻ'?ďŔLAND˙˙˙˙˙˙mac #title "Markdown test story" Test of Markdown. * item * item * item This is a [link][1] [1]: http://radio.userland.com €€€€€€€€€€.‰0áVerdana žOžîY'?ďŔLAND˙˙˙˙˙˙mac ToDo Finalize implementation Patrick's method or mine Finalized aR implementation Done Fix callbacks so they assign changed values adrCallback^(@filetext) -- good filetext = adrCallback^(filetext) -- bad renderStory €€€€€€€€‰4ć Ö%Verdana ˝•’sž!>(śşžâLAND˙˙˙˙˙˙mac #renderOutlineWith "pikerenderer" #pikeRendererDriver "html" 20 1 bold Markdown Tool <%MarkdownInfo.name%> Version: <%MarkdownInfo.version%> Changes Current state The Markdown Tool is in the gems folder. It is, as of this post, the current version. To always ensure that you have the current version select "Refresh Code..." from the Tools > Markdown menu within Radio. This tool incorporates both rendering for Windows and Mac OS X. This tool provides for 2 different methods of doing the Markdown rendering. One method by me and one by Patrick Ritchie. Read the docs they do have some useful info. Especially on installing ActivePerl. Requirements You will need to follow one of these sets of directions depending upon your OS. Mac OS X Download John Gruber's Markdown. You need to place this somewhere inside of your OS X Home folder. Windows Need to install ActivePerl. Instructions for ActivePerl. 1. Go here: http://www.activestate.com/Products/ActivePerl/ 2. Download the MSI package 3. Run the installer 4. That's it! How it works Andy's method Uses callbacks to render the post text through the Markdown script/render prior to upstreaming/rendering of the page or RSS. Nothing new is saved, only re-rendered as needed. The original marked-up text remains unchanged in weblogData.root. Patrick's method Uses callbacks at post time to render the post text through the Markdown script/renderer and then saves the Markdown rendered text to a new item inside weblogData.root. Uses other callbacks to swap in/out the Markdown rendered text and original marked-up text for editing, etc. The original marked-up text remains unchanged in weblogData.root. Both methods In editing you see marked-up text. In rendering/upstreaming you see Markdown rendered text. Tool choices It is possible to run either Andy's method or Patrick's method on either OS. It is possible to switch between the 2 methods. Markdown tool menu "Render with Markdown" This is checked and posts and stories will be rendered with Markdown. Simpler than activating and deactivating. Used for testing only. "Store Rendered & Non-Rendered" This is a checked or unchecked flag to switch between Patrick's method (checked) and Andy's method (unchecked). "Event logging" When checked an Event will be recorded in the Event log showing how long Markdown rendering took. There is a single event per post. The default value is unchecked. "Refresh Code..." This will download and install the latest version of the Markdown tool. You should do this now. To Do List Convert Markdown.pl to UserTalk. Finalize method of implementation. Make work with activeRenderer. Making progress with Marc Barrot €€€€$datatabl ˇH!?ˇH!?$datatabl°ˇH!?ˇH!?$datatabl°ˇH!?ˇH!?€„€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€4ĘĆş˝ňűž6„  !- 5A IU co t€ „ Š ˛ž ĂĎ Ýé ô  ,8 Bâ çó ü background< callbacks<Ëchanges=fcleanupJŮ codeFreshenerZinitZťlogeł makeUnixPathfˇmarkdowngÔmenuv! menuCheckTextv perlScriptwwstatusCenterMessage a testOutline s testStoryœ#title "Markdown test story" #postTime "10/12/2004; 9:04:23 PM" Test of Markdown. * item * item * item This is a [link][1] [1]: http://radio.userland.comtodo ­userDocsBĘ`$ÄVerdana ˝ňü˝ƒş '?ďŔLAND˙˙˙˙˙˙mac This script runs in its own thread. loop //loop until the application quits Add your code here. thread.sleepFor (10) //sleep for ten seconds MarkdownThread.enabled = false MarkdownSuite.init () „„„€€€`TP.˝ňüžxY˙˙˙ ctenabledscript XTţtArial śFűśFű 2ŽLAND˙˙˙˙˙˙mac on finalFilter (pta) pta^.renderedText = string.replace (pta^.renderedText, "[[title]]", "") return (true) €�����€�����€��������ţ���ą�������� ���-����Geneva���������������������������� ��������������­ÂEu´`ŢQ��� ��� �2LAND˙˙˙˙˙˙������mac ������������on firstFilter (adrPageTable) return (true) €�����€��������ą��ý��������*��[����Geneva���������������������������� ��������������­ÂEuľü7a���p���L�3*lLAND˙˙˙˙˙˙������mac ������������on pageFilter (pta) if typeOf (pta^.template) == outlineType or typeOf (pta^.template) == wpTextType table.assign (@pta^.template, string (pta^.template)) if typeOf (pta^.template) == stringType and not pta^.indirectTemplate pta^.template = string.replace (pta^.template, "<title>", "[[title]]") html.addPageToGlossary (pta) return (true) €�����€�����€�����€�����€�����€�����€�������ý���Ó�������y���.���­ÂEźśFű�������� ���� ��� ����$���0 ����; finalFilter����p�"$ firstFilter����p�#. pagefilter����p�#ë��VGeneva���������������������������� ����������č�P�E��$Ď�������������������������Ó���I�������E������ľü7¨˝…¤�������� ����url���http://127.0.0.1:5335/Markdown/���I���§�������Ł���$���˝…­˝…­�������� ���� ���i ����nlinetext���\["Al12:Users:afragen:Applications:Radio UserLand:Tools:Markdown.root"].MarkdownWebsite.indexpath��� index.wsf���§���á�������‡����������˝…­�������� ����]\["Al12:Users:afragen:Applications:Radio UserLand:Tools:Markdown.root"].MarkdownWebsite.index����p�'(��VArial����������������������������� ������������������������������������������������á���ą�������W����������´ž–������������space���/GIFfGIF89a��€��˙˙˙���!ů����,�������D�;��VArial����������������������������� ������������������������������������������������ą���������Ĺ���V�������´ž†�������� ������� �������"�������+ ����0���: ����C���L ����Q���[ ����aalink���008000bgcolor���FFFFFFflRenderlink���0000FFspaceGif���spacetext���000000vlink���800080��VArial����������������������������� ��������������������������������������������������n�����������������ľü8>������VArial����������������������������� ������������������������������������������������n���Ź�����������.����Verdana��������������������������� ��������������˝óŇ˝•Ł×��� ��ó�œťLAND˙˙˙˙˙˙������mac ������������return (renderObject(@MarkdownSuite.changes)) €��������Ź���­�����������/����Verdana��������������������������� ��������������˝óŇ˝•Ľ��� �ó�œťLAND˙˙˙˙˙˙������mac ������������return (renderObject(@MarkdownSuite.userDocs)) €��������­��^���������`���ľü7˝•Łć�������� ���� ��� �������* ����4���@ ����H���T ����[���g ����n���z ����‚���Ž ����”#filters������%ô#ftpSite������&Ó #glossary������'Ű#images������(Č#prefs������)…#tools������*°changes������+*index������+â��VVerdana��������������������������� ����������ş�“�??8“ň������������������������^��ę�������É���B���˝ňúžxY�������� ���� ��� ����&���2 ����@���L ����[���g ����w MarkdownData��������X MarkdownInfo�������: MarkdownSuite������‚MarkdownThread������!ÄMarkdownWebsite������,›��V Lucida Grande��������������������������������¨�Ľ�=�Ÿ�ke#������������������������t��Ű���Verdana��������������������������� ����� ��������ž!œžw§���O��'?ďŔLAND˙˙˙˙˙˙������mac ������������MarkdownData MarkdownInfo MarkdownSuite background callbacks fileMenu radio editItem oldCallbacks postItem renderItem renderStory user activeRenderer renderNode renderOpml weblogData changes cleanup codeFreshener loadNewCode refreshCode refreshCodeMenu releaseNewCode init log makeUnixPath markdown menu menuCheckText perlScript statusCenterMessage testOutline testStory todo userDocs MarkdownThread MarkdownWebsite €������[—,�[’d�������������€������[—,�[’d�������������€������[—,�[’d�������������€������[—,�[—x�������������€������[—,�[—x�������������€������[—,�[—„�������������€������[—,�[—„�������������€�������[—,�[— ��������������€������[—,�[— �������������€�������[—,�[— ��������������€�������[—,�[— ��������������€�������[—,�[— ��������������€������[—,�[—„�������������€������[—,�[—Đ�������������€�������[—,�[›h��������������€�������[—,�[›h��������������€������[—,�[—„�������������€�������[—,�[—x��������������€�������[—,�[—x��������������€������[—,�[—x�������������€�������[—,ö¨ŕ��������������€�������[—,ö¨ŕ��������������€�������[—,ö¨ŕ��������������€�������[—,ö¨ŕ��������������€�������[—,�[—x��������������€�������[—,�[—x��������������€�������[—,�[—x��������������€�������[—,�[—x��������������€�������[—,�[—x��������������€�������[—,�[—x��������������€�������[—,�[—x��������������€�������[—,�[—x��������������€�������[—,�[—x��������������€�������[—,�[—x��������������€�������[—,�[—x��������������€�������[—,�[—x��������������€������[—,�[’d�������������€������[—,�[’d���������������ę��ş������.@8ÖČChicago��������������������������?˙� ����������������˙˙˙˙˙˙˙˙ Lucida Grande���������������������� �����������������A�š�čŕGeneva����������������������������� ����������������^=¸ĂChicago��������������������������?˙� ����������������m.ŠŇChicago��������������������������?˙� ����������������˙˙˙˙˙˙˙˙ Lucida Grande���������������������� ����������������������˙˙����������������������������������������������������������ş