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());
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");
377 input.value = defaultInputText;
379 style.display = "block";
381 style.marginLeft = style.marginRight = "auto";
382 form.appendChild(input);
384 // The upload file input
385 var upload = doc.createElement("div");
386 upload.innerHTML = uploadImageHTML;
387 upload.style.padding = "5px";
388 form.appendChild(upload);
391 var okButton = doc.createElement("input");
392 okButton.type = "button";
393 okButton.onclick = function(){ return close(false); };
394 okButton.value = "OK";
395 style = okButton.style;
396 style.margin = "10px";
397 style.display = "inline";
402 var cancelButton = doc.createElement("input");
403 cancelButton.type = "button";
404 cancelButton.onclick = function(){ return close(true); };
405 cancelButton.value = "Cancel";
406 style = cancelButton.style;
407 style.margin = "10px";
408 style.display = "inline";
411 // The order of these buttons is different on macs.
412 if (/mac/.test(nav.platform.toLowerCase())) {
413 form.appendChild(cancelButton);
414 form.appendChild(okButton);
417 form.appendChild(okButton);
418 form.appendChild(cancelButton);
421 util.addEvent(doc.body, "keydown", checkEscape);
422 dialog.style.top = "50%";
423 dialog.style.left = "50%";
424 dialog.style.display = "block";
425 if(global.isIE_5or6){
426 dialog.style.position = "absolute";
427 dialog.style.top = doc.documentElement.scrollTop + 200 + "px";
428 dialog.style.left = "50%";
430 doc.body.appendChild(dialog);
432 // This has to be done AFTER adding the dialog to the form if you
433 // want it to be centered.
434 dialog.style.marginTop = -(position.getHeight(dialog) / 2) + "px";
435 dialog.style.marginLeft = -(position.getWidth(dialog) / 2) + "px";
441 // Why is this in a zero-length timeout?
442 // Is it working around a browser bug?
443 top.setTimeout(function(){
447 var defTextLen = defaultInputText.length;
448 if (input.selectionStart !== undefined) {
449 input.selectionStart = 0;
450 input.selectionEnd = defTextLen;
452 else if (input.createTextRange) {
453 var range = input.createTextRange();
454 range.collapse(false);
455 range.moveStart("character", -defTextLen);
456 range.moveEnd("character", defTextLen);
466 // The assignment in the while loop makes jslint cranky.
467 // I'll change it to a better loop later.
468 position.getTop = function(elem, isInner){
469 var result = elem.offsetTop;
471 while (elem = elem.offsetParent) {
472 result += elem.offsetTop;
478 position.getHeight = function (elem) {
479 return elem.offsetHeight || elem.scrollHeight;
482 position.getWidth = function (elem) {
483 return elem.offsetWidth || elem.scrollWidth;
486 position.getPageSize = function(){
488 var scrollWidth, scrollHeight;
489 var innerWidth, innerHeight;
491 // It's not very clear which blocks work with which browsers.
492 if(self.innerHeight && self.scrollMaxY){
493 scrollWidth = doc.body.scrollWidth;
494 scrollHeight = self.innerHeight + self.scrollMaxY;
496 else if(doc.body.scrollHeight > doc.body.offsetHeight){
497 scrollWidth = doc.body.scrollWidth;
498 scrollHeight = doc.body.scrollHeight;
501 scrollWidth = doc.body.offsetWidth;
502 scrollHeight = doc.body.offsetHeight;
505 if(self.innerHeight){
507 innerWidth = self.innerWidth;
508 innerHeight = self.innerHeight;
510 else if(doc.documentElement && doc.documentElement.clientHeight){
511 // Some versions of IE (IE 6 w/ a DOCTYPE declaration)
512 innerWidth = doc.documentElement.clientWidth;
513 innerHeight = doc.documentElement.clientHeight;
516 // Other versions of IE
517 innerWidth = doc.body.clientWidth;
518 innerHeight = doc.body.clientHeight;
521 var maxWidth = Math.max(scrollWidth, innerWidth);
522 var maxHeight = Math.max(scrollHeight, innerHeight);
523 return [maxWidth, maxHeight, innerWidth, innerHeight];
526 // Watches the input textarea, polling at an interval and runs
527 // a callback function if anything has changed.
528 wmd.inputPoller = function(callback, interval){
530 var pollerObj = this;
531 var inputArea = wmd.panels.input;
533 // Stored start, end and text. Used to see if there are changes to the input.
538 var killHandle; // Used to cancel monitoring on destruction.
539 // Checks to see if anything has changed in the textarea.
540 // If so, it runs the callback.
541 this.tick = function(){
543 if (!util.isVisible(inputArea)) {
547 // Update the selection start and end, text.
548 if (inputArea.selectionStart || inputArea.selectionStart === 0) {
549 var start = inputArea.selectionStart;
550 var end = inputArea.selectionEnd;
551 if (start != lastStart || end != lastEnd) {
555 if (markdown != inputArea.value) {
556 markdown = inputArea.value;
565 var doTickCallback = function(){
567 if (!util.isVisible(inputArea)) {
571 // If anything has changed, call the function.
572 if (pollerObj.tick()) {
577 // Set how often we poll the textarea for changes.
578 var assignInterval = function(){
579 // previewPollInterval is set at the top of the namespace.
580 killHandle = top.setInterval(doTickCallback, interval);
583 this.destroy = function(){
584 top.clearInterval(killHandle);
590 // Handles pushing and popping TextareaStates for undo/redo commands.
591 // I should rename the stack variables to list.
592 wmd.undoManager = function(callback){
595 var undoStack = []; // A stack of undo states
596 var stackPtr = 0; // The index of the current state
598 var lastState; // The last state
600 var timer; // The setTimeout handle for cancelling the timer
603 // Set the mode for later logic steps.
604 var setMode = function(newMode, noSave){
606 if (mode != newMode) {
613 if (!global.isIE || mode != "moving") {
614 timer = top.setTimeout(refreshState, 1);
617 inputStateObj = null;
621 var refreshState = function(){
622 inputStateObj = new wmd.TextareaState();
627 this.setCommandMode = function(){
630 timer = top.setTimeout(refreshState, 0);
633 this.canUndo = function(){
637 this.canRedo = function(){
638 if (undoStack[stackPtr + 1]) {
644 // Removes the last state and restores it.
645 this.undo = function(){
647 if (undoObj.canUndo()) {
649 // What about setting state -1 to null or checking for undefined?
654 undoStack[stackPtr] = new wmd.TextareaState();
655 undoStack[--stackPtr].restore();
664 wmd.panels.input.focus();
669 this.redo = function(){
671 if (undoObj.canRedo()) {
673 undoStack[++stackPtr].restore();
681 wmd.panels.input.focus();
685 // Push the input area state to the stack.
686 var saveState = function(){
688 var currState = inputStateObj || new wmd.TextareaState();
693 if (mode == "moving") {
695 lastState = currState;
700 if (undoStack[stackPtr - 1].text != lastState.text) {
701 undoStack[stackPtr++] = lastState;
705 undoStack[stackPtr++] = currState;
706 undoStack[stackPtr + 1] = null;
712 var handleCtrlYZ = function(event){
716 if (event.ctrlKey || event.metaKey) {
718 // IE and Opera do not support charCode.
719 var keyCode = event.charCode || event.keyCode;
720 var keyCodeChar = String.fromCharCode(keyCode);
722 switch (keyCodeChar) {
730 if (!event.shiftKey) {
742 if (event.preventDefault) {
743 event.preventDefault();
746 top.event.returnValue = false;
752 // Set the mode depending on what is going on in the input area.
753 var handleModeChange = function(event){
755 if (!event.ctrlKey && !event.metaKey) {
757 var keyCode = event.keyCode;
759 if ((keyCode >= 33 && keyCode <= 40) || (keyCode >= 63232 && keyCode <= 63235)) {
760 // 33 - 40: page up/dn and arrow keys
761 // 63232 - 63235: page up/dn and arrow keys on safari
764 else if (keyCode == 8 || keyCode == 46 || keyCode == 127) {
770 else if (keyCode == 13) {
774 else if (keyCode == 27) {
778 else if ((keyCode < 16 || keyCode > 20) && keyCode != 91) {
779 // 16-20 are shift, etc.
780 // 91: left window key
781 // I think this might be a little messed up since there are
782 // a lot of nonprinting keys above 20.
788 var setEventHandlers = function(){
790 util.addEvent(wmd.panels.input, "keypress", function(event){
793 if ((event.ctrlKey || event.metaKey) && (event.keyCode == 89 || event.keyCode == 90)) {
794 event.preventDefault();
798 var handlePaste = function(){
799 if (global.isIE || (inputStateObj && inputStateObj.text != wmd.panels.input.value)) {
800 if (timer == undefined) {
808 // pastePollInterval is specified at the beginning of this namespace.
809 poller = new wmd.inputPoller(handlePaste, pastePollInterval);
811 util.addEvent(wmd.panels.input, "keydown", handleCtrlYZ);
812 util.addEvent(wmd.panels.input, "keydown", handleModeChange);
814 util.addEvent(wmd.panels.input, "mousedown", function(){
817 wmd.panels.input.onpaste = handlePaste;
818 wmd.panels.input.ondrop = handlePaste;
821 var init = function(){
827 this.destroy = function(){
836 // I think my understanding of how the buttons and callbacks are stored in the array is incomplete.
837 wmd.editor = function(previewRefreshCallback){
839 if (!previewRefreshCallback) {
840 previewRefreshCallback = function(){};
843 var inputBox = wmd.panels.input;
845 var offsetHeight = 0;
852 var div; // This name is pretty ambiguous. I should rename this.
854 // Used to cancel recurring events from setInterval.
857 var undoMgr; // The undo manager
859 // Perform the button's action.
860 var doClick = function(button){
867 undoMgr.setCommandMode();
870 var state = new wmd.TextareaState();
876 var chunks = state.getChunks();
878 // Some commands launch a "modal" prompt dialog. Javascript
879 // can't really make a modal dialog box and the WMD code
880 // will continue to execute while the dialog is displayed.
881 // This prevents the dialog pattern I'm used to and means
882 // I can't do something like this:
884 // var link = CreateLinkDialog();
885 // makeMarkdownLink(link);
887 // Instead of this straightforward method of handling a
888 // dialog I have to pass any code which would execute
889 // after the dialog is dismissed (e.g. link creation)
890 // in a function parameter.
892 // Yes this is awkward and I think it sucks, but there's
893 // no real workaround. Only the image and link code
894 // create dialogs and require the function pointers.
895 var fixupInputArea = function(){
900 state.setChunks(chunks);
904 previewRefreshCallback();
907 var useDefaultText = true;
908 var noCleanup = button.textOp(chunks, fixupInputArea, useDefaultText);
916 if (button.execute) {
917 button.execute(editObj);
921 var setUndoRedoButtonStates = function(){
923 setupButton(document.getElementById("wmd-undo-button"), undoMgr.canUndo());
924 setupButton(document.getElementById("wmd-redo-button"), undoMgr.canRedo());
928 var setupButton = function(button, isEnabled) {
930 var normalYShift = "0px";
931 var disabledYShift = "-20px";
932 var highlightYShift = "-40px";
935 button.style.backgroundPosition = button.XShift + " " + normalYShift;
936 button.onmouseover = function(){
937 this.style.backgroundPosition = this.XShift + " " + highlightYShift;
940 button.onmouseout = function(){
941 this.style.backgroundPosition = this.XShift + " " + normalYShift;
944 // IE tries to select the background image "button" text (it's
945 // implemented in a list item) so we have to cache the selection
948 button.onmousedown = function() {
949 wmd.ieRetardedClick = true;
950 wmd.ieCachedRange = document.selection.createRange();
956 button.onclick = function() {
957 if (this.onmouseout) {
966 button.style.backgroundPosition = button.XShift + " " + disabledYShift;
967 button.onmouseover = button.onmouseout = button.onclick = function(){};
971 var makeSpritedButtonRow = function(){
973 var buttonBar = document.getElementById("wmd-button-bar");
975 var normalYShift = "0px";
976 var disabledYShift = "-20px";
977 var highlightYShift = "-40px";
979 var buttonRow = document.createElement("ul");
980 buttonRow.id = "wmd-button-row";
981 buttonRow = buttonBar.appendChild(buttonRow);
984 var boldButton = document.createElement("li");
985 boldButton.className = "wmd-button";
986 boldButton.id = "wmd-bold-button";
987 boldButton.title = "Strong <strong> Ctrl+B";
988 boldButton.XShift = "0px";
989 boldButton.textOp = command.doBold;
990 setupButton(boldButton, true);
991 buttonRow.appendChild(boldButton);
993 var italicButton = document.createElement("li");
994 italicButton.className = "wmd-button";
995 italicButton.id = "wmd-italic-button";
996 italicButton.title = "Emphasis <em> Ctrl+I";
997 italicButton.XShift = "-20px";
998 italicButton.textOp = command.doItalic;
999 setupButton(italicButton, true);
1000 buttonRow.appendChild(italicButton);
1002 var spacer1 = document.createElement("li");
1003 spacer1.className = "wmd-spacer";
1004 spacer1.id = "wmd-spacer1";
1005 buttonRow.appendChild(spacer1);
1007 var linkButton = document.createElement("li");
1008 linkButton.className = "wmd-button";
1009 linkButton.id = "wmd-link-button";
1010 linkButton.title = "Hyperlink <a> Ctrl+L";
1011 linkButton.XShift = "-40px";
1012 linkButton.textOp = function(chunk, postProcessing, useDefaultText){
1013 return command.doLinkOrImage(chunk, postProcessing, false);
1015 setupButton(linkButton, true);
1016 buttonRow.appendChild(linkButton);
1018 var quoteButton = document.createElement("li");
1019 quoteButton.className = "wmd-button";
1020 quoteButton.id = "wmd-quote-button";
1021 quoteButton.title = "Blockquote <blockquote> Ctrl+Q";
1022 quoteButton.XShift = "-60px";
1023 quoteButton.textOp = command.doBlockquote;
1024 setupButton(quoteButton, true);
1025 buttonRow.appendChild(quoteButton);
1027 var codeButton = document.createElement("li");
1028 codeButton.className = "wmd-button";
1029 codeButton.id = "wmd-code-button";
1030 codeButton.title = "Code Sample <pre><code> Ctrl+K";
1031 codeButton.XShift = "-80px";
1032 codeButton.textOp = command.doCode;
1033 setupButton(codeButton, true);
1034 buttonRow.appendChild(codeButton);
1036 var imageButton = document.createElement("li");
1037 imageButton.className = "wmd-button";
1038 imageButton.id = "wmd-image-button";
1039 imageButton.title = "Image <img> Ctrl+G";
1040 imageButton.XShift = "-100px";
1041 imageButton.textOp = function(chunk, postProcessing, useDefaultText){
1042 return command.doLinkOrImage(chunk, postProcessing, true);
1044 setupButton(imageButton, true);
1045 buttonRow.appendChild(imageButton);
1047 var spacer2 = document.createElement("li");
1048 spacer2.className = "wmd-spacer";
1049 spacer2.id = "wmd-spacer2";
1050 buttonRow.appendChild(spacer2);
1052 var olistButton = document.createElement("li");
1053 olistButton.className = "wmd-button";
1054 olistButton.id = "wmd-olist-button";
1055 olistButton.title = "Numbered List <ol> Ctrl+O";
1056 olistButton.XShift = "-120px";
1057 olistButton.textOp = function(chunk, postProcessing, useDefaultText){
1058 command.doList(chunk, postProcessing, true, useDefaultText);
1060 setupButton(olistButton, true);
1061 buttonRow.appendChild(olistButton);
1063 var ulistButton = document.createElement("li");
1064 ulistButton.className = "wmd-button";
1065 ulistButton.id = "wmd-ulist-button";
1066 ulistButton.title = "Bulleted List <ul> Ctrl+U";
1067 ulistButton.XShift = "-140px";
1068 ulistButton.textOp = function(chunk, postProcessing, useDefaultText){
1069 command.doList(chunk, postProcessing, false, useDefaultText);
1071 setupButton(ulistButton, true);
1072 buttonRow.appendChild(ulistButton);
1074 var headingButton = document.createElement("li");
1075 headingButton.className = "wmd-button";
1076 headingButton.id = "wmd-heading-button";
1077 headingButton.title = "Heading <h1>/<h2> Ctrl+H";
1078 headingButton.XShift = "-160px";
1079 headingButton.textOp = command.doHeading;
1080 setupButton(headingButton, true);
1081 buttonRow.appendChild(headingButton);
1083 var hrButton = document.createElement("li");
1084 hrButton.className = "wmd-button";
1085 hrButton.id = "wmd-hr-button";
1086 hrButton.title = "Horizontal Rule <hr> Ctrl+R";
1087 hrButton.XShift = "-180px";
1088 hrButton.textOp = command.doHorizontalRule;
1089 setupButton(hrButton, true);
1090 buttonRow.appendChild(hrButton);
1092 var spacer3 = document.createElement("li");
1093 spacer3.className = "wmd-spacer";
1094 spacer3.id = "wmd-spacer3";
1095 buttonRow.appendChild(spacer3);
1097 var undoButton = document.createElement("li");
1098 undoButton.className = "wmd-button";
1099 undoButton.id = "wmd-undo-button";
1100 undoButton.title = "Undo - Ctrl+Z";
1101 undoButton.XShift = "-200px";
1102 undoButton.execute = function(manager){
1105 setupButton(undoButton, true);
1106 buttonRow.appendChild(undoButton);
1108 var redoButton = document.createElement("li");
1109 redoButton.className = "wmd-button";
1110 redoButton.id = "wmd-redo-button";
1111 redoButton.title = "Redo - Ctrl+Y";
1112 if (/win/.test(nav.platform.toLowerCase())) {
1113 redoButton.title = "Redo - Ctrl+Y";
1116 // mac and other non-Windows platforms
1117 redoButton.title = "Redo - Ctrl+Shift+Z";
1119 redoButton.XShift = "-220px";
1120 redoButton.execute = function(manager){
1123 setupButton(redoButton, true);
1124 buttonRow.appendChild(redoButton);
1126 var helpButton = document.createElement("li");
1127 helpButton.className = "wmd-button";
1128 helpButton.id = "wmd-help-button";
1129 helpButton.XShift = "-240px";
1130 helpButton.isHelp = true;
1132 var helpAnchor = document.createElement("a");
1133 helpAnchor.href = helpLink;
1134 helpAnchor.target = helpTarget
1135 helpAnchor.title = helpHoverTitle;
1136 helpButton.appendChild(helpAnchor);
1138 setupButton(helpButton, true);
1139 buttonRow.appendChild(helpButton);
1141 setUndoRedoButtonStates();
1144 var setupEditor = function(){
1146 if (/\?noundo/.test(doc.location.href)) {
1147 wmd.nativeUndo = true;
1150 if (!wmd.nativeUndo) {
1151 undoMgr = new wmd.undoManager(function(){
1152 previewRefreshCallback();
1153 setUndoRedoButtonStates();
1157 makeSpritedButtonRow();
1160 var keyEvent = "keydown";
1161 if (global.isOpera) {
1162 keyEvent = "keypress";
1165 util.addEvent(inputBox, keyEvent, function(key){
1167 // Check to see if we have a button key and, if so execute the callback.
1168 if (key.ctrlKey || key.metaKey) {
1170 var keyCode = key.charCode || key.keyCode;
1171 var keyCodeStr = String.fromCharCode(keyCode).toLowerCase();
1173 switch(keyCodeStr) {
1175 doClick(document.getElementById("wmd-bold-button"));
1178 doClick(document.getElementById("wmd-italic-button"));
1181 doClick(document.getElementById("wmd-link-button"));
1184 doClick(document.getElementById("wmd-quote-button"));
1187 doClick(document.getElementById("wmd-code-button"));
1190 doClick(document.getElementById("wmd-image-button"));
1193 doClick(document.getElementById("wmd-olist-button"));
1196 doClick(document.getElementById("wmd-ulist-button"));
1199 doClick(document.getElementById("wmd-heading-button"));
1202 doClick(document.getElementById("wmd-hr-button"));
1205 doClick(document.getElementById("wmd-redo-button"));
1209 doClick(document.getElementById("wmd-redo-button"));
1212 doClick(document.getElementById("wmd-undo-button"));
1220 if (key.preventDefault) {
1221 key.preventDefault();
1225 top.event.returnValue = false;
1230 // Auto-continue lists, code blocks and block quotes when
1231 // the enter key is pressed.
1232 util.addEvent(inputBox, "keyup", function(key){
1233 if (!key.shiftKey && !key.ctrlKey && !key.metaKey) {
1234 var keyCode = key.charCode || key.keyCode;
1235 // Key code 13 is Enter
1236 if (keyCode === 13) {
1238 fakeButton.textOp = command.doAutoindent;
1239 doClick(fakeButton);
1244 // Disable ESC clearing the input textarea on IE
1246 util.addEvent(inputBox, "keydown", function(key){
1247 var code = key.keyCode;
1248 // Key code 27 is ESC
1255 if (inputBox.form) {
1256 var submitCallback = inputBox.form.onsubmit;
1257 inputBox.form.onsubmit = function(){
1259 if (submitCallback) {
1260 return submitCallback.apply(this, arguments);
1266 // Convert the contents of the input textarea to HTML in the output/preview panels.
1267 var convertToHtml = function(){
1270 var markdownConverter = new wmd.showdown.converter();
1272 var text = inputBox.value;
1274 var callback = function(){
1275 inputBox.value = text;
1278 if (!/markdown/.test(wmd.wmd_env.output.toLowerCase())) {
1279 if (markdownConverter) {
1280 inputBox.value = markdownConverter.makeHtml(text);
1281 top.setTimeout(callback, 0);
1288 this.undo = function(){
1294 this.redo = function(){
1300 // This is pretty useless. The setupEditor function contents
1301 // should just be copied here.
1302 var init = function(){
1306 this.destroy = function(){
1310 if (div.parentNode) {
1311 div.parentNode.removeChild(div);
1314 inputBox.style.marginTop = "";
1316 top.clearInterval(creationHandle);
1322 // The input textarea state/contents.
1323 // This is used to implement undo/redo by the undo manager.
1324 wmd.TextareaState = function(){
1327 var stateObj = this;
1328 var inputArea = wmd.panels.input;
1330 this.init = function() {
1332 if (!util.isVisible(inputArea)) {
1336 this.setInputAreaSelectionStartEnd();
1337 this.scrollTop = inputArea.scrollTop;
1338 if (!this.text && inputArea.selectionStart || inputArea.selectionStart === 0) {
1339 this.text = inputArea.value;
1344 // Sets the selected text in the input box after we've performed an
1346 this.setInputAreaSelection = function(){
1348 if (!util.isVisible(inputArea)) {
1352 if (inputArea.selectionStart !== undefined && !global.isOpera) {
1355 inputArea.selectionStart = stateObj.start;
1356 inputArea.selectionEnd = stateObj.end;
1357 inputArea.scrollTop = stateObj.scrollTop;
1359 else if (doc.selection) {
1361 if (doc.activeElement && doc.activeElement !== inputArea) {
1366 var range = inputArea.createTextRange();
1367 range.moveStart("character", -inputArea.value.length);
1368 range.moveEnd("character", -inputArea.value.length);
1369 range.moveEnd("character", stateObj.end);
1370 range.moveStart("character", stateObj.start);
1375 this.setInputAreaSelectionStartEnd = function(){
1377 if (inputArea.selectionStart || inputArea.selectionStart === 0) {
1379 stateObj.start = inputArea.selectionStart;
1380 stateObj.end = inputArea.selectionEnd;
1382 else if (doc.selection) {
1384 stateObj.text = util.fixEolChars(inputArea.value);
1386 // IE loses the selection in the textarea when buttons are
1387 // clicked. On IE we cache the selection and set a flag
1388 // which we check for here.
1390 if(wmd.ieRetardedClick && wmd.ieCachedRange) {
1391 range = wmd.ieCachedRange;
1392 wmd.ieRetardedClick = false;
1395 range = doc.selection.createRange();
1398 var fixedRange = util.fixEolChars(range.text);
1399 var marker = "\x07";
1400 var markedRange = marker + fixedRange + marker;
1401 range.text = markedRange;
1402 var inputText = util.fixEolChars(inputArea.value);
1404 range.moveStart("character", -markedRange.length);
1405 range.text = fixedRange;
1407 stateObj.start = inputText.indexOf(marker);
1408 stateObj.end = inputText.lastIndexOf(marker) - marker.length;
1410 var len = stateObj.text.length - util.fixEolChars(inputArea.value).length;
1413 range.moveStart("character", -fixedRange.length);
1418 range.text = fixedRange;
1421 this.setInputAreaSelection();
1425 // Restore this state into the input area.
1426 this.restore = function(){
1428 if (stateObj.text != undefined && stateObj.text != inputArea.value) {
1429 inputArea.value = stateObj.text;
1431 this.setInputAreaSelection();
1432 inputArea.scrollTop = stateObj.scrollTop;
1435 // Gets a collection of HTML chunks from the inptut textarea.
1436 this.getChunks = function(){
1438 var chunk = new wmd.Chunks();
1440 chunk.before = util.fixEolChars(stateObj.text.substring(0, stateObj.start));
1441 chunk.startTag = "";
1442 chunk.selection = util.fixEolChars(stateObj.text.substring(stateObj.start, stateObj.end));
1444 chunk.after = util.fixEolChars(stateObj.text.substring(stateObj.end));
1445 chunk.scrollTop = stateObj.scrollTop;
1450 // Sets the TextareaState properties given a chunk of markdown.
1451 this.setChunks = function(chunk){
1453 chunk.before = chunk.before + chunk.startTag;
1454 chunk.after = chunk.endTag + chunk.after;
1456 if (global.isOpera) {
1457 chunk.before = chunk.before.replace(/\n/g, "\r\n");
1458 chunk.selection = chunk.selection.replace(/\n/g, "\r\n");
1459 chunk.after = chunk.after.replace(/\n/g, "\r\n");
1462 this.start = chunk.before.length;
1463 this.end = chunk.before.length + chunk.selection.length;
1464 this.text = chunk.before + chunk.selection + chunk.after;
1465 this.scrollTop = chunk.scrollTop;
1471 // before: contains all the text in the input box BEFORE the selection.
1472 // after: contains all the text in the input box AFTER the selection.
1473 wmd.Chunks = function(){
1476 // startRegex: a regular expression to find the start tag
1477 // endRegex: a regular expresssion to find the end tag
1478 wmd.Chunks.prototype.findTags = function(startRegex, endRegex){
1480 var chunkObj = this;
1485 regex = util.extendRegExp(startRegex, "", "$");
1487 this.before = this.before.replace(regex,
1489 chunkObj.startTag = chunkObj.startTag + match;
1493 regex = util.extendRegExp(startRegex, "^", "");
1495 this.selection = this.selection.replace(regex,
1497 chunkObj.startTag = chunkObj.startTag + match;
1504 regex = util.extendRegExp(endRegex, "", "$");
1506 this.selection = this.selection.replace(regex,
1508 chunkObj.endTag = match + chunkObj.endTag;
1512 regex = util.extendRegExp(endRegex, "^", "");
1514 this.after = this.after.replace(regex,
1516 chunkObj.endTag = match + chunkObj.endTag;
1522 // If remove is false, the whitespace is transferred
1523 // to the before/after regions.
1525 // If remove is true, the whitespace disappears.
1526 wmd.Chunks.prototype.trimWhitespace = function(remove){
1528 this.selection = this.selection.replace(/^(\s*)/, "");
1531 this.before += re.$1;
1534 this.selection = this.selection.replace(/(\s*)$/, "");
1537 this.after = re.$1 + this.after;
1542 wmd.Chunks.prototype.addBlankLines = function(nLinesBefore, nLinesAfter, findExtraNewlines){
1544 if (nLinesBefore === undefined) {
1548 if (nLinesAfter === undefined) {
1556 var replacementText;
1558 if (navigator.userAgent.match(/Chrome/)) {
1562 this.selection = this.selection.replace(/(^\n*)/, "");
1563 this.startTag = this.startTag + re.$1;
1564 this.selection = this.selection.replace(/(\n*$)/, "");
1565 this.endTag = this.endTag + re.$1;
1566 this.startTag = this.startTag.replace(/(^\n*)/, "");
1567 this.before = this.before + re.$1;
1568 this.endTag = this.endTag.replace(/(\n*$)/, "");
1569 this.after = this.after + re.$1;
1573 regexText = replacementText = "";
1575 while (nLinesBefore--) {
1576 regexText += "\\n?";
1577 replacementText += "\n";
1580 if (findExtraNewlines) {
1583 this.before = this.before.replace(new re(regexText + "$", ""), replacementText);
1588 regexText = replacementText = "";
1590 while (nLinesAfter--) {
1591 regexText += "\\n?";
1592 replacementText += "\n";
1594 if (findExtraNewlines) {
1598 this.after = this.after.replace(new re(regexText, ""), replacementText);
1602 // The markdown symbols - 4 spaces = code, > = blockquote, etc.
1603 command.prefixes = "(?:\\s{4,}|\\s*>|\\s*-\\s+|\\s*\\d+\\.|=|\\+|-|_|\\*|#|\\s*\\[[^\n]]+\\]:)";
1605 // Remove markdown symbols from the chunk selection.
1606 command.unwrap = function(chunk){
1607 var txt = new re("([^\\n])\\n(?!(\\n|" + command.prefixes + "))", "g");
1608 chunk.selection = chunk.selection.replace(txt, "$1 $2");
1611 command.wrap = function(chunk, len){
1612 command.unwrap(chunk);
1613 var regex = new re("(.{1," + len + "})( +|$\\n?)", "gm");
1615 chunk.selection = chunk.selection.replace(regex, function(line, marked){
1616 if (new re("^" + command.prefixes, "").test(line)) {
1619 return marked + "\n";
1622 chunk.selection = chunk.selection.replace(/\s+$/, "");
1625 command.doBold = function(chunk, postProcessing, useDefaultText){
1626 return command.doBorI(chunk, 2, "strong text");
1629 command.doItalic = function(chunk, postProcessing, useDefaultText){
1630 return command.doBorI(chunk, 1, "emphasized text");
1633 // chunk: The selected region that will be enclosed with */**
1634 // nStars: 1 for italics, 2 for bold
1635 // insertText: If you just click the button without highlighting text, this gets inserted
1636 command.doBorI = function(chunk, nStars, insertText){
1638 // Get rid of whitespace and fix up newlines.
1639 chunk.trimWhitespace();
1640 chunk.selection = chunk.selection.replace(/\n{2,}/g, "\n");
1642 // Look for stars before and after. Is the chunk already marked up?
1643 chunk.before.search(/(\**$)/);
1644 var starsBefore = re.$1;
1646 chunk.after.search(/(^\**)/);
1647 var starsAfter = re.$1;
1649 var prevStars = Math.min(starsBefore.length, starsAfter.length);
1651 // Remove stars if we have to since the button acts as a toggle.
1652 if ((prevStars >= nStars) && (prevStars != 2 || nStars != 1)) {
1653 chunk.before = chunk.before.replace(re("[*]{" + nStars + "}$", ""), "");
1654 chunk.after = chunk.after.replace(re("^[*]{" + nStars + "}", ""), "");
1656 else if (!chunk.selection && starsAfter) {
1657 // It's not really clear why this code is necessary. It just moves
1658 // some arbitrary stuff around.
1659 chunk.after = chunk.after.replace(/^([*_]*)/, "");
1660 chunk.before = chunk.before.replace(/(\s?)$/, "");
1661 var whitespace = re.$1;
1662 chunk.before = chunk.before + starsAfter + whitespace;
1666 // In most cases, if you don't have any selected text and click the button
1667 // you'll get a selected, marked up region with the default text inserted.
1668 if (!chunk.selection && !starsAfter) {
1669 chunk.selection = insertText;
1672 // Add the true markup.
1673 var markup = nStars <= 1 ? "*" : "**"; // shouldn't the test be = ?
1674 chunk.before = chunk.before + markup;
1675 chunk.after = markup + chunk.after;
1681 command.stripLinkDefs = function(text, defsToAdd){
1683 text = text.replace(/^[ ]{0,3}\[(\d+)\]:[ \t]*\n?[ \t]*<?(\S+?)>?[ \t]*\n?[ \t]*(?:(\n*)["(](.+?)[")][ \t]*)?(?:\n+|$)/gm,
1684 function(totalMatch, id, link, newlines, title){
1685 defsToAdd[id] = totalMatch.replace(/\s*$/, "");
1687 // Strip the title and return that separately.
1688 defsToAdd[id] = totalMatch.replace(/["(](.+?)[")]$/, "");
1689 return newlines + title;
1697 command.addLinkDef = function(chunk, linkDef){
1699 var refNumber = 0; // The current reference number
1700 var defsToAdd = {}; //
1701 // Start with a clean slate by removing all previous link definitions.
1702 chunk.before = command.stripLinkDefs(chunk.before, defsToAdd);
1703 chunk.selection = command.stripLinkDefs(chunk.selection, defsToAdd);
1704 chunk.after = command.stripLinkDefs(chunk.after, defsToAdd);
1707 var regex = /(\[)((?:\[[^\]]*\]|[^\[\]])*)(\][ ]?(?:\n[ ]*)?\[)(\d+)(\])/g;
1711 var addDefNumber = function(def){
1713 def = def.replace(/^[ ]{0,3}\[(\d+)\]:/, " [" + refNumber + "]:");
1718 // a) the recursive call to getLink cannot go infinite, because by definition
1719 // of regex, inner is always a proper substring of wholeMatch, and
1720 // b) more than one level of nesting is neither supported by the regex
1721 // nor making a lot of sense (the only use case for nesting is a linked image)
1722 var getLink = function (wholeMatch, before, inner, afterInner, id, end) {
1723 inner = inner.replace(regex, getLink);
1724 if (defsToAdd[id]) {
1725 addDefNumber(defsToAdd[id]);
1726 return before + inner + afterInner + 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 util.prompt(imageDialogText, imageDefaultText, makeLinkMarkdown);
1805 util.prompt(linkDialogText, linkDefaultText, makeLinkMarkdown);
1811 util.makeAPI = function(){
1813 wmd.wmd.editor = wmd.editor;
1814 wmd.wmd.previewManager = wmd.previewManager;
1817 util.startEditor = function(){
1819 if (wmd.wmd_env.autostart === false) {
1824 var edit; // The editor (buttons + input + outputs) - the main object.
1825 var previewMgr; // The preview manager.
1827 // Fired after the page has fully loaded.
1828 var loadListener = function(){
1830 wmd.panels = new wmd.PanelCollection();
1832 previewMgr = new wmd.previewManager();
1833 var previewRefreshCallback = previewMgr.refresh;
1835 edit = new wmd.editor(previewRefreshCallback);
1837 previewMgr.refresh(true);
1841 util.addEvent(top, "load", loadListener);
1844 wmd.previewManager = function(){
1846 var managerObj = this;
1853 var maxDelay = 3000;
1854 var startType = "delayed"; // The other legal value is "manual"
1856 // Adds event listeners to elements and creates the input poller.
1857 var setupEvents = function(inputElem, listener){
1859 util.addEvent(inputElem, "input", listener);
1860 inputElem.onpaste = listener;
1861 inputElem.ondrop = listener;
1863 util.addEvent(inputElem, "keypress", listener);
1864 util.addEvent(inputElem, "keydown", listener);
1865 // previewPollInterval is set at the top of this file.
1866 poller = new wmd.inputPoller(listener, previewPollInterval);
1869 var getDocScrollTop = function(){
1873 if (top.innerHeight) {
1874 result = top.pageYOffset;
1877 if (doc.documentElement && doc.documentElement.scrollTop) {
1878 result = doc.documentElement.scrollTop;
1882 result = doc.body.scrollTop;
1888 var makePreviewHtml = function(){
1890 // If there are no registered preview and output panels
1891 // there is nothing to do.
1892 if (!wmd.panels.preview && !wmd.panels.output) {
1896 var text = wmd.panels.input.value;
1897 if (text && text == oldInputText) {
1898 return; // Input text hasn't changed.
1901 oldInputText = text;
1904 var prevTime = new Date().getTime();
1906 if (!converter && wmd.showdown) {
1907 converter = new wmd.showdown.converter();
1911 text = converter.makeHtml(text);
1914 // Calculate the processing time of the HTML creation.
1915 // It's used as the delay time in the event listener.
1916 var currTime = new Date().getTime();
1917 elapsedTime = currTime - prevTime;
1919 pushPreviewHtml(text);
1923 // setTimeout is already used. Used as an event listener.
1924 var applyTimeout = function(){
1927 top.clearTimeout(timeout);
1928 timeout = undefined;
1931 if (startType !== "manual") {
1935 if (startType === "delayed") {
1936 delay = elapsedTime;
1939 if (delay > maxDelay) {
1942 timeout = top.setTimeout(makePreviewHtml, delay);
1946 var getScaleFactor = function(panel){
1947 if (panel.scrollHeight <= panel.clientHeight) {
1950 return panel.scrollTop / (panel.scrollHeight - panel.clientHeight);
1953 var setPanelScrollTops = function(){
1955 if (wmd.panels.preview) {
1956 wmd.panels.preview.scrollTop = (wmd.panels.preview.scrollHeight - wmd.panels.preview.clientHeight) * getScaleFactor(wmd.panels.preview);
1960 if (wmd.panels.output) {
1961 wmd.panels.output.scrollTop = (wmd.panels.output.scrollHeight - wmd.panels.output.clientHeight) * getScaleFactor(wmd.panels.output);
1966 this.refresh = function(requiresRefresh){
1968 if (requiresRefresh) {
1977 this.processingTime = function(){
1982 this.output = function(){
1986 // The mode can be "manual" or "delayed"
1987 this.setUpdateMode = function(mode){
1989 managerObj.refresh();
1992 var isFirstTimeFilled = true;
1994 var pushPreviewHtml = function(text){
1996 var emptyTop = position.getTop(wmd.panels.input) - getDocScrollTop();
1998 // Send the encoded HTML to the output textarea/div.
1999 if (wmd.panels.output) {
2000 // The value property is only defined if the output is a textarea.
2001 if (wmd.panels.output.value !== undefined) {
2002 wmd.panels.output.value = text;
2003 wmd.panels.output.readOnly = true;
2005 // Otherwise we are just replacing the text in a div.
2006 // Send the HTML wrapped in <pre><code>
2008 var newText = text.replace(/&/g, "&");
2009 newText = newText.replace(/</g, "<");
2010 wmd.panels.output.innerHTML = "<pre><code>" + newText + "</code></pre>";
2014 if (wmd.panels.preview) {
2015 wmd.panels.preview.innerHTML = text;
2018 setPanelScrollTops();
2020 if (isFirstTimeFilled) {
2021 isFirstTimeFilled = false;
2025 var fullTop = position.getTop(wmd.panels.input) - getDocScrollTop();
2028 top.setTimeout(function(){
2029 top.scrollBy(0, fullTop - emptyTop);
2033 top.scrollBy(0, fullTop - emptyTop);
2037 var init = function(){
2039 setupEvents(wmd.panels.input, applyTimeout);
2042 if (wmd.panels.preview) {
2043 wmd.panels.preview.scrollTop = 0;
2045 if (wmd.panels.output) {
2046 wmd.panels.output.scrollTop = 0;
2050 this.destroy = function(){
2059 // Moves the cursor to the next line and continues lists, quotes and code.
2060 command.doAutoindent = function(chunk, postProcessing, useDefaultText){
2062 chunk.before = chunk.before.replace(/(\n|^)[ ]{0,3}([*+-]|\d+[.])[ \t]*\n$/, "\n\n");
2063 chunk.before = chunk.before.replace(/(\n|^)[ ]{0,3}>[ \t]*\n$/, "\n\n");
2064 chunk.before = chunk.before.replace(/(\n|^)[ \t]+\n$/, "\n\n");
2066 useDefaultText = false;
2068 if(/(\n|^)[ ]{0,3}([*+-])[ \t]+.*\n$/.test(chunk.before)){
2070 command.doList(chunk, postProcessing, false, true);
2073 if(/(\n|^)[ ]{0,3}(\d+[.])[ \t]+.*\n$/.test(chunk.before)){
2075 command.doList(chunk, postProcessing, true, true);
2078 if(/(\n|^)[ ]{0,3}>[ \t]+.*\n$/.test(chunk.before)){
2079 if(command.doBlockquote){
2080 command.doBlockquote(chunk, postProcessing, useDefaultText);
2083 if(/(\n|^)(\t|[ ]{4,}).*\n$/.test(chunk.before)){
2085 command.doCode(chunk, postProcessing, useDefaultText);
2090 command.doBlockquote = function(chunk, postProcessing, useDefaultText){
2092 chunk.selection = chunk.selection.replace(/^(\n*)([^\r]+?)(\n*)$/,
2093 function(totalMatch, newlinesBefore, text, newlinesAfter){
2094 chunk.before += newlinesBefore;
2095 chunk.after = newlinesAfter + chunk.after;
2099 chunk.before = chunk.before.replace(/(>[ \t]*)$/,
2100 function(totalMatch, blankLine){
2101 chunk.selection = blankLine + chunk.selection;
2105 var defaultText = useDefaultText ? "Blockquote" : "";
2106 chunk.selection = chunk.selection.replace(/^(\s|>)+$/ ,"");
2107 chunk.selection = chunk.selection || defaultText;
2109 // The original code uses a regular expression to find out how much of the
2110 // text *directly before* the selection already was a blockquote:
2113 chunk.before = chunk.before.replace(/\n?$/,"\n");
2115 chunk.before = chunk.before.replace(/(((\n|^)(\n[ \t]*)*>(.+\n)*.*)+(\n[ \t]*)*$)/,
2116 function (totalMatch) {
2117 chunk.startTag = totalMatch;
2121 // This comes down to:
2122 // Go backwards as many lines a possible, such that each line
2123 // a) starts with ">", or
2124 // b) is almost empty, except for whitespace, or
2125 // c) is preceeded by an unbroken chain of non-empty lines
2126 // leading up to a line that starts with ">" and at least one more character
2128 // d) at least one line fulfills a)
2130 // Since this is essentially a backwards-moving regex, it's susceptible to
2131 // catstrophic backtracking and can cause the browser to hang;
2132 // see e.g. http://meta.stackoverflow.com/questions/9807.
2134 // Hence we replaced this by a simple state machine that just goes through the
2135 // lines and checks for a), b), and c).
2140 var lines = chunk.before.replace(/\n$/, "").split("\n");
2141 var inChain = false;
2142 for (var i in lines) {
2145 inChain = inChain && line.length > 0; // c) any non-empty line continues the chain
2146 if (/^>/.test(line)) { // a)
2148 if (!inChain && line.length > 1) // c) any line that starts with ">" and has at least one more character starts the chain
2150 } else if (/^[ \t]*$/.test(line)) { // b)
2153 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
2156 match += line + "\n";
2158 leftOver += match + line;
2162 if (!/(^|\n)>/.test(match)) { // d)
2168 chunk.startTag = match;
2169 chunk.before = leftOver;
2174 chunk.after = chunk.after.replace(/^\n?/,"\n");
2177 chunk.after = chunk.after.replace(/^(((\n|^)(\n[ \t]*)*>(.+\n)*.*)+(\n[ \t]*)*)/,
2178 function(totalMatch){
2179 chunk.endTag = totalMatch;
2183 var replaceBlanksInTags = function(useBracket){
2185 var replacement = useBracket ? "> " : "";
2188 chunk.startTag = chunk.startTag.replace(/\n((>|\s)*)\n$/,
2189 function(totalMatch, markdown){
2190 return "\n" + markdown.replace(/^[ ]{0,3}>?[ \t]*$/gm, replacement) + "\n";
2194 chunk.endTag = chunk.endTag.replace(/^\n((>|\s)*)\n/,
2195 function(totalMatch, markdown){
2196 return "\n" + markdown.replace(/^[ ]{0,3}>?[ \t]*$/gm, replacement) + "\n";
2201 if(/^(?![ ]{0,3}>)/m.test(chunk.selection)){
2202 command.wrap(chunk, wmd.wmd_env.lineLength - 2);
2203 chunk.selection = chunk.selection.replace(/^/gm, "> ");
2204 replaceBlanksInTags(true);
2205 chunk.addBlankLines();
2208 chunk.selection = chunk.selection.replace(/^[ ]{0,3}> ?/gm, "");
2209 command.unwrap(chunk);
2210 replaceBlanksInTags(false);
2212 if(!/^(\n|^)[ ]{0,3}>/.test(chunk.selection) && chunk.startTag){
2213 chunk.startTag = chunk.startTag.replace(/\n{0,2}$/, "\n\n");
2216 if(!/(\n|^)[ ]{0,3}>.*$/.test(chunk.selection) && chunk.endTag){
2217 chunk.endTag=chunk.endTag.replace(/^\n{0,2}/, "\n\n");
2221 if(!/\n/.test(chunk.selection)){
2222 chunk.selection = chunk.selection.replace(/^(> *)/,
2223 function(wholeMatch, blanks){
2224 chunk.startTag += blanks;
2230 command.doCode = function(chunk, postProcessing, useDefaultText){
2232 var hasTextBefore = /\S[ ]*$/.test(chunk.before);
2233 var hasTextAfter = /^[ ]*\S/.test(chunk.after);
2235 // Use 'four space' markdown if the selection is on its own
2236 // line or is multiline.
2237 if((!hasTextAfter && !hasTextBefore) || /\n/.test(chunk.selection)){
2239 chunk.before = chunk.before.replace(/[ ]{4}$/,
2240 function(totalMatch){
2241 chunk.selection = totalMatch + chunk.selection;
2245 var nLinesBefore = 1;
2246 var nLinesAfter = 1;
2249 if(/\n(\t|[ ]{4,}).*\n$/.test(chunk.before) || chunk.after === ""){
2252 if(/^\n(\t|[ ]{4,})/.test(chunk.after)){
2253 nLinesAfter = 0; // This needs to happen on line 1
2256 chunk.addBlankLines(nLinesBefore, nLinesAfter);
2258 if(!chunk.selection){
2259 chunk.startTag = " ";
2260 chunk.selection = useDefaultText ? "enter code here" : "";
2263 if(/^[ ]{0,3}\S/m.test(chunk.selection)){
2264 chunk.selection = chunk.selection.replace(/^/gm, " ");
2267 chunk.selection = chunk.selection.replace(/^[ ]{4}/gm, "");
2272 // Use backticks (`) to delimit the code block.
2274 chunk.trimWhitespace();
2275 chunk.findTags(/`/, /`/);
2277 if(!chunk.startTag && !chunk.endTag){
2278 chunk.startTag = chunk.endTag="`";
2279 if(!chunk.selection){
2280 chunk.selection = useDefaultText ? "enter code here" : "";
2283 else if(chunk.endTag && !chunk.startTag){
2284 chunk.before += chunk.endTag;
2288 chunk.startTag = chunk.endTag="";
2293 command.doList = function(chunk, postProcessing, isNumberedList, useDefaultText){
2295 // These are identical except at the very beginning and end.
2296 // Should probably use the regex extension function to make this clearer.
2297 var previousItemsRegex = /(\n|^)(([ ]{0,3}([*+-]|\d+[.])[ \t]+.*)(\n.+|\n{2,}([*+-].*|\d+[.])[ \t]+.*|\n{2,}[ \t]+\S.*)*)\n*$/;
2298 var nextItemsRegex = /^\n*(([ ]{0,3}([*+-]|\d+[.])[ \t]+.*)(\n.+|\n{2,}([*+-].*|\d+[.])[ \t]+.*|\n{2,}[ \t]+\S.*)*)\n*/;
2300 // The default bullet is a dash but others are possible.
2301 // This has nothing to do with the particular HTML bullet,
2302 // it's just a markdown bullet.
2305 // The number in a numbered list.
2308 // Get the item prefix - e.g. " 1. " for a numbered list, " - " for a bulleted list.
2309 var getItemPrefix = function(){
2312 prefix = " " + num + ". ";
2316 prefix = " " + bullet + " ";
2321 // Fixes the prefixes of the other list items.
2322 var getPrefixedItem = function(itemText){
2324 // The numbering flag is unset when called by autoindent.
2325 if(isNumberedList === undefined){
2326 isNumberedList = /^\s*\d/.test(itemText);
2329 // Renumber/bullet the list element.
2330 itemText = itemText.replace(/^[ ]{0,3}([*+-]|\d+[.])\s/gm,
2332 return getItemPrefix();
2338 chunk.findTags(/(\n|^)*[ ]{0,3}([*+-]|\d+[.])\s+/, null);
2340 if(chunk.before && !/\n$/.test(chunk.before) && !/^\n/.test(chunk.startTag)){
2341 chunk.before += chunk.startTag;
2342 chunk.startTag = "";
2347 var hasDigits = /\d+[.]/.test(chunk.startTag);
2348 chunk.startTag = "";
2349 chunk.selection = chunk.selection.replace(/\n[ ]{4}/g, "\n");
2350 command.unwrap(chunk);
2351 chunk.addBlankLines();
2354 // Have to renumber the bullet points if this is a numbered list.
2355 chunk.after = chunk.after.replace(nextItemsRegex, getPrefixedItem);
2357 if(isNumberedList == hasDigits){
2362 var nLinesBefore = 1;
2364 chunk.before = chunk.before.replace(previousItemsRegex,
2366 if(/^\s*([*+-])/.test(itemText)){
2369 nLinesBefore = /[^\n]\n\n[^\n]/.test(itemText) ? 1 : 0;
2370 return getPrefixedItem(itemText);
2373 if(!chunk.selection){
2374 chunk.selection = useDefaultText ? "List item" : " ";
2377 var prefix = getItemPrefix();
2379 var nLinesAfter = 1;
2381 chunk.after = chunk.after.replace(nextItemsRegex,
2383 nLinesAfter = /[^\n]\n\n[^\n]/.test(itemText) ? 1 : 0;
2384 return getPrefixedItem(itemText);
2387 chunk.trimWhitespace(true);
2388 chunk.addBlankLines(nLinesBefore, nLinesAfter, true);
2389 chunk.startTag = prefix;
2390 var spaces = prefix.replace(/./g, " ");
2391 command.wrap(chunk, wmd.wmd_env.lineLength - spaces.length);
2392 chunk.selection = chunk.selection.replace(/\n/g, "\n" + spaces);
2396 command.doHeading = function(chunk, postProcessing, useDefaultText){
2398 // Remove leading/trailing whitespace and reduce internal spaces to single spaces.
2399 chunk.selection = chunk.selection.replace(/\s+/g, " ");
2400 chunk.selection = chunk.selection.replace(/(^\s+|\s+$)/g, "");
2402 // If we clicked the button with no selected text, we just
2403 // make a level 2 hash header around some default text.
2404 if(!chunk.selection){
2405 chunk.startTag = "## ";
2406 chunk.selection = "Heading";
2407 chunk.endTag = " ##";
2411 var headerLevel = 0; // The existing header level of the selected text.
2413 // Remove any existing hash heading markdown and save the header level.
2414 chunk.findTags(/#+[ ]*/, /[ ]*#+/);
2415 if(/#+/.test(chunk.startTag)){
2416 headerLevel = re.lastMatch.length;
2418 chunk.startTag = chunk.endTag = "";
2420 // Try to get the current header level by looking for - and = in the line
2421 // below the selection.
2422 chunk.findTags(null, /\s?(-+|=+)/);
2423 if(/=+/.test(chunk.endTag)){
2426 if(/-+/.test(chunk.endTag)){
2430 // Skip to the next line so we can create the header markdown.
2431 chunk.startTag = chunk.endTag = "";
2432 chunk.addBlankLines(1, 1);
2434 // We make a level 2 header if there is no current header.
2435 // If there is a header level, we substract one from the header level.
2436 // If it's already a level 1 header, it's removed.
2437 var headerLevelToCreate = headerLevel == 0 ? 2 : headerLevel - 1;
2439 if(headerLevelToCreate > 0){
2441 // The button only creates level 1 and 2 underline headers.
2442 // Why not have it iterate over hash header levels? Wouldn't that be easier and cleaner?
2443 var headerChar = headerLevelToCreate >= 2 ? "-" : "=";
2444 var len = chunk.selection.length;
2445 if(len > wmd.wmd_env.lineLength){
2446 len = wmd.wmd_env.lineLength;
2448 chunk.endTag = "\n";
2450 chunk.endTag += headerChar;
2455 command.doHorizontalRule = function(chunk, postProcessing, useDefaultText){
2456 chunk.startTag = "----------\n";
2457 chunk.selection = "";
2458 chunk.addBlankLines(2, 1, true);
2463 Attacklab.wmd_env = {};
2464 Attacklab.account_options = {};
2465 Attacklab.wmd_defaults = {version:1, output:"HTML", lineLength:40, delayLoad:false};
2469 Attacklab.wmd = function()
2471 Attacklab.loadEnv = function()
2473 var mergeEnv = function(env)
2482 Attacklab.wmd_env[key] = env[key];
2486 mergeEnv(Attacklab.wmd_defaults);
2487 mergeEnv(Attacklab.account_options);
2488 mergeEnv(top["wmd_options"]);
2489 Attacklab.full = true;
2491 var defaultButtons = "bold italic link blockquote code image ol ul heading hr";
2492 Attacklab.wmd_env.buttons = Attacklab.wmd_env.buttons || defaultButtons;
2494 Attacklab.loadEnv();
2499 Attacklab.wmdBase();
2500 Attacklab.Util.startEditor();