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', 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());
74 var toolbar_strong_label = $.i18n._('bold') + " <strong> Ctrl-B";
75 var toolbar_emphasis_label = $.i18n._('italic') + " <em> Ctrl-I";
76 var toolbar_hyperlink_label = $.i18n._('link') + " <a> Ctrl-L";
77 var toolbar_blockquote_label = $.i18n._('quote') + " <blockquote> Ctrl-.";
78 var toolbar_code_label = $.i18n._('preformatted text') + " <pre><code> Ctrl-K";
79 var toolbar_image_label = $.i18n._('image') + " <img> Ctrl-G";
80 var toolbar_numbered_label = $.i18n._('numbered list') + " <ol> Ctrl-O";
81 var toolbar_bulleted_label = $.i18n._('bulleted list') + " <ul> Ctrl-U";
82 var toolbar_heading_label = $.i18n._('heading') + " <h1>/<h2> Ctrl-H";
83 var toolbar_horizontal_label = $.i18n._('horizontal bar') + " <hr> Ctrl-R";
84 var toolbar_undo_label = $.i18n._('undo') + " Ctrl-Z";
85 var toolbar_redo_label = $.i18n._('redo') + " Ctrl-Y";
87 // -------------------------------------------------------------------
88 // YOUR CHANGES GO HERE
90 // I've tried to localize the things you are likely to change to
92 // -------------------------------------------------------------------
94 // The text that appears on the upper part of the dialog box when
96 var imageDialogText = "<p style='margin-top: 0px'>" + $.i18n._('enter image url') + "</p>";
97 var linkDialogText = "<p style='margin-top: 0px'>" + $.i18n._('enter url') + "</p>";
98 var uploadImageHTML ="<div>" + $.i18n._('upload image') + "</div>" +
99 "<input type=\"file\" name=\"file-upload\" id=\"file-upload\" size=\"26\" "+
100 "onchange=\"return ajaxFileUpload($('#image-url'));\"/><br>" +
101 "<img id=\"loading\" src=\"" + mediaUrl("media/images/indicator.gif") + "\" style=\"display:none;\"/>";
104 // The default text that appears in the dialog input box when entering
106 var imageDefaultText = "http://";
107 var linkDefaultText = "http://";
109 // The location of your button images relative to the base directory.
110 var imageDirectory = "images/";
112 // Some intervals in ms. These can be adjusted to reduce the control's load.
113 var previewPollInterval = 500;
114 var pastePollInterval = 100;
116 // The link and title for the help button
117 var helpLink = "http://wmd-editor.com/";
118 var helpHoverTitle = "WMD website";
119 var helpTarget = "_blank";
121 // -------------------------------------------------------------------
122 // END OF YOUR CHANGES
123 // -------------------------------------------------------------------
125 // A collection of the important regions on the page.
126 // Cached so we don't have to keep traversing the DOM.
127 wmd.PanelCollection = function(){
128 this.buttonBar = doc.getElementById("wmd-button-bar");
129 this.preview = doc.getElementById("previewer");
130 this.output = doc.getElementById("wmd-output");
131 this.input = doc.getElementById("editor");
134 // This PanelCollection object can't be filled until after the page
136 wmd.panels = undefined;
138 // Internet explorer has problems with CSS sprite buttons that use HTML
139 // lists. When you click on the background image "button", IE will
140 // select the non-existent link text and discard the selection in the
141 // textarea. The solution to this is to cache the textarea selection
142 // on the button's mousedown event and set a flag. In the part of the
143 // code where we need to grab the selection, we check for the flag
144 // and, if it's set, use the cached area instead of querying the
147 // This ONLY affects Internet Explorer (tested on versions 6, 7
148 // and 8) and ONLY on button clicks. Keyboard shortcuts work
149 // normally since the focus never leaves the textarea.
150 wmd.ieCachedRange = null; // cached textarea selection
151 wmd.ieRetardedClick = false; // flag
153 // Returns true if the DOM element is visible, false if it's hidden.
154 // Checks if display is anything other than none.
155 util.isVisible = function (elem) {
157 if (window.getComputedStyle) {
159 return window.getComputedStyle(elem, null).getPropertyValue("display") !== "none";
161 else if (elem.currentStyle) {
163 return elem.currentStyle["display"] !== "none";
168 // Adds a listener callback to a DOM element which is fired on a specified
170 util.addEvent = function(elem, event, listener){
171 if (elem.attachEvent) {
172 // IE only. The "on" is mandatory.
173 elem.attachEvent("on" + event, listener);
177 elem.addEventListener(event, listener, false);
182 // Removes a listener callback from a DOM element which is fired on a specified
184 util.removeEvent = function(elem, event, listener){
185 if (elem.detachEvent) {
186 // IE only. The "on" is mandatory.
187 elem.detachEvent("on" + event, listener);
191 elem.removeEventListener(event, listener, false);
195 // Converts \r\n and \r to \n.
196 util.fixEolChars = function(text){
197 text = text.replace(/\r\n/g, "\n");
198 text = text.replace(/\r/g, "\n");
202 // Extends a regular expression. Returns a new RegExp
203 // using pre + regex + post as the expression.
204 // Used in a few functions where we have a base
205 // expression and we want to pre- or append some
206 // conditions to it (e.g. adding "$" to the end).
207 // The flags are unchanged.
209 // regex is a RegExp, pre and post are strings.
210 util.extendRegExp = function(regex, pre, post){
212 if (pre === null || pre === undefined)
216 if(post === null || post === undefined)
221 var pattern = regex.toString();
224 // Replace the flags with empty space and store them.
225 // Technically, this can match incorrect flags like "gmm".
226 var result = pattern.match(/\/([gim]*)$/);
227 if (result === null) {
234 // Remove the flags and slash delimiters from the regular expression.
235 pattern = pattern.replace(/(^\/|\/[gim]*$)/g, "");
236 pattern = pre + pattern + post;
238 return new RegExp(pattern, flags);
242 // Sets the image for a button passed to the WMD editor.
243 // Returns a new element with the image attached.
244 // Adds several style properties to the image.
245 util.createImage = function(img){
247 var imgPath = imageDirectory + img;
249 var elem = doc.createElement("img");
250 elem.className = "wmd-button";
257 // This simulates a modal dialog box and asks for the URL when you
258 // click the hyperlink or image buttons.
260 // text: The html for the input box.
261 // defaultInputText: The default value that appears in the input box.
262 // makeLinkMarkdown: The function which is executed when the prompt is dismissed, either via OK or Cancel
263 util.prompt = function(text, defaultInputText, makeLinkMarkdown){
265 // These variables need to be declared at this level since they are used
266 // in multiple functions.
267 var dialog; // The dialog box.
268 var background; // The background beind the dialog box.
269 var input; // The text box where you enter the hyperlink.
271 // The dialog box type(0: Link, 1: Image)
272 if(arguments.length == 4){
276 if (defaultInputText === undefined) {
277 defaultInputText = "";
280 // Used as a keydown event handler. Esc dismisses the prompt.
281 // Key code 27 is ESC.
282 var checkEscape = function(key){
283 var code = (key.charCode || key.keyCode);
289 // Dismisses the hyperlink input box.
290 // isCancel is true if we don't care about the input text.
291 // isCancel is false if we are going to keep the text.
292 var close = function(isCancel){
293 util.removeEvent(doc.body, "keydown", checkEscape);
294 var text = input.value;
300 // Fixes common pasting errors.
301 text = text.replace('http://http://', 'http://');
302 text = text.replace('http://https://', 'https://');
303 text = text.replace('http://ftp://', 'ftp://');
305 if (text.indexOf('http://') === -1 && text.indexOf('ftp://') === -1 && text.indexOf('https://') === -1 && text.indexOf('/') !== 0) {
306 text = 'http://' + text;
310 dialog.parentNode.removeChild(dialog);
311 background.parentNode.removeChild(background);
312 makeLinkMarkdown(text);
316 // Creates the background behind the hyperlink text entry box.
317 // Most of this has been moved to CSS but the div creation and
318 // browser-specific hacks remain here.
319 var createBackground = function(){
321 background = doc.createElement("div");
322 background.className = "wmd-prompt-background";
323 style = background.style;
324 style.position = "absolute";
327 style.zIndex = "1000";
329 // Some versions of Konqueror don't support transparent colors
330 // so we make the whole window transparent.
332 // Is this necessary on modern konqueror browsers?
333 if (global.isKonqueror){
334 style.backgroundColor = "transparent";
336 else if (global.isIE){
337 style.filter = "alpha(opacity=50)";
340 style.opacity = "0.5";
343 var pageSize = position.getPageSize();
344 style.height = pageSize[1] + "px";
347 style.left = doc.documentElement.scrollLeft;
348 style.width = doc.documentElement.clientWidth;
352 style.width = "100%";
355 doc.body.appendChild(background);
358 // Create the text input box form/window.
359 var createDialog = function(){
361 // The main dialog box.
362 dialog = doc.createElement("div");
363 dialog.className = "wmd-prompt-dialog";
364 dialog.style.padding = "10px;";
365 dialog.style.position = "fixed";
366 dialog.style.width = "400px";
367 dialog.style.zIndex = "1001";
370 var question = doc.createElement("div");
371 question.innerHTML = text;
372 question.style.padding = "5px";
373 dialog.appendChild(question);
375 // The web form container for the text box and buttons.
376 var form = doc.createElement("form");
377 form.onsubmit = function(){ return close(false); };
381 style.cssFloat = "left";
382 style.width = "100%";
383 style.textAlign = "center";
384 style.position = "relative";
385 dialog.appendChild(form);
387 // The input text box
388 input = doc.createElement("input");
390 input.id = "image-url";
393 input.value = defaultInputText;
395 style.display = "block";
397 style.marginLeft = style.marginRight = "auto";
398 form.appendChild(input);
400 // The upload file input
402 var upload = doc.createElement("div");
403 upload.innerHTML = uploadImageHTML;
404 upload.style.padding = "5px";
405 form.appendChild(upload);
409 var okButton = doc.createElement("input");
410 okButton.type = "button";
411 okButton.onclick = function(){ return close(false); };
412 okButton.value = "OK";
413 style = okButton.style;
414 style.margin = "10px";
415 style.display = "inline";
420 var cancelButton = doc.createElement("input");
421 cancelButton.type = "button";
422 cancelButton.onclick = function(){ return close(true); };
423 cancelButton.value = "Cancel";
424 style = cancelButton.style;
425 style.margin = "10px";
426 style.display = "inline";
429 // The order of these buttons is different on macs.
430 if (/mac/.test(nav.platform.toLowerCase())) {
431 form.appendChild(cancelButton);
432 form.appendChild(okButton);
435 form.appendChild(okButton);
436 form.appendChild(cancelButton);
439 util.addEvent(doc.body, "keydown", checkEscape);
440 dialog.style.top = "50%";
441 dialog.style.left = "50%";
442 dialog.style.display = "block";
443 if(global.isIE_5or6){
444 dialog.style.position = "absolute";
445 dialog.style.top = doc.documentElement.scrollTop + 200 + "px";
446 dialog.style.left = "50%";
448 doc.body.appendChild(dialog);
450 // This has to be done AFTER adding the dialog to the form if you
451 // want it to be centered.
452 dialog.style.marginTop = -(position.getHeight(dialog) / 2) + "px";
453 dialog.style.marginLeft = -(position.getWidth(dialog) / 2) + "px";
459 // Why is this in a zero-length timeout?
460 // Is it working around a browser bug?
461 top.setTimeout(function(){
465 var defTextLen = defaultInputText.length;
466 if (input.selectionStart !== undefined) {
467 input.selectionStart = 0;
468 input.selectionEnd = defTextLen;
470 else if (input.createTextRange) {
471 var range = input.createTextRange();
472 range.collapse(false);
473 range.moveStart("character", -defTextLen);
474 range.moveEnd("character", defTextLen);
484 // The assignment in the while loop makes jslint cranky.
485 // I'll change it to a better loop later.
486 position.getTop = function(elem, isInner){
487 var result = elem.offsetTop;
489 while (elem = elem.offsetParent) {
490 result += elem.offsetTop;
496 position.getHeight = function (elem) {
497 return elem.offsetHeight || elem.scrollHeight;
500 position.getWidth = function (elem) {
501 return elem.offsetWidth || elem.scrollWidth;
504 position.getPageSize = function(){
506 var scrollWidth, scrollHeight;
507 var innerWidth, innerHeight;
509 // It's not very clear which blocks work with which browsers.
510 if(self.innerHeight && self.scrollMaxY){
511 scrollWidth = doc.body.scrollWidth;
512 scrollHeight = self.innerHeight + self.scrollMaxY;
514 else if(doc.body.scrollHeight > doc.body.offsetHeight){
515 scrollWidth = doc.body.scrollWidth;
516 scrollHeight = doc.body.scrollHeight;
519 scrollWidth = doc.body.offsetWidth;
520 scrollHeight = doc.body.offsetHeight;
523 if(self.innerHeight){
525 innerWidth = self.innerWidth;
526 innerHeight = self.innerHeight;
528 else if(doc.documentElement && doc.documentElement.clientHeight){
529 // Some versions of IE (IE 6 w/ a DOCTYPE declaration)
530 innerWidth = doc.documentElement.clientWidth;
531 innerHeight = doc.documentElement.clientHeight;
534 // Other versions of IE
535 innerWidth = doc.body.clientWidth;
536 innerHeight = doc.body.clientHeight;
539 var maxWidth = Math.max(scrollWidth, innerWidth);
540 var maxHeight = Math.max(scrollHeight, innerHeight);
541 return [maxWidth, maxHeight, innerWidth, innerHeight];
544 // Watches the input textarea, polling at an interval and runs
545 // a callback function if anything has changed.
546 wmd.inputPoller = function(callback, interval){
548 var pollerObj = this;
549 var inputArea = wmd.panels.input;
551 // Stored start, end and text. Used to see if there are changes to the input.
556 var killHandle; // Used to cancel monitoring on destruction.
557 // Checks to see if anything has changed in the textarea.
558 // If so, it runs the callback.
559 this.tick = function(){
561 if (!util.isVisible(inputArea)) {
565 // Update the selection start and end, text.
566 if (inputArea.selectionStart || inputArea.selectionStart === 0) {
567 var start = inputArea.selectionStart;
568 var end = inputArea.selectionEnd;
569 if (start != lastStart || end != lastEnd) {
573 if (markdown != inputArea.value) {
574 markdown = inputArea.value;
583 var doTickCallback = function(){
585 if (!util.isVisible(inputArea)) {
589 // If anything has changed, call the function.
590 if (pollerObj.tick()) {
595 // Set how often we poll the textarea for changes.
596 var assignInterval = function(){
597 // previewPollInterval is set at the top of the namespace.
598 killHandle = top.setInterval(doTickCallback, interval);
601 this.destroy = function(){
602 top.clearInterval(killHandle);
608 // Handles pushing and popping TextareaStates for undo/redo commands.
609 // I should rename the stack variables to list.
610 wmd.undoManager = function(callback){
613 var undoStack = []; // A stack of undo states
614 var stackPtr = 0; // The index of the current state
616 var lastState; // The last state
618 var timer; // The setTimeout handle for cancelling the timer
621 // Set the mode for later logic steps.
622 var setMode = function(newMode, noSave){
624 if (mode != newMode) {
631 if (!global.isIE || mode != "moving") {
632 timer = top.setTimeout(refreshState, 1);
635 inputStateObj = null;
639 var refreshState = function(){
640 inputStateObj = new wmd.TextareaState();
645 this.setCommandMode = function(){
648 timer = top.setTimeout(refreshState, 0);
651 this.canUndo = function(){
655 this.canRedo = function(){
656 if (undoStack[stackPtr + 1]) {
662 // Removes the last state and restores it.
663 this.undo = function(){
665 if (undoObj.canUndo()) {
667 // What about setting state -1 to null or checking for undefined?
672 undoStack[stackPtr] = new wmd.TextareaState();
673 undoStack[--stackPtr].restore();
682 wmd.panels.input.focus();
687 this.redo = function(){
689 if (undoObj.canRedo()) {
691 undoStack[++stackPtr].restore();
699 wmd.panels.input.focus();
703 // Push the input area state to the stack.
704 var saveState = function(){
706 var currState = inputStateObj || new wmd.TextareaState();
711 if (mode == "moving") {
713 lastState = currState;
718 if (undoStack[stackPtr - 1].text != lastState.text) {
719 undoStack[stackPtr++] = lastState;
723 undoStack[stackPtr++] = currState;
724 undoStack[stackPtr + 1] = null;
730 var handleCtrlYZ = function(event){
734 if (event.ctrlKey || event.metaKey) {
736 // IE and Opera do not support charCode.
737 var keyCode = event.charCode || event.keyCode;
738 var keyCodeChar = String.fromCharCode(keyCode);
740 switch (keyCodeChar) {
748 if (!event.shiftKey) {
760 if (event.preventDefault) {
761 event.preventDefault();
764 top.event.returnValue = false;
770 // Set the mode depending on what is going on in the input area.
771 var handleModeChange = function(event){
773 if (!event.ctrlKey && !event.metaKey) {
775 var keyCode = event.keyCode;
777 if ((keyCode >= 33 && keyCode <= 40) || (keyCode >= 63232 && keyCode <= 63235)) {
778 // 33 - 40: page up/dn and arrow keys
779 // 63232 - 63235: page up/dn and arrow keys on safari
782 else if (keyCode == 8 || keyCode == 46 || keyCode == 127) {
788 else if (keyCode == 13) {
792 else if (keyCode == 27) {
796 else if ((keyCode < 16 || keyCode > 20) && keyCode != 91) {
797 // 16-20 are shift, etc.
798 // 91: left window key
799 // I think this might be a little messed up since there are
800 // a lot of nonprinting keys above 20.
806 var setEventHandlers = function(){
808 util.addEvent(wmd.panels.input, "keypress", function(event){
811 if ((event.ctrlKey || event.metaKey) && (event.keyCode == 89 || event.keyCode == 90)) {
812 event.preventDefault();
816 var handlePaste = function(){
817 if (global.isIE || (inputStateObj && inputStateObj.text != wmd.panels.input.value)) {
818 if (timer == undefined) {
826 // pastePollInterval is specified at the beginning of this namespace.
827 poller = new wmd.inputPoller(handlePaste, pastePollInterval);
829 util.addEvent(wmd.panels.input, "keydown", handleCtrlYZ);
830 util.addEvent(wmd.panels.input, "keydown", handleModeChange);
832 util.addEvent(wmd.panels.input, "mousedown", function(){
835 wmd.panels.input.onpaste = handlePaste;
836 wmd.panels.input.ondrop = handlePaste;
839 var init = function(){
845 this.destroy = function(){
854 // I think my understanding of how the buttons and callbacks are stored in the array is incomplete.
855 wmd.editor = function(previewRefreshCallback){
857 if (!previewRefreshCallback) {
858 previewRefreshCallback = function(){};
861 var inputBox = wmd.panels.input;
863 var offsetHeight = 0;
870 var div; // This name is pretty ambiguous. I should rename this.
872 // Used to cancel recurring events from setInterval.
875 var undoMgr; // The undo manager
877 // Perform the button's action.
878 var doClick = function(button){
885 undoMgr.setCommandMode();
888 var state = new wmd.TextareaState();
894 var chunks = state.getChunks();
896 // Some commands launch a "modal" prompt dialog. Javascript
897 // can't really make a modal dialog box and the WMD code
898 // will continue to execute while the dialog is displayed.
899 // This prevents the dialog pattern I'm used to and means
900 // I can't do something like this:
902 // var link = CreateLinkDialog();
903 // makeMarkdownLink(link);
905 // Instead of this straightforward method of handling a
906 // dialog I have to pass any code which would execute
907 // after the dialog is dismissed (e.g. link creation)
908 // in a function parameter.
910 // Yes this is awkward and I think it sucks, but there's
911 // no real workaround. Only the image and link code
912 // create dialogs and require the function pointers.
913 var fixupInputArea = function(){
918 state.setChunks(chunks);
922 previewRefreshCallback();
925 var useDefaultText = true;
926 var noCleanup = button.textOp(chunks, fixupInputArea, useDefaultText);
934 if (button.execute) {
935 button.execute(editObj);
939 var setUndoRedoButtonStates = function(){
941 setupButton(document.getElementById("wmd-undo-button"), undoMgr.canUndo());
942 setupButton(document.getElementById("wmd-redo-button"), undoMgr.canRedo());
946 var setupButton = function(button, isEnabled) {
948 var normalYShift = "0px";
949 var disabledYShift = "-20px";
950 var highlightYShift = "-40px";
953 button.style.backgroundPosition = button.XShift + " " + normalYShift;
954 button.onmouseover = function(){
955 this.style.backgroundPosition = this.XShift + " " + highlightYShift;
958 button.onmouseout = function(){
959 this.style.backgroundPosition = this.XShift + " " + normalYShift;
962 // IE tries to select the background image "button" text (it's
963 // implemented in a list item) so we have to cache the selection
966 button.onmousedown = function() {
967 wmd.ieRetardedClick = true;
968 wmd.ieCachedRange = document.selection.createRange();
974 button.onclick = function() {
975 if (this.onmouseout) {
984 button.style.backgroundPosition = button.XShift + " " + disabledYShift;
985 button.onmouseover = button.onmouseout = button.onclick = function(){};
989 var makeSpritedButtonRow = function(){
991 var buttonBar = document.getElementById("wmd-button-bar");
993 var normalYShift = "0px";
994 var disabledYShift = "-20px";
995 var highlightYShift = "-40px";
997 var buttonRow = document.createElement("ul");
998 buttonRow.id = "wmd-button-row";
999 buttonRow = buttonBar.appendChild(buttonRow);
1002 var boldButton = document.createElement("li");
1003 boldButton.className = "wmd-button";
1004 boldButton.id = "wmd-bold-button";
1005 boldButton.title = toolbar_strong_label;
1006 boldButton.XShift = "0px";
1007 boldButton.textOp = command.doBold;
1008 setupButton(boldButton, true);
1009 buttonRow.appendChild(boldButton);
1011 var italicButton = document.createElement("li");
1012 italicButton.className = "wmd-button";
1013 italicButton.id = "wmd-italic-button";
1014 italicButton.title = toolbar_emphasis_label;
1015 italicButton.XShift = "-20px";
1016 italicButton.textOp = command.doItalic;
1017 setupButton(italicButton, true);
1018 buttonRow.appendChild(italicButton);
1020 var spacer1 = document.createElement("li");
1021 spacer1.className = "wmd-spacer";
1022 spacer1.id = "wmd-spacer1";
1023 buttonRow.appendChild(spacer1);
1025 var linkButton = document.createElement("li");
1026 linkButton.className = "wmd-button";
1027 linkButton.id = "wmd-link-button";
1028 linkButton.title = toolbar_hyperlink_label;
1029 linkButton.XShift = "-40px";
1030 linkButton.textOp = function(chunk, postProcessing, useDefaultText){
1031 return command.doLinkOrImage(chunk, postProcessing, false);
1033 setupButton(linkButton, true);
1034 buttonRow.appendChild(linkButton);
1036 var quoteButton = document.createElement("li");
1037 quoteButton.className = "wmd-button";
1038 quoteButton.id = "wmd-quote-button";
1039 quoteButton.title = toolbar_blockquote_label;
1040 quoteButton.XShift = "-60px";
1041 quoteButton.textOp = command.doBlockquote;
1042 setupButton(quoteButton, true);
1043 buttonRow.appendChild(quoteButton);
1045 var codeButton = document.createElement("li");
1046 codeButton.className = "wmd-button";
1047 codeButton.id = "wmd-code-button";
1048 codeButton.title = toolbar_code_label;
1049 codeButton.XShift = "-80px";
1050 codeButton.textOp = command.doCode;
1051 setupButton(codeButton, true);
1052 buttonRow.appendChild(codeButton);
1054 var imageButton = document.createElement("li");
1055 imageButton.className = "wmd-button";
1056 imageButton.id = "wmd-image-button";
1057 imageButton.title = toolbar_image_label;
1058 imageButton.XShift = "-100px";
1059 imageButton.textOp = function(chunk, postProcessing, useDefaultText){
1060 return command.doLinkOrImage(chunk, postProcessing, true);
1062 setupButton(imageButton, true);
1063 buttonRow.appendChild(imageButton);
1065 var spacer2 = document.createElement("li");
1066 spacer2.className = "wmd-spacer";
1067 spacer2.id = "wmd-spacer2";
1068 buttonRow.appendChild(spacer2);
1070 var olistButton = document.createElement("li");
1071 olistButton.className = "wmd-button";
1072 olistButton.id = "wmd-olist-button";
1073 olistButton.title = toolbar_numbered_label;
1074 olistButton.XShift = "-120px";
1075 olistButton.textOp = function(chunk, postProcessing, useDefaultText){
1076 command.doList(chunk, postProcessing, true, useDefaultText);
1078 setupButton(olistButton, true);
1079 buttonRow.appendChild(olistButton);
1081 var ulistButton = document.createElement("li");
1082 ulistButton.className = "wmd-button";
1083 ulistButton.id = "wmd-ulist-button";
1084 ulistButton.title = toolbar_bulleted_label;
1085 ulistButton.XShift = "-140px";
1086 ulistButton.textOp = function(chunk, postProcessing, useDefaultText){
1087 command.doList(chunk, postProcessing, false, useDefaultText);
1089 setupButton(ulistButton, true);
1090 buttonRow.appendChild(ulistButton);
1092 var headingButton = document.createElement("li");
1093 headingButton.className = "wmd-button";
1094 headingButton.id = "wmd-heading-button";
1095 headingButton.title = toolbar_heading_label;
1096 headingButton.XShift = "-160px";
1097 headingButton.textOp = command.doHeading;
1098 setupButton(headingButton, true);
1099 buttonRow.appendChild(headingButton);
1101 var hrButton = document.createElement("li");
1102 hrButton.className = "wmd-button";
1103 hrButton.id = "wmd-hr-button";
1104 hrButton.title = toolbar_horizontal_label;
1105 hrButton.XShift = "-180px";
1106 hrButton.textOp = command.doHorizontalRule;
1107 setupButton(hrButton, true);
1108 buttonRow.appendChild(hrButton);
1110 var spacer3 = document.createElement("li");
1111 spacer3.className = "wmd-spacer";
1112 spacer3.id = "wmd-spacer3";
1113 buttonRow.appendChild(spacer3);
1115 var undoButton = document.createElement("li");
1116 undoButton.className = "wmd-button";
1117 undoButton.id = "wmd-undo-button";
1118 undoButton.title = toolbar_undo_label;
1119 undoButton.XShift = "-200px";
1120 undoButton.execute = function(manager){
1123 setupButton(undoButton, true);
1124 buttonRow.appendChild(undoButton);
1126 var redoButton = document.createElement("li");
1127 redoButton.className = "wmd-button";
1128 redoButton.id = "wmd-redo-button";
1129 redoButton.title = toolbar_redo_label;
1130 if (/win/.test(nav.platform.toLowerCase())) {
1131 redoButton.title = toolbar_redo_label;
1134 // mac and other non-Windows platforms
1135 redoButton.title = $.i18n._('redo') + " - Ctrl+Shift+Z";
1137 redoButton.XShift = "-220px";
1138 redoButton.execute = function(manager){
1141 setupButton(redoButton, true);
1142 buttonRow.appendChild(redoButton);
1144 setUndoRedoButtonStates();
1147 var setupEditor = function(){
1149 if (/\?noundo/.test(doc.location.href)) {
1150 wmd.nativeUndo = true;
1153 if (!wmd.nativeUndo) {
1154 undoMgr = new wmd.undoManager(function(){
1155 previewRefreshCallback();
1156 setUndoRedoButtonStates();
1160 makeSpritedButtonRow();
1163 var keyEvent = "keydown";
1164 if (global.isOpera) {
1165 keyEvent = "keypress";
1168 util.addEvent(inputBox, keyEvent, function(key){
1170 // Check to see if we have a button key and, if so execute the callback.
1171 if (key.ctrlKey || key.metaKey) {
1173 var keyCode = key.charCode || key.keyCode;
1174 var keyCodeStr = String.fromCharCode(keyCode).toLowerCase();
1176 // Bugfix for messed up DEL and .
1177 if (keyCode === 46) {
1180 if (keyCode === 190) {
1184 switch(keyCodeStr) {
1186 doClick(document.getElementById("wmd-bold-button"));
1189 doClick(document.getElementById("wmd-italic-button"));
1192 doClick(document.getElementById("wmd-link-button"));
1195 doClick(document.getElementById("wmd-quote-button"));
1198 doClick(document.getElementById("wmd-code-button"));
1201 doClick(document.getElementById("wmd-image-button"));
1204 doClick(document.getElementById("wmd-olist-button"));
1207 doClick(document.getElementById("wmd-ulist-button"));
1210 doClick(document.getElementById("wmd-heading-button"));
1213 doClick(document.getElementById("wmd-hr-button"));
1216 doClick(document.getElementById("wmd-redo-button"));
1220 doClick(document.getElementById("wmd-redo-button"));
1223 doClick(document.getElementById("wmd-undo-button"));
1231 if (key.preventDefault) {
1232 key.preventDefault();
1236 top.event.returnValue = false;
1241 // Auto-continue lists, code blocks and block quotes when
1242 // the enter key is pressed.
1243 util.addEvent(inputBox, "keyup", function(key){
1244 if (!key.shiftKey && !key.ctrlKey && !key.metaKey) {
1245 var keyCode = key.charCode || key.keyCode;
1246 // Key code 13 is Enter
1247 if (keyCode === 13) {
1249 fakeButton.textOp = command.doAutoindent;
1250 doClick(fakeButton);
1255 // Disable ESC clearing the input textarea on IE
1257 util.addEvent(inputBox, "keydown", function(key){
1258 var code = key.keyCode;
1259 // Key code 27 is ESC
1266 if (inputBox.form) {
1267 var submitCallback = inputBox.form.onsubmit;
1268 inputBox.form.onsubmit = function(){
1270 if (submitCallback) {
1271 return submitCallback.apply(this, arguments);
1277 // Convert the contents of the input textarea to HTML in the output/preview panels.
1278 var convertToHtml = function(){
1281 var markdownConverter = new wmd.showdown.converter();
1283 var text = inputBox.value;
1285 var callback = function(){
1286 inputBox.value = text;
1289 if (!/markdown/.test(wmd.wmd_env.output.toLowerCase())) {
1290 if (markdownConverter) {
1291 inputBox.value = markdownConverter.makeHtml(text);
1292 top.setTimeout(callback, 0);
1299 this.undo = function(){
1305 this.redo = function(){
1311 // This is pretty useless. The setupEditor function contents
1312 // should just be copied here.
1313 var init = function(){
1317 this.destroy = function(){
1321 if (div.parentNode) {
1322 div.parentNode.removeChild(div);
1325 inputBox.style.marginTop = "";
1327 top.clearInterval(creationHandle);
1333 // The input textarea state/contents.
1334 // This is used to implement undo/redo by the undo manager.
1335 wmd.TextareaState = function(){
1338 var stateObj = this;
1339 var inputArea = wmd.panels.input;
1341 this.init = function() {
1343 if (!util.isVisible(inputArea)) {
1347 this.setInputAreaSelectionStartEnd();
1348 this.scrollTop = inputArea.scrollTop;
1349 if (!this.text && inputArea.selectionStart || inputArea.selectionStart === 0) {
1350 this.text = inputArea.value;
1355 // Sets the selected text in the input box after we've performed an
1357 this.setInputAreaSelection = function(){
1359 if (!util.isVisible(inputArea)) {
1363 if (inputArea.selectionStart !== undefined && !global.isOpera) {
1366 inputArea.selectionStart = stateObj.start;
1367 inputArea.selectionEnd = stateObj.end;
1368 inputArea.scrollTop = stateObj.scrollTop;
1370 else if (doc.selection) {
1372 if (doc.activeElement && doc.activeElement !== inputArea) {
1377 var range = inputArea.createTextRange();
1378 range.moveStart("character", -inputArea.value.length);
1379 range.moveEnd("character", -inputArea.value.length);
1380 range.moveEnd("character", stateObj.end);
1381 range.moveStart("character", stateObj.start);
1386 this.setInputAreaSelectionStartEnd = function(){
1388 if (inputArea.selectionStart || inputArea.selectionStart === 0) {
1390 stateObj.start = inputArea.selectionStart;
1391 stateObj.end = inputArea.selectionEnd;
1393 else if (doc.selection) {
1395 stateObj.text = util.fixEolChars(inputArea.value);
1397 // IE loses the selection in the textarea when buttons are
1398 // clicked. On IE we cache the selection and set a flag
1399 // which we check for here.
1401 if(wmd.ieRetardedClick && wmd.ieCachedRange) {
1402 range = wmd.ieCachedRange;
1403 wmd.ieRetardedClick = false;
1406 range = doc.selection.createRange();
1409 var fixedRange = util.fixEolChars(range.text);
1410 var marker = "\x07";
1411 var markedRange = marker + fixedRange + marker;
1412 range.text = markedRange;
1413 var inputText = util.fixEolChars(inputArea.value);
1415 range.moveStart("character", -markedRange.length);
1416 range.text = fixedRange;
1418 stateObj.start = inputText.indexOf(marker);
1419 stateObj.end = inputText.lastIndexOf(marker) - marker.length;
1421 var len = stateObj.text.length - util.fixEolChars(inputArea.value).length;
1424 range.moveStart("character", -fixedRange.length);
1429 range.text = fixedRange;
1432 this.setInputAreaSelection();
1436 // Restore this state into the input area.
1437 this.restore = function(){
1439 if (stateObj.text != undefined && stateObj.text != inputArea.value) {
1440 inputArea.value = stateObj.text;
1442 this.setInputAreaSelection();
1443 inputArea.scrollTop = stateObj.scrollTop;
1446 // Gets a collection of HTML chunks from the inptut textarea.
1447 this.getChunks = function(){
1449 var chunk = new wmd.Chunks();
1451 chunk.before = util.fixEolChars(stateObj.text.substring(0, stateObj.start));
1452 chunk.startTag = "";
1453 chunk.selection = util.fixEolChars(stateObj.text.substring(stateObj.start, stateObj.end));
1455 chunk.after = util.fixEolChars(stateObj.text.substring(stateObj.end));
1456 chunk.scrollTop = stateObj.scrollTop;
1461 // Sets the TextareaState properties given a chunk of markdown.
1462 this.setChunks = function(chunk){
1464 chunk.before = chunk.before + chunk.startTag;
1465 chunk.after = chunk.endTag + chunk.after;
1467 if (global.isOpera) {
1468 chunk.before = chunk.before.replace(/\n/g, "\r\n");
1469 chunk.selection = chunk.selection.replace(/\n/g, "\r\n");
1470 chunk.after = chunk.after.replace(/\n/g, "\r\n");
1473 this.start = chunk.before.length;
1474 this.end = chunk.before.length + chunk.selection.length;
1475 this.text = chunk.before + chunk.selection + chunk.after;
1476 this.scrollTop = chunk.scrollTop;
1482 // before: contains all the text in the input box BEFORE the selection.
1483 // after: contains all the text in the input box AFTER the selection.
1484 wmd.Chunks = function(){
1487 // startRegex: a regular expression to find the start tag
1488 // endRegex: a regular expresssion to find the end tag
1489 wmd.Chunks.prototype.findTags = function(startRegex, endRegex){
1491 var chunkObj = this;
1496 regex = util.extendRegExp(startRegex, "", "$");
1498 this.before = this.before.replace(regex,
1500 chunkObj.startTag = chunkObj.startTag + match;
1504 regex = util.extendRegExp(startRegex, "^", "");
1506 this.selection = this.selection.replace(regex,
1508 chunkObj.startTag = chunkObj.startTag + match;
1515 regex = util.extendRegExp(endRegex, "", "$");
1517 this.selection = this.selection.replace(regex,
1519 chunkObj.endTag = match + chunkObj.endTag;
1523 regex = util.extendRegExp(endRegex, "^", "");
1525 this.after = this.after.replace(regex,
1527 chunkObj.endTag = match + chunkObj.endTag;
1533 // If remove is false, the whitespace is transferred
1534 // to the before/after regions.
1536 // If remove is true, the whitespace disappears.
1537 wmd.Chunks.prototype.trimWhitespace = function(remove){
1539 this.selection = this.selection.replace(/^(\s*)/, "");
1542 this.before += re.$1;
1545 this.selection = this.selection.replace(/(\s*)$/, "");
1548 this.after = re.$1 + this.after;
1553 wmd.Chunks.prototype.addBlankLines = function(nLinesBefore, nLinesAfter, findExtraNewlines){
1555 if (nLinesBefore === undefined) {
1559 if (nLinesAfter === undefined) {
1567 var replacementText;
1569 this.selection = this.selection.replace(/(^\n*)/, "");
1570 this.startTag = this.startTag + re.$1;
1571 this.selection = this.selection.replace(/(\n*$)/, "");
1572 this.endTag = this.endTag + re.$1;
1573 this.startTag = this.startTag.replace(/(^\n*)/, "");
1574 this.before = this.before + re.$1;
1575 this.endTag = this.endTag.replace(/(\n*$)/, "");
1576 this.after = this.after + re.$1;
1580 regexText = replacementText = "";
1582 while (nLinesBefore--) {
1583 regexText += "\\n?";
1584 replacementText += "\n";
1587 if (findExtraNewlines) {
1590 this.before = this.before.replace(new re(regexText + "$", ""), replacementText);
1595 regexText = replacementText = "";
1597 while (nLinesAfter--) {
1598 regexText += "\\n?";
1599 replacementText += "\n";
1601 if (findExtraNewlines) {
1605 this.after = this.after.replace(new re(regexText, ""), replacementText);
1609 // The markdown symbols - 4 spaces = code, > = blockquote, etc.
1610 command.prefixes = "(?:\\s{4,}|\\s*>|\\s*-\\s+|\\s*\\d+\\.|=|\\+|-|_|\\*|#|\\s*\\[[^\n]]+\\]:)";
1612 // Remove markdown symbols from the chunk selection.
1613 command.unwrap = function(chunk){
1614 var txt = new re("([^\\n])\\n(?!(\\n|" + command.prefixes + "))", "g");
1615 chunk.selection = chunk.selection.replace(txt, "$1 $2");
1618 command.wrap = function(chunk, len){
1619 command.unwrap(chunk);
1620 var regex = new re("(.{1," + len + "})( +|$\\n?)", "gm");
1622 chunk.selection = chunk.selection.replace(regex, function(line, marked){
1623 if (new re("^" + command.prefixes, "").test(line)) {
1626 return marked + "\n";
1629 chunk.selection = chunk.selection.replace(/\s+$/, "");
1632 command.doBold = function(chunk, postProcessing, useDefaultText){
1633 return command.doBorI(chunk, 2, "strong text");
1636 command.doItalic = function(chunk, postProcessing, useDefaultText){
1637 return command.doBorI(chunk, 1, "emphasized text");
1640 // chunk: The selected region that will be enclosed with */**
1641 // nStars: 1 for italics, 2 for bold
1642 // insertText: If you just click the button without highlighting text, this gets inserted
1643 command.doBorI = function(chunk, nStars, insertText){
1645 // Get rid of whitespace and fixup newlines.
1646 chunk.trimWhitespace();
1647 chunk.selection = chunk.selection.replace(/\n{2,}/g, "\n");
1649 // Look for stars before and after. Is the chunk already marked up?
1650 chunk.before.search(/(\**$)/);
1651 var starsBefore = re.$1;
1653 chunk.after.search(/(^\**)/);
1654 var starsAfter = re.$1;
1656 var prevStars = Math.min(starsBefore.length, starsAfter.length);
1658 // Remove stars if we have to since the button acts as a toggle.
1659 if ((prevStars >= nStars) && (prevStars != 2 || nStars != 1)) {
1660 chunk.before = chunk.before.replace(re("[*]{" + nStars + "}$", ""), "");
1661 chunk.after = chunk.after.replace(re("^[*]{" + nStars + "}", ""), "");
1663 else if (!chunk.selection && starsAfter) {
1664 // It's not really clear why this code is necessary. It just moves
1665 // some arbitrary stuff around.
1666 chunk.after = chunk.after.replace(/^([*_]*)/, "");
1667 chunk.before = chunk.before.replace(/(\s?)$/, "");
1668 var whitespace = re.$1;
1669 chunk.before = chunk.before + starsAfter + whitespace;
1673 // In most cases, if you don't have any selected text and click the button
1674 // you'll get a selected, marked up region with the default text inserted.
1675 if (!chunk.selection && !starsAfter) {
1676 chunk.selection = insertText;
1679 // Add the true markup.
1680 var markup = nStars <= 1 ? "*" : "**"; // shouldn't the test be = ?
1681 chunk.before = chunk.before + markup;
1682 chunk.after = markup + chunk.after;
1688 command.stripLinkDefs = function(text, defsToAdd){
1690 text = text.replace(/^[ ]{0,3}\[(\d+)\]:[ \t]*\n?[ \t]*<?(\S+?)>?[ \t]*\n?[ \t]*(?:(\n*)["(](.+?)[")][ \t]*)?(?:\n+|$)/gm,
1691 function(totalMatch, id, link, newlines, title){
1692 defsToAdd[id] = totalMatch.replace(/\s*$/, "");
1694 // Strip the title and return that separately.
1695 defsToAdd[id] = totalMatch.replace(/["(](.+?)[")]$/, "");
1696 return newlines + title;
1704 command.addLinkDef = function(chunk, linkDef){
1706 var refNumber = 0; // The current reference number
1707 var defsToAdd = {}; //
1708 // Start with a clean slate by removing all previous link definitions.
1709 chunk.before = command.stripLinkDefs(chunk.before, defsToAdd);
1710 chunk.selection = command.stripLinkDefs(chunk.selection, defsToAdd);
1711 chunk.after = command.stripLinkDefs(chunk.after, defsToAdd);
1714 var regex = /(\[(?:\[[^\]]*\]|[^\[\]])*\][ ]?(?:\n[ ]*)?\[)(\d+)(\])/g;
1716 var addDefNumber = function(def){
1718 def = def.replace(/^[ ]{0,3}\[(\d+)\]:/, " [" + refNumber + "]:");
1722 var getLink = function(wholeMatch, link, id, end){
1724 if (defsToAdd[id]) {
1725 addDefNumber(defsToAdd[id]);
1726 return link + refNumber + end;
1732 chunk.before = chunk.before.replace(regex, getLink);
1735 addDefNumber(linkDef);
1738 chunk.selection = chunk.selection.replace(regex, getLink);
1741 var refOut = refNumber;
1743 chunk.after = chunk.after.replace(regex, getLink);
1746 chunk.after = chunk.after.replace(/\n*$/, "");
1749 chunk.selection = chunk.selection.replace(/\n*$/, "");
1752 chunk.after += "\n\n" + defs;
1757 command.doLinkOrImage = function(chunk, postProcessing, isImage){
1759 chunk.trimWhitespace();
1760 chunk.findTags(/\s*!?\[/, /\][ ]?(?:\n[ ]*)?(\[.*?\])?/);
1762 if (chunk.endTag.length > 1) {
1764 chunk.startTag = chunk.startTag.replace(/!?\[/, "");
1766 command.addLinkDef(chunk, null);
1771 if (/\n\n/.test(chunk.selection)) {
1772 command.addLinkDef(chunk, null);
1776 // The function to be executed when you enter a link and press OK or Cancel.
1777 // Marks up the link and adds the ref.
1778 var makeLinkMarkdown = function(link){
1780 if (link !== null) {
1782 chunk.startTag = chunk.endTag = "";
1783 var linkDef = " [999]: " + link;
1785 var num = command.addLinkDef(chunk, linkDef);
1786 chunk.startTag = isImage ? "![" : "[";
1787 chunk.endTag = "][" + num + "]";
1789 if (!chunk.selection) {
1791 chunk.selection = "alt text";
1794 chunk.selection = "link text";
1802 // add fourth param to identify image window
1803 util.prompt(imageDialogText, imageDefaultText, makeLinkMarkdown, 1);
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;
2111 chunk.before = chunk.before.replace(/\n?$/,"\n");
2114 chunk.after = chunk.after.replace(/^\n?/,"\n");
2117 chunk.before = chunk.before.replace(/(((\n|^)(\n[ \t]*)*>(.+\n)*.*)+(\n[ \t]*)*$)/,
2118 function(totalMatch){
2119 chunk.startTag = totalMatch;
2123 chunk.after = chunk.after.replace(/^(((\n|^)(\n[ \t]*)*>(.+\n)*.*)+(\n[ \t]*)*)/,
2124 function(totalMatch){
2125 chunk.endTag = totalMatch;
2129 var replaceBlanksInTags = function(useBracket){
2131 var replacement = useBracket ? "> " : "";
2134 chunk.startTag = chunk.startTag.replace(/\n((>|\s)*)\n$/,
2135 function(totalMatch, markdown){
2136 return "\n" + markdown.replace(/^[ ]{0,3}>?[ \t]*$/gm, replacement) + "\n";
2140 chunk.endTag = chunk.endTag.replace(/^\n((>|\s)*)\n/,
2141 function(totalMatch, markdown){
2142 return "\n" + markdown.replace(/^[ ]{0,3}>?[ \t]*$/gm, replacement) + "\n";
2147 if(/^(?![ ]{0,3}>)/m.test(chunk.selection)){
2148 command.wrap(chunk, wmd.wmd_env.lineLength - 2);
2149 chunk.selection = chunk.selection.replace(/^/gm, "> ");
2150 replaceBlanksInTags(true);
2151 chunk.addBlankLines();
2154 chunk.selection = chunk.selection.replace(/^[ ]{0,3}> ?/gm, "");
2155 command.unwrap(chunk);
2156 replaceBlanksInTags(false);
2158 if(!/^(\n|^)[ ]{0,3}>/.test(chunk.selection) && chunk.startTag){
2159 chunk.startTag = chunk.startTag.replace(/\n{0,2}$/, "\n\n");
2162 if(!/(\n|^)[ ]{0,3}>.*$/.test(chunk.selection) && chunk.endTag){
2163 chunk.endTag=chunk.endTag.replace(/^\n{0,2}/, "\n\n");
2167 if(!/\n/.test(chunk.selection)){
2168 chunk.selection = chunk.selection.replace(/^(> *)/,
2169 function(wholeMatch, blanks){
2170 chunk.startTag += blanks;
2176 command.doCode = function(chunk, postProcessing, useDefaultText){
2178 var hasTextBefore = /\S[ ]*$/.test(chunk.before);
2179 var hasTextAfter = /^[ ]*\S/.test(chunk.after);
2181 // Use 'four space' markdown if the selection is on its own
2182 // line or is multiline.
2183 if((!hasTextAfter && !hasTextBefore) || /\n/.test(chunk.selection)){
2185 chunk.before = chunk.before.replace(/[ ]{4}$/,
2186 function(totalMatch){
2187 chunk.selection = totalMatch + chunk.selection;
2191 var nLinesBefore = 1;
2192 var nLinesAfter = 1;
2195 if(/\n(\t|[ ]{4,}).*\n$/.test(chunk.before) || chunk.after === ""){
2198 if(/^\n(\t|[ ]{4,})/.test(chunk.after)){
2199 nLinesAfter = 0; // This needs to happen on line 1
2202 chunk.addBlankLines(nLinesBefore, nLinesAfter);
2204 if(!chunk.selection){
2205 chunk.startTag = " ";
2206 chunk.selection = useDefaultText ? "enter code here" : "";
2209 if(/^[ ]{0,3}\S/m.test(chunk.selection)){
2210 chunk.selection = chunk.selection.replace(/^/gm, " ");
2213 chunk.selection = chunk.selection.replace(/^[ ]{4}/gm, "");
2218 // Use backticks (`) to delimit the code block.
2220 chunk.trimWhitespace();
2221 chunk.findTags(/`/, /`/);
2223 if(!chunk.startTag && !chunk.endTag){
2224 chunk.startTag = chunk.endTag="`";
2225 if(!chunk.selection){
2226 chunk.selection = useDefaultText ? "enter code here" : "";
2229 else if(chunk.endTag && !chunk.startTag){
2230 chunk.before += chunk.endTag;
2234 chunk.startTag = chunk.endTag="";
2239 command.doList = function(chunk, postProcessing, isNumberedList, useDefaultText){
2241 // These are identical except at the very beginning and end.
2242 // Should probably use the regex extension function to make this clearer.
2243 var previousItemsRegex = /(\n|^)(([ ]{0,3}([*+-]|\d+[.])[ \t]+.*)(\n.+|\n{2,}([*+-].*|\d+[.])[ \t]+.*|\n{2,}[ \t]+\S.*)*)\n*$/;
2244 var nextItemsRegex = /^\n*(([ ]{0,3}([*+-]|\d+[.])[ \t]+.*)(\n.+|\n{2,}([*+-].*|\d+[.])[ \t]+.*|\n{2,}[ \t]+\S.*)*)\n*/;
2246 // The default bullet is a dash but others are possible.
2247 // This has nothing to do with the particular HTML bullet,
2248 // it's just a markdown bullet.
2251 // The number in a numbered list.
2254 // Get the item prefix - e.g. " 1. " for a numbered list, " - " for a bulleted list.
2255 var getItemPrefix = function(){
2258 prefix = " " + num + ". ";
2262 prefix = " " + bullet + " ";
2267 // Fixes the prefixes of the other list items.
2268 var getPrefixedItem = function(itemText){
2270 // The numbering flag is unset when called by autoindent.
2271 if(isNumberedList === undefined){
2272 isNumberedList = /^\s*\d/.test(itemText);
2275 // Renumber/bullet the list element.
2276 itemText = itemText.replace(/^[ ]{0,3}([*+-]|\d+[.])\s/gm,
2278 return getItemPrefix();
2284 chunk.findTags(/(\n|^)*[ ]{0,3}([*+-]|\d+[.])\s+/, null);
2286 if(chunk.before && !/\n$/.test(chunk.before) && !/^\n/.test(chunk.startTag)){
2287 chunk.before += chunk.startTag;
2288 chunk.startTag = "";
2293 var hasDigits = /\d+[.]/.test(chunk.startTag);
2294 chunk.startTag = "";
2295 chunk.selection = chunk.selection.replace(/\n[ ]{4}/g, "\n");
2296 command.unwrap(chunk);
2297 chunk.addBlankLines();
2300 // Have to renumber the bullet points if this is a numbered list.
2301 chunk.after = chunk.after.replace(nextItemsRegex, getPrefixedItem);
2303 if(isNumberedList == hasDigits){
2308 var nLinesBefore = 1;
2310 chunk.before = chunk.before.replace(previousItemsRegex,
2312 if(/^\s*([*+-])/.test(itemText)){
2315 nLinesBefore = /[^\n]\n\n[^\n]/.test(itemText) ? 1 : 0;
2316 return getPrefixedItem(itemText);
2319 if(!chunk.selection){
2320 chunk.selection = useDefaultText ? "List item" : " ";
2323 var prefix = getItemPrefix();
2325 var nLinesAfter = 1;
2327 chunk.after = chunk.after.replace(nextItemsRegex,
2329 nLinesAfter = /[^\n]\n\n[^\n]/.test(itemText) ? 1 : 0;
2330 return getPrefixedItem(itemText);
2333 chunk.trimWhitespace(true);
2334 chunk.addBlankLines(nLinesBefore, nLinesAfter, true);
2335 chunk.startTag = prefix;
2336 var spaces = prefix.replace(/./g, " ");
2337 command.wrap(chunk, wmd.wmd_env.lineLength - spaces.length);
2338 chunk.selection = chunk.selection.replace(/\n/g, "\n" + spaces);
2342 command.doHeading = function(chunk, postProcessing, useDefaultText){
2344 // Remove leading/trailing whitespace and reduce internal spaces to single spaces.
2345 chunk.selection = chunk.selection.replace(/\s+/g, " ");
2346 chunk.selection = chunk.selection.replace(/(^\s+|\s+$)/g, "");
2348 // If we clicked the button with no selected text, we just
2349 // make a level 2 hash header around some default text.
2350 if(!chunk.selection){
2351 chunk.startTag = "## ";
2352 chunk.selection = "Heading";
2353 chunk.endTag = " ##";
2357 var headerLevel = 0; // The existing header level of the selected text.
2359 // Remove any existing hash heading markdown and save the header level.
2360 chunk.findTags(/#+[ ]*/, /[ ]*#+/);
2361 if(/#+/.test(chunk.startTag)){
2362 headerLevel = re.lastMatch.length;
2364 chunk.startTag = chunk.endTag = "";
2366 // Try to get the current header level by looking for - and = in the line
2367 // below the selection.
2368 chunk.findTags(null, /\s?(-+|=+)/);
2369 if(/=+/.test(chunk.endTag)){
2372 if(/-+/.test(chunk.endTag)){
2376 // Skip to the next line so we can create the header markdown.
2377 chunk.startTag = chunk.endTag = "";
2378 chunk.addBlankLines(1, 1);
2380 // We make a level 2 header if there is no current header.
2381 // If there is a header level, we substract one from the header level.
2382 // If it's already a level 1 header, it's removed.
2383 var headerLevelToCreate = headerLevel == 0 ? 2 : headerLevel - 1;
2385 if(headerLevelToCreate > 0){
2387 // The button only creates level 1 and 2 underline headers.
2388 // Why not have it iterate over hash header levels? Wouldn't that be easier and cleaner?
2389 var headerChar = headerLevelToCreate >= 2 ? "-" : "=";
2390 var len = chunk.selection.length;
2391 if(len > wmd.wmd_env.lineLength){
2392 len = wmd.wmd_env.lineLength;
2394 chunk.endTag = "\n";
2396 chunk.endTag += headerChar;
2401 command.doHorizontalRule = function(chunk, postProcessing, useDefaultText){
2402 chunk.startTag = "----------\n";
2403 chunk.selection = "";
2404 chunk.addBlankLines(2, 1, true);
2409 Attacklab.wmd_env = {};
2410 Attacklab.account_options = {};
2411 Attacklab.wmd_defaults = {version:1, output:"Markdown", lineLength:40, delayLoad:false};
2415 Attacklab.wmd = function()
2417 Attacklab.loadEnv = function()
2419 var mergeEnv = function(env)
2428 Attacklab.wmd_env[key] = env[key];
2432 mergeEnv(Attacklab.wmd_defaults);
2433 mergeEnv(Attacklab.account_options);
2434 mergeEnv(top["wmd_options"]);
2435 Attacklab.full = true;
2437 var defaultButtons = "bold italic link blockquote code image ol ul heading hr";
2438 Attacklab.wmd_env.buttons = Attacklab.wmd_env.buttons || defaultButtons;
2440 Attacklab.loadEnv();
2445 Attacklab.wmdBase();
2446 Attacklab.Util.startEditor();