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();
31 imageUrl.attr('value', appUrl + fileURL);
35 error: function (data, status, e)
45 var Attacklab = Attacklab || {};
47 Attacklab.wmdBase = function(){
49 // A few handy aliases for readability.
50 var wmd = top.Attacklab;
51 var doc = top.document;
53 var nav = top.navigator;
62 var position = wmd.Position;
63 var command = wmd.Command;
64 var global = wmd.Global;
67 // Used to work around some browser bugs where we can't use feature testing.
68 global.isIE = /msie/.test(nav.userAgent.toLowerCase());
69 global.isIE_5or6 = /msie 6/.test(nav.userAgent.toLowerCase()) || /msie 5/.test(nav.userAgent.toLowerCase());
70 global.isIE_7plus = global.isIE && !global.isIE_5or6;
71 global.isOpera = /opera/.test(nav.userAgent.toLowerCase());
72 global.isKonqueror = /konqueror/.test(nav.userAgent.toLowerCase());
75 // -------------------------------------------------------------------
76 // YOUR CHANGES GO HERE
78 // I've tried to localize the things you are likely to change to
80 // -------------------------------------------------------------------
82 // The text that appears on the upper part of the dialog box when
84 var imageDialogText = "<p style='margin-top: 0px'>" + $.i18n._('enter image url') + "</p>";
85 var linkDialogText = "<p style='margin-top: 0px'>" + $.i18n._('enter url') + "</p>";
86 var uploadImageHTML ="<div>" + $.i18n._('upload image') + "</div>" +
87 "<input type=\"file\" name=\"file-upload\" id=\"file-upload\" size=\"26\" "+
88 "onchange=\"return ajaxFileUpload($('#image-url'));\"/><br>" +
89 "<img id=\"loading\" src=\"" + mediaUrl("media/images/indicator.gif") + "\" style=\"display:none;\"/>";
91 // The default text that appears in the dialog input box when entering
93 var imageDefaultText = "http://";
94 var linkDefaultText = "http://";
96 // The location of your button images relative to the base directory.
97 var imageDirectory = "images/";
99 // Some intervals in ms. These can be adjusted to reduce the control's load.
100 var previewPollInterval = 500;
101 var pastePollInterval = 100;
103 // The link and title for the help button
104 var helpLink = "http://wmd-editor.com/";
105 var helpHoverTitle = "WMD website";
106 var helpTarget = "_blank";
108 // -------------------------------------------------------------------
109 // END OF YOUR CHANGES
110 // -------------------------------------------------------------------
112 // A collection of the important regions on the page.
113 // Cached so we don't have to keep traversing the DOM.
114 wmd.PanelCollection = function(){
115 this.buttonBar = doc.getElementById("wmd-button-bar");
116 this.preview = doc.getElementById("previewer");
117 this.output = doc.getElementById("wmd-output");
118 this.input = doc.getElementById("editor");
121 // This PanelCollection object can't be filled until after the page
123 wmd.panels = undefined;
125 // Internet explorer has problems with CSS sprite buttons that use HTML
126 // lists. When you click on the background image "button", IE will
127 // select the non-existent link text and discard the selection in the
128 // textarea. The solution to this is to cache the textarea selection
129 // on the button's mousedown event and set a flag. In the part of the
130 // code where we need to grab the selection, we check for the flag
131 // and, if it's set, use the cached area instead of querying the
134 // This ONLY affects Internet Explorer (tested on versions 6, 7
135 // and 8) and ONLY on button clicks. Keyboard shortcuts work
136 // normally since the focus never leaves the textarea.
137 wmd.ieCachedRange = null; // cached textarea selection
138 wmd.ieRetardedClick = false; // flag
140 // Returns true if the DOM element is visible, false if it's hidden.
141 // Checks if display is anything other than none.
142 util.isVisible = function (elem) {
144 if (window.getComputedStyle) {
146 return window.getComputedStyle(elem, null).getPropertyValue("display") !== "none";
148 else if (elem.currentStyle) {
150 return elem.currentStyle["display"] !== "none";
155 // Adds a listener callback to a DOM element which is fired on a specified
157 util.addEvent = function(elem, event, listener){
158 if (elem.attachEvent) {
159 // IE only. The "on" is mandatory.
160 elem.attachEvent("on" + event, listener);
164 elem.addEventListener(event, listener, false);
169 // Removes a listener callback from a DOM element which is fired on a specified
171 util.removeEvent = function(elem, event, listener){
172 if (elem.detachEvent) {
173 // IE only. The "on" is mandatory.
174 elem.detachEvent("on" + event, listener);
178 elem.removeEventListener(event, listener, false);
182 // Converts \r\n and \r to \n.
183 util.fixEolChars = function(text){
184 text = text.replace(/\r\n/g, "\n");
185 text = text.replace(/\r/g, "\n");
189 // Extends a regular expression. Returns a new RegExp
190 // using pre + regex + post as the expression.
191 // Used in a few functions where we have a base
192 // expression and we want to pre- or append some
193 // conditions to it (e.g. adding "$" to the end).
194 // The flags are unchanged.
196 // regex is a RegExp, pre and post are strings.
197 util.extendRegExp = function(regex, pre, post){
199 if (pre === null || pre === undefined)
203 if(post === null || post === undefined)
208 var pattern = regex.toString();
211 // Replace the flags with empty space and store them.
212 // Technically, this can match incorrect flags like "gmm".
213 var result = pattern.match(/\/([gim]*)$/);
214 if (result === null) {
221 // Remove the flags and slash delimiters from the regular expression.
222 pattern = pattern.replace(/(^\/|\/[gim]*$)/g, "");
223 pattern = pre + pattern + post;
225 return new RegExp(pattern, flags);
229 // Sets the image for a button passed to the WMD editor.
230 // Returns a new element with the image attached.
231 // Adds several style properties to the image.
232 util.createImage = function(img){
234 var imgPath = imageDirectory + img;
236 var elem = doc.createElement("img");
237 elem.className = "wmd-button";
244 // This simulates a modal dialog box and asks for the URL when you
245 // click the hyperlink or image buttons.
247 // text: The html for the input box.
248 // defaultInputText: The default value that appears in the input box.
249 // makeLinkMarkdown: The function which is executed when the prompt is dismissed, either via OK or Cancel
250 util.prompt = function(text, defaultInputText, makeLinkMarkdown){
252 // These variables need to be declared at this level since they are used
253 // in multiple functions.
254 var dialog; // The dialog box.
255 var background; // The background beind the dialog box.
256 var input; // The text box where you enter the hyperlink.
258 // The dialog box type(0: Link, 1: Image)
259 if(arguments.length == 4){
263 if (defaultInputText === undefined) {
264 defaultInputText = "";
267 // Used as a keydown event handler. Esc dismisses the prompt.
268 // Key code 27 is ESC.
269 var checkEscape = function(key){
270 var code = (key.charCode || key.keyCode);
276 // Dismisses the hyperlink input box.
277 // isCancel is true if we don't care about the input text.
278 // isCancel is false if we are going to keep the text.
279 var close = function(isCancel){
280 util.removeEvent(doc.body, "keydown", checkEscape);
281 var text = input.value;
287 // Fixes common pasting errors.
288 text = text.replace('http://http://', 'http://');
289 text = text.replace('http://https://', 'https://');
290 text = text.replace('http://ftp://', 'ftp://');
292 if (text.indexOf('http://') === -1 && text.indexOf('ftp://') === -1 && text.indexOf('https://') === -1) {
293 text = 'http://' + text;
297 dialog.parentNode.removeChild(dialog);
298 background.parentNode.removeChild(background);
299 makeLinkMarkdown(text);
303 // Creates the background behind the hyperlink text entry box.
304 // Most of this has been moved to CSS but the div creation and
305 // browser-specific hacks remain here.
306 var createBackground = function(){
308 background = doc.createElement("div");
309 background.className = "wmd-prompt-background";
310 style = background.style;
311 style.position = "absolute";
314 style.zIndex = "1000";
316 // Some versions of Konqueror don't support transparent colors
317 // so we make the whole window transparent.
319 // Is this necessary on modern konqueror browsers?
320 if (global.isKonqueror){
321 style.backgroundColor = "transparent";
323 else if (global.isIE){
324 style.filter = "alpha(opacity=50)";
327 style.opacity = "0.5";
330 var pageSize = position.getPageSize();
331 style.height = pageSize[1] + "px";
334 style.left = doc.documentElement.scrollLeft;
335 style.width = doc.documentElement.clientWidth;
339 style.width = "100%";
342 doc.body.appendChild(background);
345 // Create the text input box form/window.
346 var createDialog = function(){
348 // The main dialog box.
349 dialog = doc.createElement("div");
350 dialog.className = "wmd-prompt-dialog";
351 dialog.style.padding = "10px;";
352 dialog.style.position = "fixed";
353 dialog.style.width = "400px";
354 dialog.style.zIndex = "1001";
357 var question = doc.createElement("div");
358 question.innerHTML = text;
359 question.style.padding = "5px";
360 dialog.appendChild(question);
362 // The web form container for the text box and buttons.
363 var form = doc.createElement("form");
364 form.onsubmit = function(){ return close(false); };
368 style.cssFloat = "left";
369 style.width = "100%";
370 style.textAlign = "center";
371 style.position = "relative";
372 dialog.appendChild(form);
374 // The input text box
375 input = doc.createElement("input");
376 input.id = "image-url";
378 input.value = defaultInputText;
380 style.display = "block";
382 style.marginLeft = style.marginRight = "auto";
383 form.appendChild(input);
385 // The upload file input
386 var upload = doc.createElement("div");
387 upload.innerHTML = uploadImageHTML;
388 upload.style.padding = "5px";
389 form.appendChild(upload);
392 var okButton = doc.createElement("input");
393 okButton.type = "button";
394 okButton.onclick = function(){ return close(false); };
395 okButton.value = "OK";
396 style = okButton.style;
397 style.margin = "10px";
398 style.display = "inline";
403 var cancelButton = doc.createElement("input");
404 cancelButton.type = "button";
405 cancelButton.onclick = function(){ return close(true); };
406 cancelButton.value = "Cancel";
407 style = cancelButton.style;
408 style.margin = "10px";
409 style.display = "inline";
412 // The order of these buttons is different on macs.
413 if (/mac/.test(nav.platform.toLowerCase())) {
414 form.appendChild(cancelButton);
415 form.appendChild(okButton);
418 form.appendChild(okButton);
419 form.appendChild(cancelButton);
422 util.addEvent(doc.body, "keydown", checkEscape);
423 dialog.style.top = "50%";
424 dialog.style.left = "50%";
425 dialog.style.display = "block";
426 if(global.isIE_5or6){
427 dialog.style.position = "absolute";
428 dialog.style.top = doc.documentElement.scrollTop + 200 + "px";
429 dialog.style.left = "50%";
431 doc.body.appendChild(dialog);
433 // This has to be done AFTER adding the dialog to the form if you
434 // want it to be centered.
435 dialog.style.marginTop = -(position.getHeight(dialog) / 2) + "px";
436 dialog.style.marginLeft = -(position.getWidth(dialog) / 2) + "px";
442 // Why is this in a zero-length timeout?
443 // Is it working around a browser bug?
444 top.setTimeout(function(){
448 var defTextLen = defaultInputText.length;
449 if (input.selectionStart !== undefined) {
450 input.selectionStart = 0;
451 input.selectionEnd = defTextLen;
453 else if (input.createTextRange) {
454 var range = input.createTextRange();
455 range.collapse(false);
456 range.moveStart("character", -defTextLen);
457 range.moveEnd("character", defTextLen);
467 // The assignment in the while loop makes jslint cranky.
468 // I'll change it to a better loop later.
469 position.getTop = function(elem, isInner){
470 var result = elem.offsetTop;
472 while (elem = elem.offsetParent) {
473 result += elem.offsetTop;
479 position.getHeight = function (elem) {
480 return elem.offsetHeight || elem.scrollHeight;
483 position.getWidth = function (elem) {
484 return elem.offsetWidth || elem.scrollWidth;
487 position.getPageSize = function(){
489 var scrollWidth, scrollHeight;
490 var innerWidth, innerHeight;
492 // It's not very clear which blocks work with which browsers.
493 if(self.innerHeight && self.scrollMaxY){
494 scrollWidth = doc.body.scrollWidth;
495 scrollHeight = self.innerHeight + self.scrollMaxY;
497 else if(doc.body.scrollHeight > doc.body.offsetHeight){
498 scrollWidth = doc.body.scrollWidth;
499 scrollHeight = doc.body.scrollHeight;
502 scrollWidth = doc.body.offsetWidth;
503 scrollHeight = doc.body.offsetHeight;
506 if(self.innerHeight){
508 innerWidth = self.innerWidth;
509 innerHeight = self.innerHeight;
511 else if(doc.documentElement && doc.documentElement.clientHeight){
512 // Some versions of IE (IE 6 w/ a DOCTYPE declaration)
513 innerWidth = doc.documentElement.clientWidth;
514 innerHeight = doc.documentElement.clientHeight;
517 // Other versions of IE
518 innerWidth = doc.body.clientWidth;
519 innerHeight = doc.body.clientHeight;
522 var maxWidth = Math.max(scrollWidth, innerWidth);
523 var maxHeight = Math.max(scrollHeight, innerHeight);
524 return [maxWidth, maxHeight, innerWidth, innerHeight];
527 // Watches the input textarea, polling at an interval and runs
528 // a callback function if anything has changed.
529 wmd.inputPoller = function(callback, interval){
531 var pollerObj = this;
532 var inputArea = wmd.panels.input;
534 // Stored start, end and text. Used to see if there are changes to the input.
539 var killHandle; // Used to cancel monitoring on destruction.
540 // Checks to see if anything has changed in the textarea.
541 // If so, it runs the callback.
542 this.tick = function(){
544 if (!util.isVisible(inputArea)) {
548 // Update the selection start and end, text.
549 if (inputArea.selectionStart || inputArea.selectionStart === 0) {
550 var start = inputArea.selectionStart;
551 var end = inputArea.selectionEnd;
552 if (start != lastStart || end != lastEnd) {
556 if (markdown != inputArea.value) {
557 markdown = inputArea.value;
566 var doTickCallback = function(){
568 if (!util.isVisible(inputArea)) {
572 // If anything has changed, call the function.
573 if (pollerObj.tick()) {
578 // Set how often we poll the textarea for changes.
579 var assignInterval = function(){
580 // previewPollInterval is set at the top of the namespace.
581 killHandle = top.setInterval(doTickCallback, interval);
584 this.destroy = function(){
585 top.clearInterval(killHandle);
591 // Handles pushing and popping TextareaStates for undo/redo commands.
592 // I should rename the stack variables to list.
593 wmd.undoManager = function(callback){
596 var undoStack = []; // A stack of undo states
597 var stackPtr = 0; // The index of the current state
599 var lastState; // The last state
601 var timer; // The setTimeout handle for cancelling the timer
604 // Set the mode for later logic steps.
605 var setMode = function(newMode, noSave){
607 if (mode != newMode) {
614 if (!global.isIE || mode != "moving") {
615 timer = top.setTimeout(refreshState, 1);
618 inputStateObj = null;
622 var refreshState = function(){
623 inputStateObj = new wmd.TextareaState();
628 this.setCommandMode = function(){
631 timer = top.setTimeout(refreshState, 0);
634 this.canUndo = function(){
638 this.canRedo = function(){
639 if (undoStack[stackPtr + 1]) {
645 // Removes the last state and restores it.
646 this.undo = function(){
648 if (undoObj.canUndo()) {
650 // What about setting state -1 to null or checking for undefined?
655 undoStack[stackPtr] = new wmd.TextareaState();
656 undoStack[--stackPtr].restore();
665 wmd.panels.input.focus();
670 this.redo = function(){
672 if (undoObj.canRedo()) {
674 undoStack[++stackPtr].restore();
682 wmd.panels.input.focus();
686 // Push the input area state to the stack.
687 var saveState = function(){
689 var currState = inputStateObj || new wmd.TextareaState();
694 if (mode == "moving") {
696 lastState = currState;
701 if (undoStack[stackPtr - 1].text != lastState.text) {
702 undoStack[stackPtr++] = lastState;
706 undoStack[stackPtr++] = currState;
707 undoStack[stackPtr + 1] = null;
713 var handleCtrlYZ = function(event){
717 if (event.ctrlKey || event.metaKey) {
719 // IE and Opera do not support charCode.
720 var keyCode = event.charCode || event.keyCode;
721 var keyCodeChar = String.fromCharCode(keyCode);
723 switch (keyCodeChar) {
731 if (!event.shiftKey) {
743 if (event.preventDefault) {
744 event.preventDefault();
747 top.event.returnValue = false;
753 // Set the mode depending on what is going on in the input area.
754 var handleModeChange = function(event){
756 if (!event.ctrlKey && !event.metaKey) {
758 var keyCode = event.keyCode;
760 if ((keyCode >= 33 && keyCode <= 40) || (keyCode >= 63232 && keyCode <= 63235)) {
761 // 33 - 40: page up/dn and arrow keys
762 // 63232 - 63235: page up/dn and arrow keys on safari
765 else if (keyCode == 8 || keyCode == 46 || keyCode == 127) {
771 else if (keyCode == 13) {
775 else if (keyCode == 27) {
779 else if ((keyCode < 16 || keyCode > 20) && keyCode != 91) {
780 // 16-20 are shift, etc.
781 // 91: left window key
782 // I think this might be a little messed up since there are
783 // a lot of nonprinting keys above 20.
789 var setEventHandlers = function(){
791 util.addEvent(wmd.panels.input, "keypress", function(event){
794 if ((event.ctrlKey || event.metaKey) && (event.keyCode == 89 || event.keyCode == 90)) {
795 event.preventDefault();
799 var handlePaste = function(){
800 if (global.isIE || (inputStateObj && inputStateObj.text != wmd.panels.input.value)) {
801 if (timer == undefined) {
809 // pastePollInterval is specified at the beginning of this namespace.
810 poller = new wmd.inputPoller(handlePaste, pastePollInterval);
812 util.addEvent(wmd.panels.input, "keydown", handleCtrlYZ);
813 util.addEvent(wmd.panels.input, "keydown", handleModeChange);
815 util.addEvent(wmd.panels.input, "mousedown", function(){
818 wmd.panels.input.onpaste = handlePaste;
819 wmd.panels.input.ondrop = handlePaste;
822 var init = function(){
828 this.destroy = function(){
837 // I think my understanding of how the buttons and callbacks are stored in the array is incomplete.
838 wmd.editor = function(previewRefreshCallback){
840 if (!previewRefreshCallback) {
841 previewRefreshCallback = function(){};
844 var inputBox = wmd.panels.input;
846 var offsetHeight = 0;
853 var div; // This name is pretty ambiguous. I should rename this.
855 // Used to cancel recurring events from setInterval.
858 var undoMgr; // The undo manager
860 // Perform the button's action.
861 var doClick = function(button){
868 undoMgr.setCommandMode();
871 var state = new wmd.TextareaState();
877 var chunks = state.getChunks();
879 // Some commands launch a "modal" prompt dialog. Javascript
880 // can't really make a modal dialog box and the WMD code
881 // will continue to execute while the dialog is displayed.
882 // This prevents the dialog pattern I'm used to and means
883 // I can't do something like this:
885 // var link = CreateLinkDialog();
886 // makeMarkdownLink(link);
888 // Instead of this straightforward method of handling a
889 // dialog I have to pass any code which would execute
890 // after the dialog is dismissed (e.g. link creation)
891 // in a function parameter.
893 // Yes this is awkward and I think it sucks, but there's
894 // no real workaround. Only the image and link code
895 // create dialogs and require the function pointers.
896 var fixupInputArea = function(){
901 state.setChunks(chunks);
905 previewRefreshCallback();
908 var useDefaultText = true;
909 var noCleanup = button.textOp(chunks, fixupInputArea, useDefaultText);
917 if (button.execute) {
918 button.execute(editObj);
922 var setUndoRedoButtonStates = function(){
924 setupButton(document.getElementById("wmd-undo-button"), undoMgr.canUndo());
925 setupButton(document.getElementById("wmd-redo-button"), undoMgr.canRedo());
929 var setupButton = function(button, isEnabled) {
931 var normalYShift = "0px";
932 var disabledYShift = "-20px";
933 var highlightYShift = "-40px";
936 button.style.backgroundPosition = button.XShift + " " + normalYShift;
937 button.onmouseover = function(){
938 this.style.backgroundPosition = this.XShift + " " + highlightYShift;
941 button.onmouseout = function(){
942 this.style.backgroundPosition = this.XShift + " " + normalYShift;
945 // IE tries to select the background image "button" text (it's
946 // implemented in a list item) so we have to cache the selection
949 button.onmousedown = function() {
950 wmd.ieRetardedClick = true;
951 wmd.ieCachedRange = document.selection.createRange();
957 button.onclick = function() {
958 if (this.onmouseout) {
967 button.style.backgroundPosition = button.XShift + " " + disabledYShift;
968 button.onmouseover = button.onmouseout = button.onclick = function(){};
972 var makeSpritedButtonRow = function(){
974 var buttonBar = document.getElementById("wmd-button-bar");
976 var normalYShift = "0px";
977 var disabledYShift = "-20px";
978 var highlightYShift = "-40px";
980 var buttonRow = document.createElement("ul");
981 buttonRow.id = "wmd-button-row";
982 buttonRow = buttonBar.appendChild(buttonRow);
985 var boldButton = document.createElement("li");
986 boldButton.className = "wmd-button";
987 boldButton.id = "wmd-bold-button";
988 boldButton.title = "Strong <strong> Ctrl+B";
989 boldButton.XShift = "0px";
990 boldButton.textOp = command.doBold;
991 setupButton(boldButton, true);
992 buttonRow.appendChild(boldButton);
994 var italicButton = document.createElement("li");
995 italicButton.className = "wmd-button";
996 italicButton.id = "wmd-italic-button";
997 italicButton.title = "Emphasis <em> Ctrl+I";
998 italicButton.XShift = "-20px";
999 italicButton.textOp = command.doItalic;
1000 setupButton(italicButton, true);
1001 buttonRow.appendChild(italicButton);
1003 var spacer1 = document.createElement("li");
1004 spacer1.className = "wmd-spacer";
1005 spacer1.id = "wmd-spacer1";
1006 buttonRow.appendChild(spacer1);
1008 var linkButton = document.createElement("li");
1009 linkButton.className = "wmd-button";
1010 linkButton.id = "wmd-link-button";
1011 linkButton.title = "Hyperlink <a> Ctrl+L";
1012 linkButton.XShift = "-40px";
1013 linkButton.textOp = function(chunk, postProcessing, useDefaultText){
1014 return command.doLinkOrImage(chunk, postProcessing, false);
1016 setupButton(linkButton, true);
1017 buttonRow.appendChild(linkButton);
1019 var quoteButton = document.createElement("li");
1020 quoteButton.className = "wmd-button";
1021 quoteButton.id = "wmd-quote-button";
1022 quoteButton.title = "Blockquote <blockquote> Ctrl+Q";
1023 quoteButton.XShift = "-60px";
1024 quoteButton.textOp = command.doBlockquote;
1025 setupButton(quoteButton, true);
1026 buttonRow.appendChild(quoteButton);
1028 var codeButton = document.createElement("li");
1029 codeButton.className = "wmd-button";
1030 codeButton.id = "wmd-code-button";
1031 codeButton.title = "Code Sample <pre><code> Ctrl+K";
1032 codeButton.XShift = "-80px";
1033 codeButton.textOp = command.doCode;
1034 setupButton(codeButton, true);
1035 buttonRow.appendChild(codeButton);
1037 var imageButton = document.createElement("li");
1038 imageButton.className = "wmd-button";
1039 imageButton.id = "wmd-image-button";
1040 imageButton.title = "Image <img> Ctrl+G";
1041 imageButton.XShift = "-100px";
1042 imageButton.textOp = function(chunk, postProcessing, useDefaultText){
1043 return command.doLinkOrImage(chunk, postProcessing, true);
1045 setupButton(imageButton, true);
1046 buttonRow.appendChild(imageButton);
1048 var spacer2 = document.createElement("li");
1049 spacer2.className = "wmd-spacer";
1050 spacer2.id = "wmd-spacer2";
1051 buttonRow.appendChild(spacer2);
1053 var olistButton = document.createElement("li");
1054 olistButton.className = "wmd-button";
1055 olistButton.id = "wmd-olist-button";
1056 olistButton.title = "Numbered List <ol> Ctrl+O";
1057 olistButton.XShift = "-120px";
1058 olistButton.textOp = function(chunk, postProcessing, useDefaultText){
1059 command.doList(chunk, postProcessing, true, useDefaultText);
1061 setupButton(olistButton, true);
1062 buttonRow.appendChild(olistButton);
1064 var ulistButton = document.createElement("li");
1065 ulistButton.className = "wmd-button";
1066 ulistButton.id = "wmd-ulist-button";
1067 ulistButton.title = "Bulleted List <ul> Ctrl+U";
1068 ulistButton.XShift = "-140px";
1069 ulistButton.textOp = function(chunk, postProcessing, useDefaultText){
1070 command.doList(chunk, postProcessing, false, useDefaultText);
1072 setupButton(ulistButton, true);
1073 buttonRow.appendChild(ulistButton);
1075 var headingButton = document.createElement("li");
1076 headingButton.className = "wmd-button";
1077 headingButton.id = "wmd-heading-button";
1078 headingButton.title = "Heading <h1>/<h2> Ctrl+H";
1079 headingButton.XShift = "-160px";
1080 headingButton.textOp = command.doHeading;
1081 setupButton(headingButton, true);
1082 buttonRow.appendChild(headingButton);
1084 var hrButton = document.createElement("li");
1085 hrButton.className = "wmd-button";
1086 hrButton.id = "wmd-hr-button";
1087 hrButton.title = "Horizontal Rule <hr> Ctrl+R";
1088 hrButton.XShift = "-180px";
1089 hrButton.textOp = command.doHorizontalRule;
1090 setupButton(hrButton, true);
1091 buttonRow.appendChild(hrButton);
1093 var spacer3 = document.createElement("li");
1094 spacer3.className = "wmd-spacer";
1095 spacer3.id = "wmd-spacer3";
1096 buttonRow.appendChild(spacer3);
1098 var undoButton = document.createElement("li");
1099 undoButton.className = "wmd-button";
1100 undoButton.id = "wmd-undo-button";
1101 undoButton.title = "Undo - Ctrl+Z";
1102 undoButton.XShift = "-200px";
1103 undoButton.execute = function(manager){
1106 setupButton(undoButton, true);
1107 buttonRow.appendChild(undoButton);
1109 var redoButton = document.createElement("li");
1110 redoButton.className = "wmd-button";
1111 redoButton.id = "wmd-redo-button";
1112 redoButton.title = "Redo - Ctrl+Y";
1113 if (/win/.test(nav.platform.toLowerCase())) {
1114 redoButton.title = "Redo - Ctrl+Y";
1117 // mac and other non-Windows platforms
1118 redoButton.title = "Redo - Ctrl+Shift+Z";
1120 redoButton.XShift = "-220px";
1121 redoButton.execute = function(manager){
1124 setupButton(redoButton, true);
1125 buttonRow.appendChild(redoButton);
1127 var helpButton = document.createElement("li");
1128 helpButton.className = "wmd-button";
1129 helpButton.id = "wmd-help-button";
1130 helpButton.XShift = "-240px";
1131 helpButton.isHelp = true;
1133 var helpAnchor = document.createElement("a");
1134 helpAnchor.href = helpLink;
1135 helpAnchor.target = helpTarget
1136 helpAnchor.title = helpHoverTitle;
1137 helpButton.appendChild(helpAnchor);
1139 setupButton(helpButton, true);
1140 buttonRow.appendChild(helpButton);
1142 setUndoRedoButtonStates();
1145 var setupEditor = function(){
1147 if (/\?noundo/.test(doc.location.href)) {
1148 wmd.nativeUndo = true;
1151 if (!wmd.nativeUndo) {
1152 undoMgr = new wmd.undoManager(function(){
1153 previewRefreshCallback();
1154 setUndoRedoButtonStates();
1158 makeSpritedButtonRow();
1161 var keyEvent = "keydown";
1162 if (global.isOpera) {
1163 keyEvent = "keypress";
1166 util.addEvent(inputBox, keyEvent, function(key){
1168 // Check to see if we have a button key and, if so execute the callback.
1169 if (key.ctrlKey || key.metaKey) {
1171 var keyCode = key.charCode || key.keyCode;
1172 var keyCodeStr = String.fromCharCode(keyCode).toLowerCase();
1174 switch(keyCodeStr) {
1176 doClick(document.getElementById("wmd-bold-button"));
1179 doClick(document.getElementById("wmd-italic-button"));
1182 doClick(document.getElementById("wmd-link-button"));
1185 doClick(document.getElementById("wmd-quote-button"));
1188 doClick(document.getElementById("wmd-code-button"));
1191 doClick(document.getElementById("wmd-image-button"));
1194 doClick(document.getElementById("wmd-olist-button"));
1197 doClick(document.getElementById("wmd-ulist-button"));
1200 doClick(document.getElementById("wmd-heading-button"));
1203 doClick(document.getElementById("wmd-hr-button"));
1206 doClick(document.getElementById("wmd-redo-button"));
1210 doClick(document.getElementById("wmd-redo-button"));
1213 doClick(document.getElementById("wmd-undo-button"));
1221 if (key.preventDefault) {
1222 key.preventDefault();
1226 top.event.returnValue = false;
1231 // Auto-continue lists, code blocks and block quotes when
1232 // the enter key is pressed.
1233 util.addEvent(inputBox, "keyup", function(key){
1234 if (!key.shiftKey && !key.ctrlKey && !key.metaKey) {
1235 var keyCode = key.charCode || key.keyCode;
1236 // Key code 13 is Enter
1237 if (keyCode === 13) {
1239 fakeButton.textOp = command.doAutoindent;
1240 doClick(fakeButton);
1245 // Disable ESC clearing the input textarea on IE
1247 util.addEvent(inputBox, "keydown", function(key){
1248 var code = key.keyCode;
1249 // Key code 27 is ESC
1256 if (inputBox.form) {
1257 var submitCallback = inputBox.form.onsubmit;
1258 inputBox.form.onsubmit = function(){
1260 if (submitCallback) {
1261 return submitCallback.apply(this, arguments);
1267 // Convert the contents of the input textarea to HTML in the output/preview panels.
1268 var convertToHtml = function(){
1271 var markdownConverter = new wmd.showdown.converter();
1273 var text = inputBox.value;
1275 var callback = function(){
1276 inputBox.value = text;
1279 if (!/markdown/.test(wmd.wmd_env.output.toLowerCase())) {
1280 if (markdownConverter) {
1281 inputBox.value = markdownConverter.makeHtml(text);
1282 top.setTimeout(callback, 0);
1289 this.undo = function(){
1295 this.redo = function(){
1301 // This is pretty useless. The setupEditor function contents
1302 // should just be copied here.
1303 var init = function(){
1307 this.destroy = function(){
1311 if (div.parentNode) {
1312 div.parentNode.removeChild(div);
1315 inputBox.style.marginTop = "";
1317 top.clearInterval(creationHandle);
1323 // The input textarea state/contents.
1324 // This is used to implement undo/redo by the undo manager.
1325 wmd.TextareaState = function(){
1328 var stateObj = this;
1329 var inputArea = wmd.panels.input;
1331 this.init = function() {
1333 if (!util.isVisible(inputArea)) {
1337 this.setInputAreaSelectionStartEnd();
1338 this.scrollTop = inputArea.scrollTop;
1339 if (!this.text && inputArea.selectionStart || inputArea.selectionStart === 0) {
1340 this.text = inputArea.value;
1345 // Sets the selected text in the input box after we've performed an
1347 this.setInputAreaSelection = function(){
1349 if (!util.isVisible(inputArea)) {
1353 if (inputArea.selectionStart !== undefined && !global.isOpera) {
1356 inputArea.selectionStart = stateObj.start;
1357 inputArea.selectionEnd = stateObj.end;
1358 inputArea.scrollTop = stateObj.scrollTop;
1360 else if (doc.selection) {
1362 if (doc.activeElement && doc.activeElement !== inputArea) {
1367 var range = inputArea.createTextRange();
1368 range.moveStart("character", -inputArea.value.length);
1369 range.moveEnd("character", -inputArea.value.length);
1370 range.moveEnd("character", stateObj.end);
1371 range.moveStart("character", stateObj.start);
1376 this.setInputAreaSelectionStartEnd = function(){
1378 if (inputArea.selectionStart || inputArea.selectionStart === 0) {
1380 stateObj.start = inputArea.selectionStart;
1381 stateObj.end = inputArea.selectionEnd;
1383 else if (doc.selection) {
1385 stateObj.text = util.fixEolChars(inputArea.value);
1387 // IE loses the selection in the textarea when buttons are
1388 // clicked. On IE we cache the selection and set a flag
1389 // which we check for here.
1391 if(wmd.ieRetardedClick && wmd.ieCachedRange) {
1392 range = wmd.ieCachedRange;
1393 wmd.ieRetardedClick = false;
1396 range = doc.selection.createRange();
1399 var fixedRange = util.fixEolChars(range.text);
1400 var marker = "\x07";
1401 var markedRange = marker + fixedRange + marker;
1402 range.text = markedRange;
1403 var inputText = util.fixEolChars(inputArea.value);
1405 range.moveStart("character", -markedRange.length);
1406 range.text = fixedRange;
1408 stateObj.start = inputText.indexOf(marker);
1409 stateObj.end = inputText.lastIndexOf(marker) - marker.length;
1411 var len = stateObj.text.length - util.fixEolChars(inputArea.value).length;
1414 range.moveStart("character", -fixedRange.length);
1419 range.text = fixedRange;
1422 this.setInputAreaSelection();
1426 // Restore this state into the input area.
1427 this.restore = function(){
1429 if (stateObj.text != undefined && stateObj.text != inputArea.value) {
1430 inputArea.value = stateObj.text;
1432 this.setInputAreaSelection();
1433 inputArea.scrollTop = stateObj.scrollTop;
1436 // Gets a collection of HTML chunks from the inptut textarea.
1437 this.getChunks = function(){
1439 var chunk = new wmd.Chunks();
1441 chunk.before = util.fixEolChars(stateObj.text.substring(0, stateObj.start));
1442 chunk.startTag = "";
1443 chunk.selection = util.fixEolChars(stateObj.text.substring(stateObj.start, stateObj.end));
1445 chunk.after = util.fixEolChars(stateObj.text.substring(stateObj.end));
1446 chunk.scrollTop = stateObj.scrollTop;
1451 // Sets the TextareaState properties given a chunk of markdown.
1452 this.setChunks = function(chunk){
1454 chunk.before = chunk.before + chunk.startTag;
1455 chunk.after = chunk.endTag + chunk.after;
1457 if (global.isOpera) {
1458 chunk.before = chunk.before.replace(/\n/g, "\r\n");
1459 chunk.selection = chunk.selection.replace(/\n/g, "\r\n");
1460 chunk.after = chunk.after.replace(/\n/g, "\r\n");
1463 this.start = chunk.before.length;
1464 this.end = chunk.before.length + chunk.selection.length;
1465 this.text = chunk.before + chunk.selection + chunk.after;
1466 this.scrollTop = chunk.scrollTop;
1472 // before: contains all the text in the input box BEFORE the selection.
1473 // after: contains all the text in the input box AFTER the selection.
1474 wmd.Chunks = function(){
1477 // startRegex: a regular expression to find the start tag
1478 // endRegex: a regular expresssion to find the end tag
1479 wmd.Chunks.prototype.findTags = function(startRegex, endRegex){
1481 var chunkObj = this;
1486 regex = util.extendRegExp(startRegex, "", "$");
1488 this.before = this.before.replace(regex,
1490 chunkObj.startTag = chunkObj.startTag + match;
1494 regex = util.extendRegExp(startRegex, "^", "");
1496 this.selection = this.selection.replace(regex,
1498 chunkObj.startTag = chunkObj.startTag + match;
1505 regex = util.extendRegExp(endRegex, "", "$");
1507 this.selection = this.selection.replace(regex,
1509 chunkObj.endTag = match + chunkObj.endTag;
1513 regex = util.extendRegExp(endRegex, "^", "");
1515 this.after = this.after.replace(regex,
1517 chunkObj.endTag = match + chunkObj.endTag;
1523 // If remove is false, the whitespace is transferred
1524 // to the before/after regions.
1526 // If remove is true, the whitespace disappears.
1527 wmd.Chunks.prototype.trimWhitespace = function(remove){
1529 this.selection = this.selection.replace(/^(\s*)/, "");
1532 this.before += re.$1;
1535 this.selection = this.selection.replace(/(\s*)$/, "");
1538 this.after = re.$1 + this.after;
1543 wmd.Chunks.prototype.addBlankLines = function(nLinesBefore, nLinesAfter, findExtraNewlines){
1545 if (nLinesBefore === undefined) {
1549 if (nLinesAfter === undefined) {
1557 var replacementText;
1559 if (navigator.userAgent.match(/Chrome/)) {
1563 this.selection = this.selection.replace(/(^\n*)/, "");
1564 this.startTag = this.startTag + re.$1;
1565 this.selection = this.selection.replace(/(\n*$)/, "");
1566 this.endTag = this.endTag + re.$1;
1567 this.startTag = this.startTag.replace(/(^\n*)/, "");
1568 this.before = this.before + re.$1;
1569 this.endTag = this.endTag.replace(/(\n*$)/, "");
1570 this.after = this.after + re.$1;
1574 regexText = replacementText = "";
1576 while (nLinesBefore--) {
1577 regexText += "\\n?";
1578 replacementText += "\n";
1581 if (findExtraNewlines) {
1584 this.before = this.before.replace(new re(regexText + "$", ""), replacementText);
1589 regexText = replacementText = "";
1591 while (nLinesAfter--) {
1592 regexText += "\\n?";
1593 replacementText += "\n";
1595 if (findExtraNewlines) {
1599 this.after = this.after.replace(new re(regexText, ""), replacementText);
1603 // The markdown symbols - 4 spaces = code, > = blockquote, etc.
1604 command.prefixes = "(?:\\s{4,}|\\s*>|\\s*-\\s+|\\s*\\d+\\.|=|\\+|-|_|\\*|#|\\s*\\[[^\n]]+\\]:)";
1606 // Remove markdown symbols from the chunk selection.
1607 command.unwrap = function(chunk){
1608 var txt = new re("([^\\n])\\n(?!(\\n|" + command.prefixes + "))", "g");
1609 chunk.selection = chunk.selection.replace(txt, "$1 $2");
1612 command.wrap = function(chunk, len){
1613 command.unwrap(chunk);
1614 var regex = new re("(.{1," + len + "})( +|$\\n?)", "gm");
1616 chunk.selection = chunk.selection.replace(regex, function(line, marked){
1617 if (new re("^" + command.prefixes, "").test(line)) {
1620 return marked + "\n";
1623 chunk.selection = chunk.selection.replace(/\s+$/, "");
1626 command.doBold = function(chunk, postProcessing, useDefaultText){
1627 return command.doBorI(chunk, 2, "strong text");
1630 command.doItalic = function(chunk, postProcessing, useDefaultText){
1631 return command.doBorI(chunk, 1, "emphasized text");
1634 // chunk: The selected region that will be enclosed with */**
1635 // nStars: 1 for italics, 2 for bold
1636 // insertText: If you just click the button without highlighting text, this gets inserted
1637 command.doBorI = function(chunk, nStars, insertText){
1639 // Get rid of whitespace and fix up newlines.
1640 chunk.trimWhitespace();
1641 chunk.selection = chunk.selection.replace(/\n{2,}/g, "\n");
1643 // Look for stars before and after. Is the chunk already marked up?
1644 chunk.before.search(/(\**$)/);
1645 var starsBefore = re.$1;
1647 chunk.after.search(/(^\**)/);
1648 var starsAfter = re.$1;
1650 var prevStars = Math.min(starsBefore.length, starsAfter.length);
1652 // Remove stars if we have to since the button acts as a toggle.
1653 if ((prevStars >= nStars) && (prevStars != 2 || nStars != 1)) {
1654 chunk.before = chunk.before.replace(re("[*]{" + nStars + "}$", ""), "");
1655 chunk.after = chunk.after.replace(re("^[*]{" + nStars + "}", ""), "");
1657 else if (!chunk.selection && starsAfter) {
1658 // It's not really clear why this code is necessary. It just moves
1659 // some arbitrary stuff around.
1660 chunk.after = chunk.after.replace(/^([*_]*)/, "");
1661 chunk.before = chunk.before.replace(/(\s?)$/, "");
1662 var whitespace = re.$1;
1663 chunk.before = chunk.before + starsAfter + whitespace;
1667 // In most cases, if you don't have any selected text and click the button
1668 // you'll get a selected, marked up region with the default text inserted.
1669 if (!chunk.selection && !starsAfter) {
1670 chunk.selection = insertText;
1673 // Add the true markup.
1674 var markup = nStars <= 1 ? "*" : "**"; // shouldn't the test be = ?
1675 chunk.before = chunk.before + markup;
1676 chunk.after = markup + chunk.after;
1682 command.stripLinkDefs = function(text, defsToAdd){
1684 text = text.replace(/^[ ]{0,3}\[(\d+)\]:[ \t]*\n?[ \t]*<?(\S+?)>?[ \t]*\n?[ \t]*(?:(\n*)["(](.+?)[")][ \t]*)?(?:\n+|$)/gm,
1685 function(totalMatch, id, link, newlines, title){
1686 defsToAdd[id] = totalMatch.replace(/\s*$/, "");
1688 // Strip the title and return that separately.
1689 defsToAdd[id] = totalMatch.replace(/["(](.+?)[")]$/, "");
1690 return newlines + title;
1698 command.addLinkDef = function(chunk, linkDef){
1700 var refNumber = 0; // The current reference number
1701 var defsToAdd = {}; //
1702 // Start with a clean slate by removing all previous link definitions.
1703 chunk.before = command.stripLinkDefs(chunk.before, defsToAdd);
1704 chunk.selection = command.stripLinkDefs(chunk.selection, defsToAdd);
1705 chunk.after = command.stripLinkDefs(chunk.after, defsToAdd);
1708 var regex = /(\[)((?:\[[^\]]*\]|[^\[\]])*)(\][ ]?(?:\n[ ]*)?\[)(\d+)(\])/g;
1712 var addDefNumber = function(def){
1714 def = def.replace(/^[ ]{0,3}\[(\d+)\]:/, " [" + refNumber + "]:");
1719 // a) the recursive call to getLink cannot go infinite, because by definition
1720 // of regex, inner is always a proper substring of wholeMatch, and
1721 // b) more than one level of nesting is neither supported by the regex
1722 // nor making a lot of sense (the only use case for nesting is a linked image)
1723 var getLink = function (wholeMatch, before, inner, afterInner, id, end) {
1724 inner = inner.replace(regex, getLink);
1725 if (defsToAdd[id]) {
1726 addDefNumber(defsToAdd[id]);
1727 return before + inner + afterInner + refNumber + end;
1733 chunk.before = chunk.before.replace(regex, getLink);
1736 addDefNumber(linkDef);
1739 chunk.selection = chunk.selection.replace(regex, getLink);
1742 var refOut = refNumber;
1744 chunk.after = chunk.after.replace(regex, getLink);
1747 chunk.after = chunk.after.replace(/\n*$/, "");
1750 chunk.selection = chunk.selection.replace(/\n*$/, "");
1753 chunk.after += "\n\n" + defs;
1758 command.doLinkOrImage = function(chunk, postProcessing, isImage){
1760 chunk.trimWhitespace();
1761 chunk.findTags(/\s*!?\[/, /\][ ]?(?:\n[ ]*)?(\[.*?\])?/);
1763 if (chunk.endTag.length > 1) {
1765 chunk.startTag = chunk.startTag.replace(/!?\[/, "");
1767 command.addLinkDef(chunk, null);
1772 if (/\n\n/.test(chunk.selection)) {
1773 command.addLinkDef(chunk, null);
1777 // The function to be executed when you enter a link and press OK or Cancel.
1778 // Marks up the link and adds the ref.
1779 var makeLinkMarkdown = function(link){
1781 if (link !== null) {
1783 chunk.startTag = chunk.endTag = "";
1784 var linkDef = " [999]: " + link;
1786 var num = command.addLinkDef(chunk, linkDef);
1787 chunk.startTag = isImage ? "![" : "[";
1788 chunk.endTag = "][" + num + "]";
1790 if (!chunk.selection) {
1792 chunk.selection = "alt text";
1795 chunk.selection = "link text";
1803 util.prompt(imageDialogText, imageDefaultText, makeLinkMarkdown);
1806 util.prompt(linkDialogText, linkDefaultText, makeLinkMarkdown);
1812 util.makeAPI = function(){
1814 wmd.wmd.editor = wmd.editor;
1815 wmd.wmd.previewManager = wmd.previewManager;
1818 util.startEditor = function(){
1820 if (wmd.wmd_env.autostart === false) {
1825 var edit; // The editor (buttons + input + outputs) - the main object.
1826 var previewMgr; // The preview manager.
1828 // Fired after the page has fully loaded.
1829 var loadListener = function(){
1831 wmd.panels = new wmd.PanelCollection();
1833 previewMgr = new wmd.previewManager();
1834 var previewRefreshCallback = previewMgr.refresh;
1836 edit = new wmd.editor(previewRefreshCallback);
1838 previewMgr.refresh(true);
1842 util.addEvent(top, "load", loadListener);
1845 wmd.previewManager = function(){
1847 var managerObj = this;
1854 var maxDelay = 3000;
1855 var startType = "delayed"; // The other legal value is "manual"
1857 // Adds event listeners to elements and creates the input poller.
1858 var setupEvents = function(inputElem, listener){
1860 util.addEvent(inputElem, "input", listener);
1861 inputElem.onpaste = listener;
1862 inputElem.ondrop = listener;
1864 util.addEvent(inputElem, "keypress", listener);
1865 util.addEvent(inputElem, "keydown", listener);
1866 // previewPollInterval is set at the top of this file.
1867 poller = new wmd.inputPoller(listener, previewPollInterval);
1870 var getDocScrollTop = function(){
1874 if (top.innerHeight) {
1875 result = top.pageYOffset;
1878 if (doc.documentElement && doc.documentElement.scrollTop) {
1879 result = doc.documentElement.scrollTop;
1883 result = doc.body.scrollTop;
1889 var makePreviewHtml = function(){
1891 // If there are no registered preview and output panels
1892 // there is nothing to do.
1893 if (!wmd.panels.preview && !wmd.panels.output) {
1897 var text = wmd.panels.input.value;
1898 if (text && text == oldInputText) {
1899 return; // Input text hasn't changed.
1902 oldInputText = text;
1905 var prevTime = new Date().getTime();
1907 if (!converter && wmd.showdown) {
1908 converter = new wmd.showdown.converter();
1912 text = converter.makeHtml(text);
1915 // Calculate the processing time of the HTML creation.
1916 // It's used as the delay time in the event listener.
1917 var currTime = new Date().getTime();
1918 elapsedTime = currTime - prevTime;
1920 pushPreviewHtml(text);
1924 // setTimeout is already used. Used as an event listener.
1925 var applyTimeout = function(){
1928 top.clearTimeout(timeout);
1929 timeout = undefined;
1932 if (startType !== "manual") {
1936 if (startType === "delayed") {
1937 delay = elapsedTime;
1940 if (delay > maxDelay) {
1943 timeout = top.setTimeout(makePreviewHtml, delay);
1947 var getScaleFactor = function(panel){
1948 if (panel.scrollHeight <= panel.clientHeight) {
1951 return panel.scrollTop / (panel.scrollHeight - panel.clientHeight);
1954 var setPanelScrollTops = function(){
1956 if (wmd.panels.preview) {
1957 wmd.panels.preview.scrollTop = (wmd.panels.preview.scrollHeight - wmd.panels.preview.clientHeight) * getScaleFactor(wmd.panels.preview);
1961 if (wmd.panels.output) {
1962 wmd.panels.output.scrollTop = (wmd.panels.output.scrollHeight - wmd.panels.output.clientHeight) * getScaleFactor(wmd.panels.output);
1967 this.refresh = function(requiresRefresh){
1969 if (requiresRefresh) {
1978 this.processingTime = function(){
1983 this.output = function(){
1987 // The mode can be "manual" or "delayed"
1988 this.setUpdateMode = function(mode){
1990 managerObj.refresh();
1993 var isFirstTimeFilled = true;
1995 var pushPreviewHtml = function(text){
1997 var emptyTop = position.getTop(wmd.panels.input) - getDocScrollTop();
1999 // Send the encoded HTML to the output textarea/div.
2000 if (wmd.panels.output) {
2001 // The value property is only defined if the output is a textarea.
2002 if (wmd.panels.output.value !== undefined) {
2003 wmd.panels.output.value = text;
2004 wmd.panels.output.readOnly = true;
2006 // Otherwise we are just replacing the text in a div.
2007 // Send the HTML wrapped in <pre><code>
2009 var newText = text.replace(/&/g, "&");
2010 newText = newText.replace(/</g, "<");
2011 wmd.panels.output.innerHTML = "<pre><code>" + newText + "</code></pre>";
2015 if (wmd.panels.preview) {
2016 wmd.panels.preview.innerHTML = text;
2019 setPanelScrollTops();
2021 if (isFirstTimeFilled) {
2022 isFirstTimeFilled = false;
2026 var fullTop = position.getTop(wmd.panels.input) - getDocScrollTop();
2029 top.setTimeout(function(){
2030 top.scrollBy(0, fullTop - emptyTop);
2034 top.scrollBy(0, fullTop - emptyTop);
2038 var init = function(){
2040 setupEvents(wmd.panels.input, applyTimeout);
2043 if (wmd.panels.preview) {
2044 wmd.panels.preview.scrollTop = 0;
2046 if (wmd.panels.output) {
2047 wmd.panels.output.scrollTop = 0;
2051 this.destroy = function(){
2060 // Moves the cursor to the next line and continues lists, quotes and code.
2061 command.doAutoindent = function(chunk, postProcessing, useDefaultText){
2063 chunk.before = chunk.before.replace(/(\n|^)[ ]{0,3}([*+-]|\d+[.])[ \t]*\n$/, "\n\n");
2064 chunk.before = chunk.before.replace(/(\n|^)[ ]{0,3}>[ \t]*\n$/, "\n\n");
2065 chunk.before = chunk.before.replace(/(\n|^)[ \t]+\n$/, "\n\n");
2067 useDefaultText = false;
2069 if(/(\n|^)[ ]{0,3}([*+-])[ \t]+.*\n$/.test(chunk.before)){
2071 command.doList(chunk, postProcessing, false, true);
2074 if(/(\n|^)[ ]{0,3}(\d+[.])[ \t]+.*\n$/.test(chunk.before)){
2076 command.doList(chunk, postProcessing, true, true);
2079 if(/(\n|^)[ ]{0,3}>[ \t]+.*\n$/.test(chunk.before)){
2080 if(command.doBlockquote){
2081 command.doBlockquote(chunk, postProcessing, useDefaultText);
2084 if(/(\n|^)(\t|[ ]{4,}).*\n$/.test(chunk.before)){
2086 command.doCode(chunk, postProcessing, useDefaultText);
2091 command.doBlockquote = function(chunk, postProcessing, useDefaultText){
2093 chunk.selection = chunk.selection.replace(/^(\n*)([^\r]+?)(\n*)$/,
2094 function(totalMatch, newlinesBefore, text, newlinesAfter){
2095 chunk.before += newlinesBefore;
2096 chunk.after = newlinesAfter + chunk.after;
2100 chunk.before = chunk.before.replace(/(>[ \t]*)$/,
2101 function(totalMatch, blankLine){
2102 chunk.selection = blankLine + chunk.selection;
2106 var defaultText = useDefaultText ? "Blockquote" : "";
2107 chunk.selection = chunk.selection.replace(/^(\s|>)+$/ ,"");
2108 chunk.selection = chunk.selection || defaultText;
2110 // The original code uses a regular expression to find out how much of the
2111 // text *directly before* the selection already was a blockquote:
2114 chunk.before = chunk.before.replace(/\n?$/,"\n");
2116 chunk.before = chunk.before.replace(/(((\n|^)(\n[ \t]*)*>(.+\n)*.*)+(\n[ \t]*)*$)/,
2117 function (totalMatch) {
2118 chunk.startTag = totalMatch;
2122 // This comes down to:
2123 // Go backwards as many lines a possible, such that each line
2124 // a) starts with ">", or
2125 // b) is almost empty, except for whitespace, or
2126 // c) is preceeded by an unbroken chain of non-empty lines
2127 // leading up to a line that starts with ">" and at least one more character
2129 // d) at least one line fulfills a)
2131 // Since this is essentially a backwards-moving regex, it's susceptible to
2132 // catstrophic backtracking and can cause the browser to hang;
2133 // see e.g. http://meta.stackoverflow.com/questions/9807.
2135 // Hence we replaced this by a simple state machine that just goes through the
2136 // lines and checks for a), b), and c).
2141 var lines = chunk.before.replace(/\n$/, "").split("\n");
2142 var inChain = false;
2143 for (var i in lines) {
2146 inChain = inChain && line.length > 0; // c) any non-empty line continues the chain
2147 if (/^>/.test(line)) { // a)
2149 if (!inChain && line.length > 1) // c) any line that starts with ">" and has at least one more character starts the chain
2151 } else if (/^[ \t]*$/.test(line)) { // b)
2154 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
2157 match += line + "\n";
2159 leftOver += match + line;
2163 if (!/(^|\n)>/.test(match)) { // d)
2169 chunk.startTag = match;
2170 chunk.before = leftOver;
2175 chunk.after = chunk.after.replace(/^\n?/,"\n");
2178 chunk.after = chunk.after.replace(/^(((\n|^)(\n[ \t]*)*>(.+\n)*.*)+(\n[ \t]*)*)/,
2179 function(totalMatch){
2180 chunk.endTag = totalMatch;
2184 var replaceBlanksInTags = function(useBracket){
2186 var replacement = useBracket ? "> " : "";
2189 chunk.startTag = chunk.startTag.replace(/\n((>|\s)*)\n$/,
2190 function(totalMatch, markdown){
2191 return "\n" + markdown.replace(/^[ ]{0,3}>?[ \t]*$/gm, replacement) + "\n";
2195 chunk.endTag = chunk.endTag.replace(/^\n((>|\s)*)\n/,
2196 function(totalMatch, markdown){
2197 return "\n" + markdown.replace(/^[ ]{0,3}>?[ \t]*$/gm, replacement) + "\n";
2202 if(/^(?![ ]{0,3}>)/m.test(chunk.selection)){
2203 command.wrap(chunk, wmd.wmd_env.lineLength - 2);
2204 chunk.selection = chunk.selection.replace(/^/gm, "> ");
2205 replaceBlanksInTags(true);
2206 chunk.addBlankLines();
2209 chunk.selection = chunk.selection.replace(/^[ ]{0,3}> ?/gm, "");
2210 command.unwrap(chunk);
2211 replaceBlanksInTags(false);
2213 if(!/^(\n|^)[ ]{0,3}>/.test(chunk.selection) && chunk.startTag){
2214 chunk.startTag = chunk.startTag.replace(/\n{0,2}$/, "\n\n");
2217 if(!/(\n|^)[ ]{0,3}>.*$/.test(chunk.selection) && chunk.endTag){
2218 chunk.endTag=chunk.endTag.replace(/^\n{0,2}/, "\n\n");
2222 if(!/\n/.test(chunk.selection)){
2223 chunk.selection = chunk.selection.replace(/^(> *)/,
2224 function(wholeMatch, blanks){
2225 chunk.startTag += blanks;
2231 command.doCode = function(chunk, postProcessing, useDefaultText){
2233 var hasTextBefore = /\S[ ]*$/.test(chunk.before);
2234 var hasTextAfter = /^[ ]*\S/.test(chunk.after);
2236 // Use 'four space' markdown if the selection is on its own
2237 // line or is multiline.
2238 if((!hasTextAfter && !hasTextBefore) || /\n/.test(chunk.selection)){
2240 chunk.before = chunk.before.replace(/[ ]{4}$/,
2241 function(totalMatch){
2242 chunk.selection = totalMatch + chunk.selection;
2246 var nLinesBefore = 1;
2247 var nLinesAfter = 1;
2250 if(/\n(\t|[ ]{4,}).*\n$/.test(chunk.before) || chunk.after === ""){
2253 if(/^\n(\t|[ ]{4,})/.test(chunk.after)){
2254 nLinesAfter = 0; // This needs to happen on line 1
2257 chunk.addBlankLines(nLinesBefore, nLinesAfter);
2259 if(!chunk.selection){
2260 chunk.startTag = " ";
2261 chunk.selection = useDefaultText ? "enter code here" : "";
2264 if(/^[ ]{0,3}\S/m.test(chunk.selection)){
2265 chunk.selection = chunk.selection.replace(/^/gm, " ");
2268 chunk.selection = chunk.selection.replace(/^[ ]{4}/gm, "");
2273 // Use backticks (`) to delimit the code block.
2275 chunk.trimWhitespace();
2276 chunk.findTags(/`/, /`/);
2278 if(!chunk.startTag && !chunk.endTag){
2279 chunk.startTag = chunk.endTag="`";
2280 if(!chunk.selection){
2281 chunk.selection = useDefaultText ? "enter code here" : "";
2284 else if(chunk.endTag && !chunk.startTag){
2285 chunk.before += chunk.endTag;
2289 chunk.startTag = chunk.endTag="";
2294 command.doList = function(chunk, postProcessing, isNumberedList, useDefaultText){
2296 // These are identical except at the very beginning and end.
2297 // Should probably use the regex extension function to make this clearer.
2298 var previousItemsRegex = /(\n|^)(([ ]{0,3}([*+-]|\d+[.])[ \t]+.*)(\n.+|\n{2,}([*+-].*|\d+[.])[ \t]+.*|\n{2,}[ \t]+\S.*)*)\n*$/;
2299 var nextItemsRegex = /^\n*(([ ]{0,3}([*+-]|\d+[.])[ \t]+.*)(\n.+|\n{2,}([*+-].*|\d+[.])[ \t]+.*|\n{2,}[ \t]+\S.*)*)\n*/;
2301 // The default bullet is a dash but others are possible.
2302 // This has nothing to do with the particular HTML bullet,
2303 // it's just a markdown bullet.
2306 // The number in a numbered list.
2309 // Get the item prefix - e.g. " 1. " for a numbered list, " - " for a bulleted list.
2310 var getItemPrefix = function(){
2313 prefix = " " + num + ". ";
2317 prefix = " " + bullet + " ";
2322 // Fixes the prefixes of the other list items.
2323 var getPrefixedItem = function(itemText){
2325 // The numbering flag is unset when called by autoindent.
2326 if(isNumberedList === undefined){
2327 isNumberedList = /^\s*\d/.test(itemText);
2330 // Renumber/bullet the list element.
2331 itemText = itemText.replace(/^[ ]{0,3}([*+-]|\d+[.])\s/gm,
2333 return getItemPrefix();
2339 chunk.findTags(/(\n|^)*[ ]{0,3}([*+-]|\d+[.])\s+/, null);
2341 if(chunk.before && !/\n$/.test(chunk.before) && !/^\n/.test(chunk.startTag)){
2342 chunk.before += chunk.startTag;
2343 chunk.startTag = "";
2348 var hasDigits = /\d+[.]/.test(chunk.startTag);
2349 chunk.startTag = "";
2350 chunk.selection = chunk.selection.replace(/\n[ ]{4}/g, "\n");
2351 command.unwrap(chunk);
2352 chunk.addBlankLines();
2355 // Have to renumber the bullet points if this is a numbered list.
2356 chunk.after = chunk.after.replace(nextItemsRegex, getPrefixedItem);
2358 if(isNumberedList == hasDigits){
2363 var nLinesBefore = 1;
2365 chunk.before = chunk.before.replace(previousItemsRegex,
2367 if(/^\s*([*+-])/.test(itemText)){
2370 nLinesBefore = /[^\n]\n\n[^\n]/.test(itemText) ? 1 : 0;
2371 return getPrefixedItem(itemText);
2374 if(!chunk.selection){
2375 chunk.selection = useDefaultText ? "List item" : " ";
2378 var prefix = getItemPrefix();
2380 var nLinesAfter = 1;
2382 chunk.after = chunk.after.replace(nextItemsRegex,
2384 nLinesAfter = /[^\n]\n\n[^\n]/.test(itemText) ? 1 : 0;
2385 return getPrefixedItem(itemText);
2388 chunk.trimWhitespace(true);
2389 chunk.addBlankLines(nLinesBefore, nLinesAfter, true);
2390 chunk.startTag = prefix;
2391 var spaces = prefix.replace(/./g, " ");
2392 command.wrap(chunk, wmd.wmd_env.lineLength - spaces.length);
2393 chunk.selection = chunk.selection.replace(/\n/g, "\n" + spaces);
2397 command.doHeading = function(chunk, postProcessing, useDefaultText){
2399 // Remove leading/trailing whitespace and reduce internal spaces to single spaces.
2400 chunk.selection = chunk.selection.replace(/\s+/g, " ");
2401 chunk.selection = chunk.selection.replace(/(^\s+|\s+$)/g, "");
2403 // If we clicked the button with no selected text, we just
2404 // make a level 2 hash header around some default text.
2405 if(!chunk.selection){
2406 chunk.startTag = "## ";
2407 chunk.selection = "Heading";
2408 chunk.endTag = " ##";
2412 var headerLevel = 0; // The existing header level of the selected text.
2414 // Remove any existing hash heading markdown and save the header level.
2415 chunk.findTags(/#+[ ]*/, /[ ]*#+/);
2416 if(/#+/.test(chunk.startTag)){
2417 headerLevel = re.lastMatch.length;
2419 chunk.startTag = chunk.endTag = "";
2421 // Try to get the current header level by looking for - and = in the line
2422 // below the selection.
2423 chunk.findTags(null, /\s?(-+|=+)/);
2424 if(/=+/.test(chunk.endTag)){
2427 if(/-+/.test(chunk.endTag)){
2431 // Skip to the next line so we can create the header markdown.
2432 chunk.startTag = chunk.endTag = "";
2433 chunk.addBlankLines(1, 1);
2435 // We make a level 2 header if there is no current header.
2436 // If there is a header level, we substract one from the header level.
2437 // If it's already a level 1 header, it's removed.
2438 var headerLevelToCreate = headerLevel == 0 ? 2 : headerLevel - 1;
2440 if(headerLevelToCreate > 0){
2442 // The button only creates level 1 and 2 underline headers.
2443 // Why not have it iterate over hash header levels? Wouldn't that be easier and cleaner?
2444 var headerChar = headerLevelToCreate >= 2 ? "-" : "=";
2445 var len = chunk.selection.length;
2446 if(len > wmd.wmd_env.lineLength){
2447 len = wmd.wmd_env.lineLength;
2449 chunk.endTag = "\n";
2451 chunk.endTag += headerChar;
2456 command.doHorizontalRule = function(chunk, postProcessing, useDefaultText){
2457 chunk.startTag = "----------\n";
2458 chunk.selection = "";
2459 chunk.addBlankLines(2, 1, true);
2464 Attacklab.wmd_env = {};
2465 Attacklab.account_options = {};
2466 Attacklab.wmd_defaults = {version:1, output:"HTML", lineLength:40, delayLoad:false};
2470 Attacklab.wmd = function()
2472 Attacklab.loadEnv = function()
2474 var mergeEnv = function(env)
2483 Attacklab.wmd_env[key] = env[key];
2487 mergeEnv(Attacklab.wmd_defaults);
2488 mergeEnv(Attacklab.account_options);
2489 mergeEnv(top["wmd_options"]);
2490 Attacklab.full = true;
2492 var defaultButtons = "bold italic link blockquote code image ol ul heading hr";
2493 Attacklab.wmd_env.buttons = Attacklab.wmd_env.buttons || defaultButtons;
2495 Attacklab.loadEnv();
2500 Attacklab.wmdBase();
2501 Attacklab.Util.startEditor();