1 jQuery.extend({createUploadIframe:function(d,b){var a="jUploadFrame"+d;if(window.ActiveXObject){var c=document.createElement('<iframe id="'+a+'" name="'+a+'" />');if(typeof b=="boolean"){c.src="javascript:false"}else{if(typeof b=="string"){c.src=b}}}else{var c=document.createElement("iframe");c.id=a;c.name=a}c.style.position="absolute";c.style.top="-1000px";c.style.left="-1000px";document.body.appendChild(c);return c},createUploadForm:function(g,b){var e="jUploadForm"+g;var a="jUploadFile"+g;var d=$('<form action="" method="POST" name="'+e+'" id="'+e+'" enctype="multipart/form-data"></form>');var c=$("#"+b);var f=$(c).clone();$(c).attr("id",a);$(c).before(f);$(c).appendTo(d);$(d).css("position","absolute");$(d).css("top","-1200px");$(d).css("left","-1200px");$(d).appendTo("body");return d},ajaxFileUpload:function(k){k=jQuery.extend({},jQuery.ajaxSettings,k);var a=new Date().getTime();var b=jQuery.createUploadForm(a,k.fileElementId);var i=jQuery.createUploadIframe(a,k.secureuri);var h="jUploadFrame"+a;var j="jUploadForm"+a;if(k.global&&!jQuery.active++){jQuery.event.trigger("ajaxStart")}var c=false;var f={};if(k.global){jQuery.event.trigger("ajaxSend",[f,k])}var d=function(l){var p=document.getElementById(h);try{if(p.contentWindow){f.responseText=p.contentWindow.document.body?p.contentWindow.document.body.innerText:null;f.responseXML=p.contentWindow.document.XMLDocument?p.contentWindow.document.XMLDocument:p.contentWindow.document}else{if(p.contentDocument){f.responseText=p.contentDocument.document.body?p.contentDocument.document.body.textContent||document.body.innerText:null;f.responseXML=p.contentDocument.document.XMLDocument?p.contentDocument.document.XMLDocument:p.contentDocument.document}}}catch(o){jQuery.handleError(k,f,null,o)}if(f||l=="timeout"){c=true;var m;try{m=l!="timeout"?"success":"error";if(m!="error"){var n=jQuery.uploadHttpData(f,k.dataType);if(k.success){k.success(n,m)}if(k.global){jQuery.event.trigger("ajaxSuccess",[f,k])}}else{jQuery.handleError(k,f,m)}}catch(o){m="error";jQuery.handleError(k,f,m,o)}if(k.global){jQuery.event.trigger("ajaxComplete",[f,k])}if(k.global&&!--jQuery.active){jQuery.event.trigger("ajaxStop")}if(k.complete){k.complete(f,m)}jQuery(p).unbind();setTimeout(function(){try{$(p).remove();$(b).remove()}catch(q){jQuery.handleError(k,f,null,q)}},100);f=null}};if(k.timeout>0){setTimeout(function(){if(!c){d("timeout")}},k.timeout)}try{var b=$("#"+j);$(b).attr("action",k.url);$(b).attr("method","POST");$(b).attr("target",h);if(b.encoding){b.encoding="multipart/form-data"}else{b.enctype="multipart/form-data"}$(b).submit()}catch(g){jQuery.handleError(k,f,null,g)}if(window.attachEvent){document.getElementById(h).attachEvent("onload",d)}else{document.getElementById(h).addEventListener("load",d,false)}return{abort:function(){}}},uploadHttpData:function(r,type){var data=!type;data=type=="xml"||data?r.responseXML:r.responseText;if(type=="script"){jQuery.globalEval(data)}if(type=="json"){eval("data = "+data)}if(type=="html"){jQuery("<div>").html(data).evalScripts()}return data}});
3 function ajaxFileUpload(imageUrl)
5 $("#loading").ajaxStart(function(){
7 }).ajaxComplete(function(){
11 $("#upload").ajaxStart(function(){
13 }).ajaxComplete(function(){
20 url: scriptUrl+'upload/',
22 fileElementId:'file-upload',
24 success: function (data, status)
26 var fileURL = $(data).find('file_url').text();
27 var error = $(data).find('error').text();
32 alert("There was an internal server error uploading your file.\nPermission denied.");
35 imageUrl.attr('value', appUrl + fileURL);
40 error: function (data, status, e)
50 var Attacklab = Attacklab || {};
52 Attacklab.wmdBase = function(){
54 // A few handy aliases for readability.
55 var wmd = top.Attacklab;
56 var doc = top.document;
58 var nav = top.navigator;
67 var position = wmd.Position;
68 var command = wmd.Command;
69 var global = wmd.Global;
72 // Used to work around some browser bugs where we can't use feature testing.
73 global.isIE = /msie/.test(nav.userAgent.toLowerCase());
74 global.isIE_5or6 = /msie 6/.test(nav.userAgent.toLowerCase()) || /msie 5/.test(nav.userAgent.toLowerCase());
75 global.isIE_7plus = global.isIE && !global.isIE_5or6;
76 global.isOpera = /opera/.test(nav.userAgent.toLowerCase());
77 global.isKonqueror = /konqueror/.test(nav.userAgent.toLowerCase());
80 // -------------------------------------------------------------------
81 // YOUR CHANGES GO HERE
83 // I've tried to localize the things you are likely to change to
85 // -------------------------------------------------------------------
87 // The text that appears on the upper part of the dialog box when
89 var imageDialogText = "<p style='margin-top: 0px'>" + $.i18n._('enter image url') + "</p>";
90 var linkDialogText = "<p style='margin-top: 0px'>" + $.i18n._('enter url') + "</p>";
91 var uploadImageHTML ="<div>" + $.i18n._('upload image') + "</div>" +
92 "<input type=\"file\" name=\"file-upload\" id=\"file-upload\" size=\"26\" "+
93 "onchange=\"return ajaxFileUpload($('#image-url'));\"/><br>" +
94 "<img id=\"loading\" src=\"" + mediaUrl("media/images/indicator.gif") + "\" style=\"display:none;\"/>";
96 // The default text that appears in the dialog input box when entering
98 var imageDefaultText = "http://";
99 var linkDefaultText = "http://";
101 // The location of your button images relative to the base directory.
102 var imageDirectory = "images/";
104 // Some intervals in ms. These can be adjusted to reduce the control's load.
105 var previewPollInterval = 500;
106 var pastePollInterval = 100;
108 // The link and title for the help button
109 var helpLink = "http://daringfireball.net/projects/markdown/syntax";
110 var helpHoverTitle = "MarkDown Syntax";
111 var helpTarget = "_blank";
113 // -------------------------------------------------------------------
114 // END OF YOUR CHANGES
115 // -------------------------------------------------------------------
117 // A collection of the important regions on the page.
118 // Cached so we don't have to keep traversing the DOM.
119 wmd.PanelCollection = function(){
120 this.buttonBar = doc.getElementById("wmd-button-bar");
121 this.preview = doc.getElementById("previewer");
122 this.output = doc.getElementById("wmd-output");
123 this.input = doc.getElementById("editor");
126 // This PanelCollection object can't be filled until after the page
128 wmd.panels = undefined;
130 // Internet explorer has problems with CSS sprite buttons that use HTML
131 // lists. When you click on the background image "button", IE will
132 // select the non-existent link text and discard the selection in the
133 // textarea. The solution to this is to cache the textarea selection
134 // on the button's mousedown event and set a flag. In the part of the
135 // code where we need to grab the selection, we check for the flag
136 // and, if it's set, use the cached area instead of querying the
139 // This ONLY affects Internet Explorer (tested on versions 6, 7
140 // and 8) and ONLY on button clicks. Keyboard shortcuts work
141 // normally since the focus never leaves the textarea.
142 wmd.ieCachedRange = null; // cached textarea selection
143 wmd.ieRetardedClick = false; // flag
145 // Returns true if the DOM element is visible, false if it's hidden.
146 // Checks if display is anything other than none.
147 util.isVisible = function (elem) {
149 if (window.getComputedStyle) {
151 return window.getComputedStyle(elem, null).getPropertyValue("display") !== "none";
153 else if (elem.currentStyle) {
155 return elem.currentStyle["display"] !== "none";
160 // Adds a listener callback to a DOM element which is fired on a specified
162 util.addEvent = function(elem, event, listener){
163 if (elem.attachEvent) {
164 // IE only. The "on" is mandatory.
165 elem.attachEvent("on" + event, listener);
169 elem.addEventListener(event, listener, false);
174 // Removes a listener callback from a DOM element which is fired on a specified
176 util.removeEvent = function(elem, event, listener){
177 if (elem.detachEvent) {
178 // IE only. The "on" is mandatory.
179 elem.detachEvent("on" + event, listener);
183 elem.removeEventListener(event, listener, false);
187 // Converts \r\n and \r to \n.
188 util.fixEolChars = function(text){
189 text = text.replace(/\r\n/g, "\n");
190 text = text.replace(/\r/g, "\n");
194 // Extends a regular expression. Returns a new RegExp
195 // using pre + regex + post as the expression.
196 // Used in a few functions where we have a base
197 // expression and we want to pre- or append some
198 // conditions to it (e.g. adding "$" to the end).
199 // The flags are unchanged.
201 // regex is a RegExp, pre and post are strings.
202 util.extendRegExp = function(regex, pre, post){
204 if (pre === null || pre === undefined)
208 if(post === null || post === undefined)
213 var pattern = regex.toString();
216 // Replace the flags with empty space and store them.
217 // Technically, this can match incorrect flags like "gmm".
218 var result = pattern.match(/\/([gim]*)$/);
219 if (result === null) {
226 // Remove the flags and slash delimiters from the regular expression.
227 pattern = pattern.replace(/(^\/|\/[gim]*$)/g, "");
228 pattern = pre + pattern + post;
230 return new RegExp(pattern, flags);
234 // Sets the image for a button passed to the WMD editor.
235 // Returns a new element with the image attached.
236 // Adds several style properties to the image.
237 util.createImage = function(img){
239 var imgPath = imageDirectory + img;
241 var elem = doc.createElement("img");
242 elem.className = "wmd-button";
249 // This simulates a modal dialog box and asks for the URL when you
250 // click the hyperlink or image buttons.
252 // text: The html for the input box.
253 // defaultInputText: The default value that appears in the input box.
254 // makeLinkMarkdown: The function which is executed when the prompt is dismissed, either via OK or Cancel
255 util.prompt = function(text, defaultInputText, makeLinkMarkdown){
257 // These variables need to be declared at this level since they are used
258 // in multiple functions.
259 var dialog; // The dialog box.
260 var background; // The background beind the dialog box.
261 var input; // The text box where you enter the hyperlink.
263 // The dialog box type(0: Link, 1: Image)
264 if(arguments.length == 4){
268 if (defaultInputText === undefined) {
269 defaultInputText = "";
272 // Used as a keydown event handler. Esc dismisses the prompt.
273 // Key code 27 is ESC.
274 var checkEscape = function(key){
275 var code = (key.charCode || key.keyCode);
281 // Dismisses the hyperlink input box.
282 // isCancel is true if we don't care about the input text.
283 // isCancel is false if we are going to keep the text.
284 var close = function(isCancel){
285 util.removeEvent(doc.body, "keydown", checkEscape);
286 var text = input.value;
292 // Fixes common pasting errors.
293 text = text.replace('http://http://', 'http://');
294 text = text.replace('http://https://', 'https://');
295 text = text.replace('http://ftp://', 'ftp://');
297 if (text.indexOf('http://') === -1 && text.indexOf('ftp://') === -1 && text.indexOf('https://') === -1) {
298 text = 'http://' + text;
302 dialog.parentNode.removeChild(dialog);
303 background.parentNode.removeChild(background);
304 makeLinkMarkdown(text);
308 // Creates the background behind the hyperlink text entry box.
309 // Most of this has been moved to CSS but the div creation and
310 // browser-specific hacks remain here.
311 var createBackground = function(){
313 background = doc.createElement("div");
314 background.className = "wmd-prompt-background";
315 style = background.style;
316 style.position = "absolute";
319 style.zIndex = "1000";
321 // Some versions of Konqueror don't support transparent colors
322 // so we make the whole window transparent.
324 // Is this necessary on modern konqueror browsers?
325 if (global.isKonqueror){
326 style.backgroundColor = "transparent";
328 else if (global.isIE){
329 style.filter = "alpha(opacity=50)";
332 style.opacity = "0.5";
335 var pageSize = position.getPageSize();
336 style.height = pageSize[1] + "px";
339 style.left = doc.documentElement.scrollLeft;
340 style.width = doc.documentElement.clientWidth;
344 style.width = "100%";
347 doc.body.appendChild(background);
350 // Create the text input box form/window.
351 var createDialog = function(){
353 // The main dialog box.
354 dialog = doc.createElement("div");
355 dialog.className = "wmd-prompt-dialog";
356 dialog.style.padding = "10px;";
357 dialog.style.position = "fixed";
358 dialog.style.width = "400px";
359 dialog.style.zIndex = "1001";
362 var question = doc.createElement("div");
363 question.innerHTML = text;
364 question.style.padding = "5px";
365 dialog.appendChild(question);
367 // The web form container for the text box and buttons.
368 var form = doc.createElement("form");
369 form.onsubmit = function(){ return close(false); };
373 style.cssFloat = "left";
374 style.width = "100%";
375 style.textAlign = "center";
376 style.position = "relative";
377 dialog.appendChild(form);
379 // The input text box
380 input = doc.createElement("input");
381 input.id = "image-url";
383 input.value = defaultInputText;
385 style.display = "block";
387 style.marginLeft = style.marginRight = "auto";
388 form.appendChild(input);
390 // The upload file input
391 var upload = doc.createElement("div");
392 upload.innerHTML = uploadImageHTML;
393 upload.style.padding = "5px";
394 form.appendChild(upload);
397 var okButton = doc.createElement("input");
398 okButton.type = "button";
399 okButton.onclick = function(){ return close(false); };
400 okButton.value = "OK";
401 style = okButton.style;
402 style.margin = "10px";
403 style.display = "inline";
408 var cancelButton = doc.createElement("input");
409 cancelButton.type = "button";
410 cancelButton.onclick = function(){ return close(true); };
411 cancelButton.value = "Cancel";
412 style = cancelButton.style;
413 style.margin = "10px";
414 style.display = "inline";
417 // The order of these buttons is different on macs.
418 if (/mac/.test(nav.platform.toLowerCase())) {
419 form.appendChild(cancelButton);
420 form.appendChild(okButton);
423 form.appendChild(okButton);
424 form.appendChild(cancelButton);
427 util.addEvent(doc.body, "keydown", checkEscape);
428 dialog.style.top = "50%";
429 dialog.style.left = "50%";
430 dialog.style.display = "block";
431 if(global.isIE_5or6){
432 dialog.style.position = "absolute";
433 dialog.style.top = doc.documentElement.scrollTop + 200 + "px";
434 dialog.style.left = "50%";
436 doc.body.appendChild(dialog);
438 // This has to be done AFTER adding the dialog to the form if you
439 // want it to be centered.
440 dialog.style.marginTop = -(position.getHeight(dialog) / 2) + "px";
441 dialog.style.marginLeft = -(position.getWidth(dialog) / 2) + "px";
447 // Why is this in a zero-length timeout?
448 // Is it working around a browser bug?
449 top.setTimeout(function(){
453 var defTextLen = defaultInputText.length;
454 if (input.selectionStart !== undefined) {
455 input.selectionStart = 0;
456 input.selectionEnd = defTextLen;
458 else if (input.createTextRange) {
459 var range = input.createTextRange();
460 range.collapse(false);
461 range.moveStart("character", -defTextLen);
462 range.moveEnd("character", defTextLen);
472 // The assignment in the while loop makes jslint cranky.
473 // I'll change it to a better loop later.
474 position.getTop = function(elem, isInner){
475 var result = elem.offsetTop;
477 while (elem = elem.offsetParent) {
478 result += elem.offsetTop;
484 position.getHeight = function (elem) {
485 return elem.offsetHeight || elem.scrollHeight;
488 position.getWidth = function (elem) {
489 return elem.offsetWidth || elem.scrollWidth;
492 position.getPageSize = function(){
494 var scrollWidth, scrollHeight;
495 var innerWidth, innerHeight;
497 // It's not very clear which blocks work with which browsers.
498 if(self.innerHeight && self.scrollMaxY){
499 scrollWidth = doc.body.scrollWidth;
500 scrollHeight = self.innerHeight + self.scrollMaxY;
502 else if(doc.body.scrollHeight > doc.body.offsetHeight){
503 scrollWidth = doc.body.scrollWidth;
504 scrollHeight = doc.body.scrollHeight;
507 scrollWidth = doc.body.offsetWidth;
508 scrollHeight = doc.body.offsetHeight;
511 if(self.innerHeight){
513 innerWidth = self.innerWidth;
514 innerHeight = self.innerHeight;
516 else if(doc.documentElement && doc.documentElement.clientHeight){
517 // Some versions of IE (IE 6 w/ a DOCTYPE declaration)
518 innerWidth = doc.documentElement.clientWidth;
519 innerHeight = doc.documentElement.clientHeight;
522 // Other versions of IE
523 innerWidth = doc.body.clientWidth;
524 innerHeight = doc.body.clientHeight;
527 var maxWidth = Math.max(scrollWidth, innerWidth);
528 var maxHeight = Math.max(scrollHeight, innerHeight);
529 return [maxWidth, maxHeight, innerWidth, innerHeight];
532 // Watches the input textarea, polling at an interval and runs
533 // a callback function if anything has changed.
534 wmd.inputPoller = function(callback, interval){
536 var pollerObj = this;
537 var inputArea = wmd.panels.input;
539 // Stored start, end and text. Used to see if there are changes to the input.
544 var killHandle; // Used to cancel monitoring on destruction.
545 // Checks to see if anything has changed in the textarea.
546 // If so, it runs the callback.
547 this.tick = function(){
549 if (!util.isVisible(inputArea)) {
553 // Update the selection start and end, text.
554 if (inputArea.selectionStart || inputArea.selectionStart === 0) {
555 var start = inputArea.selectionStart;
556 var end = inputArea.selectionEnd;
557 if (start != lastStart || end != lastEnd) {
561 if (markdown != inputArea.value) {
562 markdown = inputArea.value;
571 var doTickCallback = function(){
573 if (!util.isVisible(inputArea)) {
577 // If anything has changed, call the function.
578 if (pollerObj.tick()) {
583 // Set how often we poll the textarea for changes.
584 var assignInterval = function(){
585 // previewPollInterval is set at the top of the namespace.
586 killHandle = top.setInterval(doTickCallback, interval);
589 this.destroy = function(){
590 top.clearInterval(killHandle);
596 // Handles pushing and popping TextareaStates for undo/redo commands.
597 // I should rename the stack variables to list.
598 wmd.undoManager = function(callback){
601 var undoStack = []; // A stack of undo states
602 var stackPtr = 0; // The index of the current state
604 var lastState; // The last state
606 var timer; // The setTimeout handle for cancelling the timer
609 // Set the mode for later logic steps.
610 var setMode = function(newMode, noSave){
612 if (mode != newMode) {
619 if (!global.isIE || mode != "moving") {
620 timer = top.setTimeout(refreshState, 1);
623 inputStateObj = null;
627 var refreshState = function(){
628 inputStateObj = new wmd.TextareaState();
633 this.setCommandMode = function(){
636 timer = top.setTimeout(refreshState, 0);
639 this.canUndo = function(){
643 this.canRedo = function(){
644 if (undoStack[stackPtr + 1]) {
650 // Removes the last state and restores it.
651 this.undo = function(){
653 if (undoObj.canUndo()) {
655 // What about setting state -1 to null or checking for undefined?
660 undoStack[stackPtr] = new wmd.TextareaState();
661 undoStack[--stackPtr].restore();
670 wmd.panels.input.focus();
675 this.redo = function(){
677 if (undoObj.canRedo()) {
679 undoStack[++stackPtr].restore();
687 wmd.panels.input.focus();
691 // Push the input area state to the stack.
692 var saveState = function(){
694 var currState = inputStateObj || new wmd.TextareaState();
699 if (mode == "moving") {
701 lastState = currState;
706 if (undoStack[stackPtr - 1].text != lastState.text) {
707 undoStack[stackPtr++] = lastState;
711 undoStack[stackPtr++] = currState;
712 undoStack[stackPtr + 1] = null;
718 var handleCtrlYZ = function(event){
722 if (event.ctrlKey || event.metaKey) {
724 // IE and Opera do not support charCode.
725 var keyCode = event.charCode || event.keyCode;
726 var keyCodeChar = String.fromCharCode(keyCode);
728 switch (keyCodeChar) {
736 if (!event.shiftKey) {
748 if (event.preventDefault) {
749 event.preventDefault();
752 top.event.returnValue = false;
758 // Set the mode depending on what is going on in the input area.
759 var handleModeChange = function(event){
761 if (!event.ctrlKey && !event.metaKey) {
763 var keyCode = event.keyCode;
765 if ((keyCode >= 33 && keyCode <= 40) || (keyCode >= 63232 && keyCode <= 63235)) {
766 // 33 - 40: page up/dn and arrow keys
767 // 63232 - 63235: page up/dn and arrow keys on safari
770 else if (keyCode == 8 || keyCode == 46 || keyCode == 127) {
776 else if (keyCode == 13) {
780 else if (keyCode == 27) {
784 else if ((keyCode < 16 || keyCode > 20) && keyCode != 91) {
785 // 16-20 are shift, etc.
786 // 91: left window key
787 // I think this might be a little messed up since there are
788 // a lot of nonprinting keys above 20.
794 var setEventHandlers = function(){
796 util.addEvent(wmd.panels.input, "keypress", function(event){
799 if ((event.ctrlKey || event.metaKey) && (event.keyCode == 89 || event.keyCode == 90)) {
800 event.preventDefault();
804 var handlePaste = function(){
805 if (global.isIE || (inputStateObj && inputStateObj.text != wmd.panels.input.value)) {
806 if (timer == undefined) {
814 // pastePollInterval is specified at the beginning of this namespace.
815 poller = new wmd.inputPoller(handlePaste, pastePollInterval);
817 util.addEvent(wmd.panels.input, "keydown", handleCtrlYZ);
818 util.addEvent(wmd.panels.input, "keydown", handleModeChange);
820 util.addEvent(wmd.panels.input, "mousedown", function(){
823 wmd.panels.input.onpaste = handlePaste;
824 wmd.panels.input.ondrop = handlePaste;
827 var init = function(){
833 this.destroy = function(){
842 // I think my understanding of how the buttons and callbacks are stored in the array is incomplete.
843 wmd.editor = function(previewRefreshCallback){
845 if (!previewRefreshCallback) {
846 previewRefreshCallback = function(){};
849 var inputBox = wmd.panels.input;
851 var offsetHeight = 0;
858 var div; // This name is pretty ambiguous. I should rename this.
860 // Used to cancel recurring events from setInterval.
863 var undoMgr; // The undo manager
865 // Perform the button's action.
866 var doClick = function(button){
873 undoMgr.setCommandMode();
876 var state = new wmd.TextareaState();
882 var chunks = state.getChunks();
884 // Some commands launch a "modal" prompt dialog. Javascript
885 // can't really make a modal dialog box and the WMD code
886 // will continue to execute while the dialog is displayed.
887 // This prevents the dialog pattern I'm used to and means
888 // I can't do something like this:
890 // var link = CreateLinkDialog();
891 // makeMarkdownLink(link);
893 // Instead of this straightforward method of handling a
894 // dialog I have to pass any code which would execute
895 // after the dialog is dismissed (e.g. link creation)
896 // in a function parameter.
898 // Yes this is awkward and I think it sucks, but there's
899 // no real workaround. Only the image and link code
900 // create dialogs and require the function pointers.
901 var fixupInputArea = function(){
906 state.setChunks(chunks);
910 previewRefreshCallback();
913 var useDefaultText = true;
914 var noCleanup = button.textOp(chunks, fixupInputArea, useDefaultText);
922 if (button.execute) {
923 button.execute(editObj);
927 var setUndoRedoButtonStates = function(){
929 setupButton(document.getElementById("wmd-undo-button"), undoMgr.canUndo());
930 setupButton(document.getElementById("wmd-redo-button"), undoMgr.canRedo());
934 var setupButton = function(button, isEnabled) {
936 var normalYShift = "0px";
937 var disabledYShift = "-20px";
938 var highlightYShift = "-40px";
941 button.style.backgroundPosition = button.XShift + " " + normalYShift;
942 button.onmouseover = function(){
943 this.style.backgroundPosition = this.XShift + " " + highlightYShift;
946 button.onmouseout = function(){
947 this.style.backgroundPosition = this.XShift + " " + normalYShift;
950 // IE tries to select the background image "button" text (it's
951 // implemented in a list item) so we have to cache the selection
954 button.onmousedown = function() {
955 wmd.ieRetardedClick = true;
956 wmd.ieCachedRange = document.selection.createRange();
962 button.onclick = function() {
963 if (this.onmouseout) {
972 button.style.backgroundPosition = button.XShift + " " + disabledYShift;
973 button.onmouseover = button.onmouseout = button.onclick = function(){};
977 var makeSpritedButtonRow = function(){
979 var buttonBar = document.getElementById("wmd-button-bar");
981 var normalYShift = "0px";
982 var disabledYShift = "-20px";
983 var highlightYShift = "-40px";
985 var buttonRow = document.createElement("ul");
986 buttonRow.id = "wmd-button-row";
987 buttonRow = buttonBar.appendChild(buttonRow);
990 var boldButton = document.createElement("li");
991 boldButton.className = "wmd-button";
992 boldButton.id = "wmd-bold-button";
993 boldButton.title = "Strong <strong> Ctrl+B";
994 boldButton.XShift = "0px";
995 boldButton.textOp = command.doBold;
996 setupButton(boldButton, true);
997 buttonRow.appendChild(boldButton);
999 var italicButton = document.createElement("li");
1000 italicButton.className = "wmd-button";
1001 italicButton.id = "wmd-italic-button";
1002 italicButton.title = "Emphasis <em> Ctrl+I";
1003 italicButton.XShift = "-20px";
1004 italicButton.textOp = command.doItalic;
1005 setupButton(italicButton, true);
1006 buttonRow.appendChild(italicButton);
1008 var spacer1 = document.createElement("li");
1009 spacer1.className = "wmd-spacer";
1010 spacer1.id = "wmd-spacer1";
1011 buttonRow.appendChild(spacer1);
1013 var linkButton = document.createElement("li");
1014 linkButton.className = "wmd-button";
1015 linkButton.id = "wmd-link-button";
1016 linkButton.title = "Hyperlink <a> Ctrl+L";
1017 linkButton.XShift = "-40px";
1018 linkButton.textOp = function(chunk, postProcessing, useDefaultText){
1019 return command.doLinkOrImage(chunk, postProcessing, false);
1021 setupButton(linkButton, true);
1022 buttonRow.appendChild(linkButton);
1024 var quoteButton = document.createElement("li");
1025 quoteButton.className = "wmd-button";
1026 quoteButton.id = "wmd-quote-button";
1027 quoteButton.title = "Blockquote <blockquote> Ctrl+Q";
1028 quoteButton.XShift = "-60px";
1029 quoteButton.textOp = command.doBlockquote;
1030 setupButton(quoteButton, true);
1031 buttonRow.appendChild(quoteButton);
1033 var codeButton = document.createElement("li");
1034 codeButton.className = "wmd-button";
1035 codeButton.id = "wmd-code-button";
1036 codeButton.title = "Code Sample <pre><code> Ctrl+K";
1037 codeButton.XShift = "-80px";
1038 codeButton.textOp = command.doCode;
1039 setupButton(codeButton, true);
1040 buttonRow.appendChild(codeButton);
1042 var imageButton = document.createElement("li");
1043 imageButton.className = "wmd-button";
1044 imageButton.id = "wmd-image-button";
1045 imageButton.title = "Image <img> Ctrl+G";
1046 imageButton.XShift = "-100px";
1047 imageButton.textOp = function(chunk, postProcessing, useDefaultText){
1048 return command.doLinkOrImage(chunk, postProcessing, true);
1050 setupButton(imageButton, true);
1051 buttonRow.appendChild(imageButton);
1053 var spacer2 = document.createElement("li");
1054 spacer2.className = "wmd-spacer";
1055 spacer2.id = "wmd-spacer2";
1056 buttonRow.appendChild(spacer2);
1058 var olistButton = document.createElement("li");
1059 olistButton.className = "wmd-button";
1060 olistButton.id = "wmd-olist-button";
1061 olistButton.title = "Numbered List <ol> Ctrl+O";
1062 olistButton.XShift = "-120px";
1063 olistButton.textOp = function(chunk, postProcessing, useDefaultText){
1064 command.doList(chunk, postProcessing, true, useDefaultText);
1066 setupButton(olistButton, true);
1067 buttonRow.appendChild(olistButton);
1069 var ulistButton = document.createElement("li");
1070 ulistButton.className = "wmd-button";
1071 ulistButton.id = "wmd-ulist-button";
1072 ulistButton.title = "Bulleted List <ul> Ctrl+U";
1073 ulistButton.XShift = "-140px";
1074 ulistButton.textOp = function(chunk, postProcessing, useDefaultText){
1075 command.doList(chunk, postProcessing, false, useDefaultText);
1077 setupButton(ulistButton, true);
1078 buttonRow.appendChild(ulistButton);
1080 var headingButton = document.createElement("li");
1081 headingButton.className = "wmd-button";
1082 headingButton.id = "wmd-heading-button";
1083 headingButton.title = "Heading <h1>/<h2> Ctrl+H";
1084 headingButton.XShift = "-160px";
1085 headingButton.textOp = command.doHeading;
1086 setupButton(headingButton, true);
1087 buttonRow.appendChild(headingButton);
1089 var hrButton = document.createElement("li");
1090 hrButton.className = "wmd-button";
1091 hrButton.id = "wmd-hr-button";
1092 hrButton.title = "Horizontal Rule <hr> Ctrl+R";
1093 hrButton.XShift = "-180px";
1094 hrButton.textOp = command.doHorizontalRule;
1095 setupButton(hrButton, true);
1096 buttonRow.appendChild(hrButton);
1098 var spacer3 = document.createElement("li");
1099 spacer3.className = "wmd-spacer";
1100 spacer3.id = "wmd-spacer3";
1101 buttonRow.appendChild(spacer3);
1103 var undoButton = document.createElement("li");
1104 undoButton.className = "wmd-button";
1105 undoButton.id = "wmd-undo-button";
1106 undoButton.title = "Undo - Ctrl+Z";
1107 undoButton.XShift = "-200px";
1108 undoButton.execute = function(manager){
1111 setupButton(undoButton, true);
1112 buttonRow.appendChild(undoButton);
1114 var redoButton = document.createElement("li");
1115 redoButton.className = "wmd-button";
1116 redoButton.id = "wmd-redo-button";
1117 redoButton.title = "Redo - Ctrl+Y";
1118 if (/win/.test(nav.platform.toLowerCase())) {
1119 redoButton.title = "Redo - Ctrl+Y";
1122 // mac and other non-Windows platforms
1123 redoButton.title = "Redo - Ctrl+Shift+Z";
1125 redoButton.XShift = "-220px";
1126 redoButton.execute = function(manager){
1129 setupButton(redoButton, true);
1130 buttonRow.appendChild(redoButton);
1132 var helpButton = document.createElement("li");
1133 helpButton.className = "wmd-button";
1134 helpButton.id = "wmd-help-button";
1135 helpButton.XShift = "-240px";
1136 helpButton.isHelp = true;
1138 var helpAnchor = document.createElement("a");
1139 helpAnchor.href = helpLink;
1140 helpAnchor.target = helpTarget
1141 helpAnchor.title = helpHoverTitle;
1142 helpButton.appendChild(helpAnchor);
1144 setupButton(helpButton, true);
1145 buttonRow.appendChild(helpButton);
1147 setUndoRedoButtonStates();
1150 var setupEditor = function(){
1152 if (/\?noundo/.test(doc.location.href)) {
1153 wmd.nativeUndo = true;
1156 if (!wmd.nativeUndo) {
1157 undoMgr = new wmd.undoManager(function(){
1158 previewRefreshCallback();
1159 setUndoRedoButtonStates();
1163 makeSpritedButtonRow();
1166 var keyEvent = "keydown";
1167 if (global.isOpera) {
1168 keyEvent = "keypress";
1171 util.addEvent(inputBox, keyEvent, function(key){
1173 // Check to see if we have a button key and, if so execute the callback.
1174 if (key.ctrlKey || key.metaKey) {
1176 var keyCode = key.charCode || key.keyCode;
1177 var keyCodeStr = String.fromCharCode(keyCode).toLowerCase();
1179 switch(keyCodeStr) {
1181 doClick(document.getElementById("wmd-bold-button"));
1184 doClick(document.getElementById("wmd-italic-button"));
1187 doClick(document.getElementById("wmd-link-button"));
1190 doClick(document.getElementById("wmd-quote-button"));
1193 doClick(document.getElementById("wmd-code-button"));
1196 doClick(document.getElementById("wmd-image-button"));
1199 doClick(document.getElementById("wmd-olist-button"));
1202 doClick(document.getElementById("wmd-ulist-button"));
1205 doClick(document.getElementById("wmd-heading-button"));
1208 doClick(document.getElementById("wmd-hr-button"));
1211 doClick(document.getElementById("wmd-redo-button"));
1215 doClick(document.getElementById("wmd-redo-button"));
1218 doClick(document.getElementById("wmd-undo-button"));
1226 if (key.preventDefault) {
1227 key.preventDefault();
1231 top.event.returnValue = false;
1236 // Auto-continue lists, code blocks and block quotes when
1237 // the enter key is pressed.
1238 util.addEvent(inputBox, "keyup", function(key){
1239 if (!key.shiftKey && !key.ctrlKey && !key.metaKey) {
1240 var keyCode = key.charCode || key.keyCode;
1241 // Key code 13 is Enter
1242 if (keyCode === 13) {
1244 fakeButton.textOp = command.doAutoindent;
1245 doClick(fakeButton);
1250 // Disable ESC clearing the input textarea on IE
1252 util.addEvent(inputBox, "keydown", function(key){
1253 var code = key.keyCode;
1254 // Key code 27 is ESC
1261 if (inputBox.form) {
1262 var submitCallback = inputBox.form.onsubmit;
1263 inputBox.form.onsubmit = function(){
1265 if (submitCallback) {
1266 return submitCallback.apply(this, arguments);
1272 // Convert the contents of the input textarea to HTML in the output/preview panels.
1273 var convertToHtml = function(){
1276 var markdownConverter = new wmd.showdown.converter();
1278 var text = inputBox.value;
1280 var callback = function(){
1281 inputBox.value = text;
1284 if (!/markdown/.test(wmd.wmd_env.output.toLowerCase())) {
1285 if (markdownConverter) {
1286 inputBox.value = markdownConverter.makeHtml(text);
1287 top.setTimeout(callback, 0);
1294 this.undo = function(){
1300 this.redo = function(){
1306 // This is pretty useless. The setupEditor function contents
1307 // should just be copied here.
1308 var init = function(){
1312 this.destroy = function(){
1316 if (div.parentNode) {
1317 div.parentNode.removeChild(div);
1320 inputBox.style.marginTop = "";
1322 top.clearInterval(creationHandle);
1328 // The input textarea state/contents.
1329 // This is used to implement undo/redo by the undo manager.
1330 wmd.TextareaState = function(){
1333 var stateObj = this;
1334 var inputArea = wmd.panels.input;
1336 this.init = function() {
1338 if (!util.isVisible(inputArea)) {
1342 this.setInputAreaSelectionStartEnd();
1343 this.scrollTop = inputArea.scrollTop;
1344 if (!this.text && inputArea.selectionStart || inputArea.selectionStart === 0) {
1345 this.text = inputArea.value;
1350 // Sets the selected text in the input box after we've performed an
1352 this.setInputAreaSelection = function(){
1354 if (!util.isVisible(inputArea)) {
1358 if (inputArea.selectionStart !== undefined && !global.isOpera) {
1361 inputArea.selectionStart = stateObj.start;
1362 inputArea.selectionEnd = stateObj.end;
1363 inputArea.scrollTop = stateObj.scrollTop;
1365 else if (doc.selection) {
1367 if (doc.activeElement && doc.activeElement !== inputArea) {
1372 var range = inputArea.createTextRange();
1373 range.moveStart("character", -inputArea.value.length);
1374 range.moveEnd("character", -inputArea.value.length);
1375 range.moveEnd("character", stateObj.end);
1376 range.moveStart("character", stateObj.start);
1381 this.setInputAreaSelectionStartEnd = function(){
1383 if (inputArea.selectionStart || inputArea.selectionStart === 0) {
1385 stateObj.start = inputArea.selectionStart;
1386 stateObj.end = inputArea.selectionEnd;
1388 else if (doc.selection) {
1390 stateObj.text = util.fixEolChars(inputArea.value);
1392 // IE loses the selection in the textarea when buttons are
1393 // clicked. On IE we cache the selection and set a flag
1394 // which we check for here.
1396 if(wmd.ieRetardedClick && wmd.ieCachedRange) {
1397 range = wmd.ieCachedRange;
1398 wmd.ieRetardedClick = false;
1401 range = doc.selection.createRange();
1404 var fixedRange = util.fixEolChars(range.text);
1405 var marker = "\x07";
1406 var markedRange = marker + fixedRange + marker;
1407 range.text = markedRange;
1408 var inputText = util.fixEolChars(inputArea.value);
1410 range.moveStart("character", -markedRange.length);
1411 range.text = fixedRange;
1413 stateObj.start = inputText.indexOf(marker);
1414 stateObj.end = inputText.lastIndexOf(marker) - marker.length;
1416 var len = stateObj.text.length - util.fixEolChars(inputArea.value).length;
1419 range.moveStart("character", -fixedRange.length);
1424 range.text = fixedRange;
1427 this.setInputAreaSelection();
1431 // Restore this state into the input area.
1432 this.restore = function(){
1434 if (stateObj.text != undefined && stateObj.text != inputArea.value) {
1435 inputArea.value = stateObj.text;
1437 this.setInputAreaSelection();
1438 inputArea.scrollTop = stateObj.scrollTop;
1441 // Gets a collection of HTML chunks from the inptut textarea.
1442 this.getChunks = function(){
1444 var chunk = new wmd.Chunks();
1446 chunk.before = util.fixEolChars(stateObj.text.substring(0, stateObj.start));
1447 chunk.startTag = "";
1448 chunk.selection = util.fixEolChars(stateObj.text.substring(stateObj.start, stateObj.end));
1450 chunk.after = util.fixEolChars(stateObj.text.substring(stateObj.end));
1451 chunk.scrollTop = stateObj.scrollTop;
1456 // Sets the TextareaState properties given a chunk of markdown.
1457 this.setChunks = function(chunk){
1459 chunk.before = chunk.before + chunk.startTag;
1460 chunk.after = chunk.endTag + chunk.after;
1462 if (global.isOpera) {
1463 chunk.before = chunk.before.replace(/\n/g, "\r\n");
1464 chunk.selection = chunk.selection.replace(/\n/g, "\r\n");
1465 chunk.after = chunk.after.replace(/\n/g, "\r\n");
1468 this.start = chunk.before.length;
1469 this.end = chunk.before.length + chunk.selection.length;
1470 this.text = chunk.before + chunk.selection + chunk.after;
1471 this.scrollTop = chunk.scrollTop;
1477 // before: contains all the text in the input box BEFORE the selection.
1478 // after: contains all the text in the input box AFTER the selection.
1479 wmd.Chunks = function(){
1482 // startRegex: a regular expression to find the start tag
1483 // endRegex: a regular expresssion to find the end tag
1484 wmd.Chunks.prototype.findTags = function(startRegex, endRegex){
1486 var chunkObj = this;
1491 regex = util.extendRegExp(startRegex, "", "$");
1493 this.before = this.before.replace(regex,
1495 chunkObj.startTag = chunkObj.startTag + match;
1499 regex = util.extendRegExp(startRegex, "^", "");
1501 this.selection = this.selection.replace(regex,
1503 chunkObj.startTag = chunkObj.startTag + match;
1510 regex = util.extendRegExp(endRegex, "", "$");
1512 this.selection = this.selection.replace(regex,
1514 chunkObj.endTag = match + chunkObj.endTag;
1518 regex = util.extendRegExp(endRegex, "^", "");
1520 this.after = this.after.replace(regex,
1522 chunkObj.endTag = match + chunkObj.endTag;
1528 // If remove is false, the whitespace is transferred
1529 // to the before/after regions.
1531 // If remove is true, the whitespace disappears.
1532 wmd.Chunks.prototype.trimWhitespace = function(remove){
1534 this.selection = this.selection.replace(/^(\s*)/, "");
1537 this.before += re.$1;
1540 this.selection = this.selection.replace(/(\s*)$/, "");
1543 this.after = re.$1 + this.after;
1548 wmd.Chunks.prototype.addBlankLines = function(nLinesBefore, nLinesAfter, findExtraNewlines){
1550 if (nLinesBefore === undefined) {
1554 if (nLinesAfter === undefined) {
1562 var replacementText;
1564 if (navigator.userAgent.match(/Chrome/)) {
1568 this.selection = this.selection.replace(/(^\n*)/, "");
1569 this.startTag = this.startTag + re.$1;
1570 this.selection = this.selection.replace(/(\n*$)/, "");
1571 this.endTag = this.endTag + re.$1;
1572 this.startTag = this.startTag.replace(/(^\n*)/, "");
1573 this.before = this.before + re.$1;
1574 this.endTag = this.endTag.replace(/(\n*$)/, "");
1575 this.after = this.after + re.$1;
1579 regexText = replacementText = "";
1581 while (nLinesBefore--) {
1582 regexText += "\\n?";
1583 replacementText += "\n";
1586 if (findExtraNewlines) {
1589 this.before = this.before.replace(new re(regexText + "$", ""), replacementText);
1594 regexText = replacementText = "";
1596 while (nLinesAfter--) {
1597 regexText += "\\n?";
1598 replacementText += "\n";
1600 if (findExtraNewlines) {
1604 this.after = this.after.replace(new re(regexText, ""), replacementText);
1608 // The markdown symbols - 4 spaces = code, > = blockquote, etc.
1609 command.prefixes = "(?:\\s{4,}|\\s*>|\\s*-\\s+|\\s*\\d+\\.|=|\\+|-|_|\\*|#|\\s*\\[[^\n]]+\\]:)";
1611 // Remove markdown symbols from the chunk selection.
1612 command.unwrap = function(chunk){
1613 var txt = new re("([^\\n])\\n(?!(\\n|" + command.prefixes + "))", "g");
1614 chunk.selection = chunk.selection.replace(txt, "$1 $2");
1617 command.wrap = function(chunk, len){
1618 command.unwrap(chunk);
1619 var regex = new re("(.{1," + len + "})( +|$\\n?)", "gm");
1621 chunk.selection = chunk.selection.replace(regex, function(line, marked){
1622 if (new re("^" + command.prefixes, "").test(line)) {
1625 return marked + "\n";
1628 chunk.selection = chunk.selection.replace(/\s+$/, "");
1631 command.doBold = function(chunk, postProcessing, useDefaultText){
1632 return command.doBorI(chunk, 2, "strong text");
1635 command.doItalic = function(chunk, postProcessing, useDefaultText){
1636 return command.doBorI(chunk, 1, "emphasized text");
1639 // chunk: The selected region that will be enclosed with */**
1640 // nStars: 1 for italics, 2 for bold
1641 // insertText: If you just click the button without highlighting text, this gets inserted
1642 command.doBorI = function(chunk, nStars, insertText){
1644 // Get rid of whitespace and fix up newlines.
1645 chunk.trimWhitespace();
1646 chunk.selection = chunk.selection.replace(/\n{2,}/g, "\n");
1648 // Look for stars before and after. Is the chunk already marked up?
1649 chunk.before.search(/(\**$)/);
1650 var starsBefore = re.$1;
1652 chunk.after.search(/(^\**)/);
1653 var starsAfter = re.$1;
1655 var prevStars = Math.min(starsBefore.length, starsAfter.length);
1657 // Remove stars if we have to since the button acts as a toggle.
1658 if ((prevStars >= nStars) && (prevStars != 2 || nStars != 1)) {
1659 chunk.before = chunk.before.replace(re("[*]{" + nStars + "}$", ""), "");
1660 chunk.after = chunk.after.replace(re("^[*]{" + nStars + "}", ""), "");
1662 else if (!chunk.selection && starsAfter) {
1663 // It's not really clear why this code is necessary. It just moves
1664 // some arbitrary stuff around.
1665 chunk.after = chunk.after.replace(/^([*_]*)/, "");
1666 chunk.before = chunk.before.replace(/(\s?)$/, "");
1667 var whitespace = re.$1;
1668 chunk.before = chunk.before + starsAfter + whitespace;
1672 // In most cases, if you don't have any selected text and click the button
1673 // you'll get a selected, marked up region with the default text inserted.
1674 if (!chunk.selection && !starsAfter) {
1675 chunk.selection = insertText;
1678 // Add the true markup.
1679 var markup = nStars <= 1 ? "*" : "**"; // shouldn't the test be = ?
1680 chunk.before = chunk.before + markup;
1681 chunk.after = markup + chunk.after;
1687 command.stripLinkDefs = function(text, defsToAdd){
1689 text = text.replace(/^[ ]{0,3}\[(\d+)\]:[ \t]*\n?[ \t]*<?(\S+?)>?[ \t]*\n?[ \t]*(?:(\n*)["(](.+?)[")][ \t]*)?(?:\n+|$)/gm,
1690 function(totalMatch, id, link, newlines, title){
1691 defsToAdd[id] = totalMatch.replace(/\s*$/, "");
1693 // Strip the title and return that separately.
1694 defsToAdd[id] = totalMatch.replace(/["(](.+?)[")]$/, "");
1695 return newlines + title;
1703 command.addLinkDef = function(chunk, linkDef){
1705 var refNumber = 0; // The current reference number
1706 var defsToAdd = {}; //
1707 // Start with a clean slate by removing all previous link definitions.
1708 chunk.before = command.stripLinkDefs(chunk.before, defsToAdd);
1709 chunk.selection = command.stripLinkDefs(chunk.selection, defsToAdd);
1710 chunk.after = command.stripLinkDefs(chunk.after, defsToAdd);
1713 var regex = /(\[)((?:\[[^\]]*\]|[^\[\]])*)(\][ ]?(?:\n[ ]*)?\[)(\d+)(\])/g;
1717 var addDefNumber = function(def){
1719 def = def.replace(/^[ ]{0,3}\[(\d+)\]:/, " [" + refNumber + "]:");
1724 // a) the recursive call to getLink cannot go infinite, because by definition
1725 // of regex, inner is always a proper substring of wholeMatch, and
1726 // b) more than one level of nesting is neither supported by the regex
1727 // nor making a lot of sense (the only use case for nesting is a linked image)
1728 var getLink = function (wholeMatch, before, inner, afterInner, id, end) {
1729 inner = inner.replace(regex, getLink);
1730 if (defsToAdd[id]) {
1731 addDefNumber(defsToAdd[id]);
1732 return before + inner + afterInner + refNumber + end;
1738 chunk.before = chunk.before.replace(regex, getLink);
1741 addDefNumber(linkDef);
1744 chunk.selection = chunk.selection.replace(regex, getLink);
1747 var refOut = refNumber;
1749 chunk.after = chunk.after.replace(regex, getLink);
1752 chunk.after = chunk.after.replace(/\n*$/, "");
1755 chunk.selection = chunk.selection.replace(/\n*$/, "");
1758 chunk.after += "\n\n" + defs;
1763 command.doLinkOrImage = function(chunk, postProcessing, isImage){
1765 chunk.trimWhitespace();
1766 chunk.findTags(/\s*!?\[/, /\][ ]?(?:\n[ ]*)?(\[.*?\])?/);
1768 if (chunk.endTag.length > 1) {
1770 chunk.startTag = chunk.startTag.replace(/!?\[/, "");
1772 command.addLinkDef(chunk, null);
1777 if (/\n\n/.test(chunk.selection)) {
1778 command.addLinkDef(chunk, null);
1782 // The function to be executed when you enter a link and press OK or Cancel.
1783 // Marks up the link and adds the ref.
1784 var makeLinkMarkdown = function(link){
1786 if (link !== null) {
1788 chunk.startTag = chunk.endTag = "";
1789 var linkDef = " [999]: " + link;
1791 var num = command.addLinkDef(chunk, linkDef);
1792 chunk.startTag = isImage ? "![" : "[";
1793 chunk.endTag = "][" + num + "]";
1795 if (!chunk.selection) {
1797 chunk.selection = "alt text";
1800 chunk.selection = "link text";
1808 util.prompt(imageDialogText, imageDefaultText, makeLinkMarkdown);
1811 util.prompt(linkDialogText, linkDefaultText, makeLinkMarkdown);
1817 util.makeAPI = function(){
1819 wmd.wmd.editor = wmd.editor;
1820 wmd.wmd.previewManager = wmd.previewManager;
1823 util.startEditor = function(){
1825 if (wmd.wmd_env.autostart === false) {
1830 var edit; // The editor (buttons + input + outputs) - the main object.
1831 var previewMgr; // The preview manager.
1833 // Fired after the page has fully loaded.
1834 var loadListener = function(){
1836 wmd.panels = new wmd.PanelCollection();
1838 previewMgr = new wmd.previewManager();
1839 var previewRefreshCallback = previewMgr.refresh;
1841 edit = new wmd.editor(previewRefreshCallback);
1843 previewMgr.refresh(true);
1847 util.addEvent(top, "load", loadListener);
1850 wmd.previewManager = function(){
1852 var managerObj = this;
1859 var maxDelay = 3000;
1860 var startType = "delayed"; // The other legal value is "manual"
1862 // Adds event listeners to elements and creates the input poller.
1863 var setupEvents = function(inputElem, listener){
1865 util.addEvent(inputElem, "input", listener);
1866 inputElem.onpaste = listener;
1867 inputElem.ondrop = listener;
1869 util.addEvent(inputElem, "keypress", listener);
1870 util.addEvent(inputElem, "keydown", listener);
1871 // previewPollInterval is set at the top of this file.
1872 poller = new wmd.inputPoller(listener, previewPollInterval);
1875 var getDocScrollTop = function(){
1879 if (top.innerHeight) {
1880 result = top.pageYOffset;
1883 if (doc.documentElement && doc.documentElement.scrollTop) {
1884 result = doc.documentElement.scrollTop;
1888 result = doc.body.scrollTop;
1894 var makePreviewHtml = function(){
1896 // If there are no registered preview and output panels
1897 // there is nothing to do.
1898 if (!wmd.panels.preview && !wmd.panels.output) {
1902 var text = wmd.panels.input.value;
1903 if (text && text == oldInputText) {
1904 return; // Input text hasn't changed.
1907 oldInputText = text;
1910 var prevTime = new Date().getTime();
1912 if (!converter && wmd.showdown) {
1913 converter = new wmd.showdown.converter();
1917 text = converter.makeHtml(text);
1920 // Calculate the processing time of the HTML creation.
1921 // It's used as the delay time in the event listener.
1922 var currTime = new Date().getTime();
1923 elapsedTime = currTime - prevTime;
1925 pushPreviewHtml(text);
1929 // setTimeout is already used. Used as an event listener.
1930 var applyTimeout = function(){
1933 top.clearTimeout(timeout);
1934 timeout = undefined;
1937 if (startType !== "manual") {
1941 if (startType === "delayed") {
1942 delay = elapsedTime;
1945 if (delay > maxDelay) {
1948 timeout = top.setTimeout(makePreviewHtml, delay);
1952 var getScaleFactor = function(panel){
1953 if (panel.scrollHeight <= panel.clientHeight) {
1956 return panel.scrollTop / (panel.scrollHeight - panel.clientHeight);
1959 var setPanelScrollTops = function(){
1961 if (wmd.panels.preview) {
1962 wmd.panels.preview.scrollTop = (wmd.panels.preview.scrollHeight - wmd.panels.preview.clientHeight) * getScaleFactor(wmd.panels.preview);
1966 if (wmd.panels.output) {
1967 wmd.panels.output.scrollTop = (wmd.panels.output.scrollHeight - wmd.panels.output.clientHeight) * getScaleFactor(wmd.panels.output);
1972 this.refresh = function(requiresRefresh){
1974 if (requiresRefresh) {
1983 this.processingTime = function(){
1988 this.output = function(){
1992 // The mode can be "manual" or "delayed"
1993 this.setUpdateMode = function(mode){
1995 managerObj.refresh();
1998 var isFirstTimeFilled = true;
2000 var pushPreviewHtml = function(text){
2002 var emptyTop = position.getTop(wmd.panels.input) - getDocScrollTop();
2004 // Send the encoded HTML to the output textarea/div.
2005 if (wmd.panels.output) {
2006 // The value property is only defined if the output is a textarea.
2007 if (wmd.panels.output.value !== undefined) {
2008 wmd.panels.output.value = text;
2009 wmd.panels.output.readOnly = true;
2011 // Otherwise we are just replacing the text in a div.
2012 // Send the HTML wrapped in <pre><code>
2014 var newText = text.replace(/&/g, "&");
2015 newText = newText.replace(/</g, "<");
2016 wmd.panels.output.innerHTML = "<pre><code>" + newText + "</code></pre>";
2020 if (wmd.panels.preview) {
2021 wmd.panels.preview.innerHTML = text;
2024 setPanelScrollTops();
2026 if (isFirstTimeFilled) {
2027 isFirstTimeFilled = false;
2031 var fullTop = position.getTop(wmd.panels.input) - getDocScrollTop();
2034 top.setTimeout(function(){
2035 top.scrollBy(0, fullTop - emptyTop);
2039 top.scrollBy(0, fullTop - emptyTop);
2043 var init = function(){
2045 setupEvents(wmd.panels.input, applyTimeout);
2048 if (wmd.panels.preview) {
2049 wmd.panels.preview.scrollTop = 0;
2051 if (wmd.panels.output) {
2052 wmd.panels.output.scrollTop = 0;
2056 this.destroy = function(){
2065 // Moves the cursor to the next line and continues lists, quotes and code.
2066 command.doAutoindent = function(chunk, postProcessing, useDefaultText){
2068 chunk.before = chunk.before.replace(/(\n|^)[ ]{0,3}([*+-]|\d+[.])[ \t]*\n$/, "\n\n");
2069 chunk.before = chunk.before.replace(/(\n|^)[ ]{0,3}>[ \t]*\n$/, "\n\n");
2070 chunk.before = chunk.before.replace(/(\n|^)[ \t]+\n$/, "\n\n");
2072 useDefaultText = false;
2074 if(/(\n|^)[ ]{0,3}([*+-])[ \t]+.*\n$/.test(chunk.before)){
2076 command.doList(chunk, postProcessing, false, true);
2079 if(/(\n|^)[ ]{0,3}(\d+[.])[ \t]+.*\n$/.test(chunk.before)){
2081 command.doList(chunk, postProcessing, true, true);
2084 if(/(\n|^)[ ]{0,3}>[ \t]+.*\n$/.test(chunk.before)){
2085 if(command.doBlockquote){
2086 command.doBlockquote(chunk, postProcessing, useDefaultText);
2089 if(/(\n|^)(\t|[ ]{4,}).*\n$/.test(chunk.before)){
2091 command.doCode(chunk, postProcessing, useDefaultText);
2096 command.doBlockquote = function(chunk, postProcessing, useDefaultText){
2098 chunk.selection = chunk.selection.replace(/^(\n*)([^\r]+?)(\n*)$/,
2099 function(totalMatch, newlinesBefore, text, newlinesAfter){
2100 chunk.before += newlinesBefore;
2101 chunk.after = newlinesAfter + chunk.after;
2105 chunk.before = chunk.before.replace(/(>[ \t]*)$/,
2106 function(totalMatch, blankLine){
2107 chunk.selection = blankLine + chunk.selection;
2111 var defaultText = useDefaultText ? "Blockquote" : "";
2112 chunk.selection = chunk.selection.replace(/^(\s|>)+$/ ,"");
2113 chunk.selection = chunk.selection || defaultText;
2115 // The original code uses a regular expression to find out how much of the
2116 // text *directly before* the selection already was a blockquote:
2119 chunk.before = chunk.before.replace(/\n?$/,"\n");
2121 chunk.before = chunk.before.replace(/(((\n|^)(\n[ \t]*)*>(.+\n)*.*)+(\n[ \t]*)*$)/,
2122 function (totalMatch) {
2123 chunk.startTag = totalMatch;
2127 // This comes down to:
2128 // Go backwards as many lines a possible, such that each line
2129 // a) starts with ">", or
2130 // b) is almost empty, except for whitespace, or
2131 // c) is preceeded by an unbroken chain of non-empty lines
2132 // leading up to a line that starts with ">" and at least one more character
2134 // d) at least one line fulfills a)
2136 // Since this is essentially a backwards-moving regex, it's susceptible to
2137 // catstrophic backtracking and can cause the browser to hang;
2138 // see e.g. http://meta.stackoverflow.com/questions/9807.
2140 // Hence we replaced this by a simple state machine that just goes through the
2141 // lines and checks for a), b), and c).
2146 var lines = chunk.before.replace(/\n$/, "").split("\n");
2147 var inChain = false;
2148 for (var i in lines) {
2151 inChain = inChain && line.length > 0; // c) any non-empty line continues the chain
2152 if (/^>/.test(line)) { // a)
2154 if (!inChain && line.length > 1) // c) any line that starts with ">" and has at least one more character starts the chain
2156 } else if (/^[ \t]*$/.test(line)) { // b)
2159 good = inChain; // c) the line is not empty and does not start with ">", so it matches if and only if we're in the chain
2162 match += line + "\n";
2164 leftOver += match + line;
2168 if (!/(^|\n)>/.test(match)) { // d)
2174 chunk.startTag = match;
2175 chunk.before = leftOver;
2180 chunk.after = chunk.after.replace(/^\n?/,"\n");
2183 chunk.after = chunk.after.replace(/^(((\n|^)(\n[ \t]*)*>(.+\n)*.*)+(\n[ \t]*)*)/,
2184 function(totalMatch){
2185 chunk.endTag = totalMatch;
2189 var replaceBlanksInTags = function(useBracket){
2191 var replacement = useBracket ? "> " : "";
2194 chunk.startTag = chunk.startTag.replace(/\n((>|\s)*)\n$/,
2195 function(totalMatch, markdown){
2196 return "\n" + markdown.replace(/^[ ]{0,3}>?[ \t]*$/gm, replacement) + "\n";
2200 chunk.endTag = chunk.endTag.replace(/^\n((>|\s)*)\n/,
2201 function(totalMatch, markdown){
2202 return "\n" + markdown.replace(/^[ ]{0,3}>?[ \t]*$/gm, replacement) + "\n";
2207 if(/^(?![ ]{0,3}>)/m.test(chunk.selection)){
2208 command.wrap(chunk, wmd.wmd_env.lineLength - 2);
2209 chunk.selection = chunk.selection.replace(/^/gm, "> ");
2210 replaceBlanksInTags(true);
2211 chunk.addBlankLines();
2214 chunk.selection = chunk.selection.replace(/^[ ]{0,3}> ?/gm, "");
2215 command.unwrap(chunk);
2216 replaceBlanksInTags(false);
2218 if(!/^(\n|^)[ ]{0,3}>/.test(chunk.selection) && chunk.startTag){
2219 chunk.startTag = chunk.startTag.replace(/\n{0,2}$/, "\n\n");
2222 if(!/(\n|^)[ ]{0,3}>.*$/.test(chunk.selection) && chunk.endTag){
2223 chunk.endTag=chunk.endTag.replace(/^\n{0,2}/, "\n\n");
2227 if(!/\n/.test(chunk.selection)){
2228 chunk.selection = chunk.selection.replace(/^(> *)/,
2229 function(wholeMatch, blanks){
2230 chunk.startTag += blanks;
2236 command.doCode = function(chunk, postProcessing, useDefaultText){
2238 var hasTextBefore = /\S[ ]*$/.test(chunk.before);
2239 var hasTextAfter = /^[ ]*\S/.test(chunk.after);
2241 // Use 'four space' markdown if the selection is on its own
2242 // line or is multiline.
2243 if((!hasTextAfter && !hasTextBefore) || /\n/.test(chunk.selection)){
2245 chunk.before = chunk.before.replace(/[ ]{4}$/,
2246 function(totalMatch){
2247 chunk.selection = totalMatch + chunk.selection;
2251 var nLinesBefore = 1;
2252 var nLinesAfter = 1;
2255 if(/\n(\t|[ ]{4,}).*\n$/.test(chunk.before) || chunk.after === ""){
2258 if(/^\n(\t|[ ]{4,})/.test(chunk.after)){
2259 nLinesAfter = 0; // This needs to happen on line 1
2262 chunk.addBlankLines(nLinesBefore, nLinesAfter);
2264 if(!chunk.selection){
2265 chunk.startTag = " ";
2266 chunk.selection = useDefaultText ? "enter code here" : "";
2269 if(/^[ ]{0,3}\S/m.test(chunk.selection)){
2270 chunk.selection = chunk.selection.replace(/^/gm, " ");
2273 chunk.selection = chunk.selection.replace(/^[ ]{4}/gm, "");
2278 // Use backticks (`) to delimit the code block.
2280 chunk.trimWhitespace();
2281 chunk.findTags(/`/, /`/);
2283 if(!chunk.startTag && !chunk.endTag){
2284 chunk.startTag = chunk.endTag="`";
2285 if(!chunk.selection){
2286 chunk.selection = useDefaultText ? "enter code here" : "";
2289 else if(chunk.endTag && !chunk.startTag){
2290 chunk.before += chunk.endTag;
2294 chunk.startTag = chunk.endTag="";
2299 command.doList = function(chunk, postProcessing, isNumberedList, useDefaultText){
2301 // These are identical except at the very beginning and end.
2302 // Should probably use the regex extension function to make this clearer.
2303 var previousItemsRegex = /(\n|^)(([ ]{0,3}([*+-]|\d+[.])[ \t]+.*)(\n.+|\n{2,}([*+-].*|\d+[.])[ \t]+.*|\n{2,}[ \t]+\S.*)*)\n*$/;
2304 var nextItemsRegex = /^\n*(([ ]{0,3}([*+-]|\d+[.])[ \t]+.*)(\n.+|\n{2,}([*+-].*|\d+[.])[ \t]+.*|\n{2,}[ \t]+\S.*)*)\n*/;
2306 // The default bullet is a dash but others are possible.
2307 // This has nothing to do with the particular HTML bullet,
2308 // it's just a markdown bullet.
2311 // The number in a numbered list.
2314 // Get the item prefix - e.g. " 1. " for a numbered list, " - " for a bulleted list.
2315 var getItemPrefix = function(){
2318 prefix = " " + num + ". ";
2322 prefix = " " + bullet + " ";
2327 // Fixes the prefixes of the other list items.
2328 var getPrefixedItem = function(itemText){
2330 // The numbering flag is unset when called by autoindent.
2331 if(isNumberedList === undefined){
2332 isNumberedList = /^\s*\d/.test(itemText);
2335 // Renumber/bullet the list element.
2336 itemText = itemText.replace(/^[ ]{0,3}([*+-]|\d+[.])\s/gm,
2338 return getItemPrefix();
2344 chunk.findTags(/(\n|^)*[ ]{0,3}([*+-]|\d+[.])\s+/, null);
2346 if(chunk.before && !/\n$/.test(chunk.before) && !/^\n/.test(chunk.startTag)){
2347 chunk.before += chunk.startTag;
2348 chunk.startTag = "";
2353 var hasDigits = /\d+[.]/.test(chunk.startTag);
2354 chunk.startTag = "";
2355 chunk.selection = chunk.selection.replace(/\n[ ]{4}/g, "\n");
2356 command.unwrap(chunk);
2357 chunk.addBlankLines();
2360 // Have to renumber the bullet points if this is a numbered list.
2361 chunk.after = chunk.after.replace(nextItemsRegex, getPrefixedItem);
2363 if(isNumberedList == hasDigits){
2368 var nLinesBefore = 1;
2370 chunk.before = chunk.before.replace(previousItemsRegex,
2372 if(/^\s*([*+-])/.test(itemText)){
2375 nLinesBefore = /[^\n]\n\n[^\n]/.test(itemText) ? 1 : 0;
2376 return getPrefixedItem(itemText);
2379 if(!chunk.selection){
2380 chunk.selection = useDefaultText ? "List item" : " ";
2383 var prefix = getItemPrefix();
2385 var nLinesAfter = 1;
2387 chunk.after = chunk.after.replace(nextItemsRegex,
2389 nLinesAfter = /[^\n]\n\n[^\n]/.test(itemText) ? 1 : 0;
2390 return getPrefixedItem(itemText);
2393 chunk.trimWhitespace(true);
2394 chunk.addBlankLines(nLinesBefore, nLinesAfter, true);
2395 chunk.startTag = prefix;
2396 var spaces = prefix.replace(/./g, " ");
2397 command.wrap(chunk, wmd.wmd_env.lineLength - spaces.length);
2398 chunk.selection = chunk.selection.replace(/\n/g, "\n" + spaces);
2402 command.doHeading = function(chunk, postProcessing, useDefaultText){
2404 // Remove leading/trailing whitespace and reduce internal spaces to single spaces.
2405 chunk.selection = chunk.selection.replace(/\s+/g, " ");
2406 chunk.selection = chunk.selection.replace(/(^\s+|\s+$)/g, "");
2408 // If we clicked the button with no selected text, we just
2409 // make a level 2 hash header around some default text.
2410 if(!chunk.selection){
2411 chunk.startTag = "## ";
2412 chunk.selection = "Heading";
2413 chunk.endTag = " ##";
2417 var headerLevel = 0; // The existing header level of the selected text.
2419 // Remove any existing hash heading markdown and save the header level.
2420 chunk.findTags(/#+[ ]*/, /[ ]*#+/);
2421 if(/#+/.test(chunk.startTag)){
2422 headerLevel = re.lastMatch.length;
2424 chunk.startTag = chunk.endTag = "";
2426 // Try to get the current header level by looking for - and = in the line
2427 // below the selection.
2428 chunk.findTags(null, /\s?(-+|=+)/);
2429 if(/=+/.test(chunk.endTag)){
2432 if(/-+/.test(chunk.endTag)){
2436 // Skip to the next line so we can create the header markdown.
2437 chunk.startTag = chunk.endTag = "";
2438 chunk.addBlankLines(1, 1);
2440 // We make a level 2 header if there is no current header.
2441 // If there is a header level, we substract one from the header level.
2442 // If it's already a level 1 header, it's removed.
2443 var headerLevelToCreate = headerLevel == 0 ? 2 : headerLevel - 1;
2445 if(headerLevelToCreate > 0){
2447 // The button only creates level 1 and 2 underline headers.
2448 // Why not have it iterate over hash header levels? Wouldn't that be easier and cleaner?
2449 var headerChar = headerLevelToCreate >= 2 ? "-" : "=";
2450 var len = chunk.selection.length;
2451 if(len > wmd.wmd_env.lineLength){
2452 len = wmd.wmd_env.lineLength;
2454 chunk.endTag = "\n";
2456 chunk.endTag += headerChar;
2461 command.doHorizontalRule = function(chunk, postProcessing, useDefaultText){
2462 chunk.startTag = "----------\n";
2463 chunk.selection = "";
2464 chunk.addBlankLines(2, 1, true);
2469 Attacklab.wmd_env = {};
2470 Attacklab.account_options = {};
2471 Attacklab.wmd_defaults = {version:1, output:"HTML", lineLength:40, delayLoad:false};
2475 Attacklab.wmd = function()
2477 Attacklab.loadEnv = function()
2479 var mergeEnv = function(env)
2488 Attacklab.wmd_env[key] = env[key];
2492 mergeEnv(Attacklab.wmd_defaults);
2493 mergeEnv(Attacklab.account_options);
2494 mergeEnv(top["wmd_options"]);
2495 Attacklab.full = true;
2497 var defaultButtons = "bold italic link blockquote code image ol ul heading hr";
2498 Attacklab.wmd_env.buttons = Attacklab.wmd_env.buttons || defaultButtons;
2500 Attacklab.loadEnv();
2505 Attacklab.wmdBase();
2506 Attacklab.Util.startEditor();