1 var Attacklab = Attacklab || {};
3 Attacklab.wmdBase = function(){
5 // A few handy aliases for readability.
6 var wmd = top.Attacklab;
7 var doc = top.document;
9 var nav = top.navigator;
18 var position = wmd.Position;
19 var command = wmd.Command;
20 var global = wmd.Global;
23 // Used to work around some browser bugs where we can't use feature testing.
24 global.isIE = /msie/.test(nav.userAgent.toLowerCase());
25 global.isIE_5or6 = /msie 6/.test(nav.userAgent.toLowerCase()) || /msie 5/.test(nav.userAgent.toLowerCase());
26 global.isIE_7plus = global.isIE && !global.isIE_5or6;
27 global.isOpera = /opera/.test(nav.userAgent.toLowerCase());
28 global.isKonqueror = /konqueror/.test(nav.userAgent.toLowerCase());
31 // -------------------------------------------------------------------
32 // YOUR CHANGES GO HERE
34 // I've tried to localize the things you are likely to change to
36 // -------------------------------------------------------------------
38 // The text that appears on the upper part of the dialog box when
40 var imageDialogText = "<p style='margin-top: 0px'><b>Enter the image URL.</b></p><p>You can also add a title, which will be displayed as a tool tip.</p><p>Example:<br />http://wmd-editor.com/images/cloud1.jpg \"Optional title\"</p>";
41 var linkDialogText = "<p style='margin-top: 0px'><b>Enter the web address.</b></p><p>You can also add a title, which will be displayed as a tool tip.</p><p>Example:<br />http://wmd-editor.com/ \"Optional title\"</p>";
43 // The default text that appears in the dialog input box when entering
45 var imageDefaultText = "http://";
46 var linkDefaultText = "http://";
48 // The location of your button images relative to the base directory.
49 var imageDirectory = "images/";
51 // Some intervals in ms. These can be adjusted to reduce the control's load.
52 var previewPollInterval = 500;
53 var pastePollInterval = 100;
55 // The link and title for the help button
56 var helpLink = "http://wmd-editor.com/";
57 var helpHoverTitle = "WMD website";
58 var helpTarget = "_blank";
60 // -------------------------------------------------------------------
61 // END OF YOUR CHANGES
62 // -------------------------------------------------------------------
64 // A collection of the important regions on the page.
65 // Cached so we don't have to keep traversing the DOM.
66 wmd.PanelCollection = function(){
67 this.buttonBar = doc.getElementById("wmd-button-bar");
68 this.preview = doc.getElementById("previewer");
69 this.output = doc.getElementById("wmd-output");
70 this.input = doc.getElementById("editor");
73 // This PanelCollection object can't be filled until after the page
75 wmd.panels = undefined;
77 // Internet explorer has problems with CSS sprite buttons that use HTML
78 // lists. When you click on the background image "button", IE will
79 // select the non-existent link text and discard the selection in the
80 // textarea. The solution to this is to cache the textarea selection
81 // on the button's mousedown event and set a flag. In the part of the
82 // code where we need to grab the selection, we check for the flag
83 // and, if it's set, use the cached area instead of querying the
86 // This ONLY affects Internet Explorer (tested on versions 6, 7
87 // and 8) and ONLY on button clicks. Keyboard shortcuts work
88 // normally since the focus never leaves the textarea.
89 wmd.ieCachedRange = null; // cached textarea selection
90 wmd.ieRetardedClick = false; // flag
92 // Returns true if the DOM element is visible, false if it's hidden.
93 // Checks if display is anything other than none.
94 util.isVisible = function (elem) {
96 if (window.getComputedStyle) {
98 return window.getComputedStyle(elem, null).getPropertyValue("display") !== "none";
100 else if (elem.currentStyle) {
102 return elem.currentStyle["display"] !== "none";
107 // Adds a listener callback to a DOM element which is fired on a specified
109 util.addEvent = function(elem, event, listener){
110 if (elem.attachEvent) {
111 // IE only. The "on" is mandatory.
112 elem.attachEvent("on" + event, listener);
116 elem.addEventListener(event, listener, false);
121 // Removes a listener callback from a DOM element which is fired on a specified
123 util.removeEvent = function(elem, event, listener){
124 if (elem.detachEvent) {
125 // IE only. The "on" is mandatory.
126 elem.detachEvent("on" + event, listener);
130 elem.removeEventListener(event, listener, false);
134 // Converts \r\n and \r to \n.
135 util.fixEolChars = function(text){
136 text = text.replace(/\r\n/g, "\n");
137 text = text.replace(/\r/g, "\n");
141 // Extends a regular expression. Returns a new RegExp
142 // using pre + regex + post as the expression.
143 // Used in a few functions where we have a base
144 // expression and we want to pre- or append some
145 // conditions to it (e.g. adding "$" to the end).
146 // The flags are unchanged.
148 // regex is a RegExp, pre and post are strings.
149 util.extendRegExp = function(regex, pre, post){
151 if (pre === null || pre === undefined)
155 if(post === null || post === undefined)
160 var pattern = regex.toString();
163 // Replace the flags with empty space and store them.
164 // Technically, this can match incorrect flags like "gmm".
165 var result = pattern.match(/\/([gim]*)$/);
166 if (result === null) {
173 // Remove the flags and slash delimiters from the regular expression.
174 pattern = pattern.replace(/(^\/|\/[gim]*$)/g, "");
175 pattern = pre + pattern + post;
177 return new RegExp(pattern, flags);
181 // Sets the image for a button passed to the WMD editor.
182 // Returns a new element with the image attached.
183 // Adds several style properties to the image.
184 util.createImage = function(img){
186 var imgPath = imageDirectory + img;
188 var elem = doc.createElement("img");
189 elem.className = "wmd-button";
196 // This simulates a modal dialog box and asks for the URL when you
197 // click the hyperlink or image buttons.
199 // text: The html for the input box.
200 // defaultInputText: The default value that appears in the input box.
201 // makeLinkMarkdown: The function which is executed when the prompt is dismissed, either via OK or Cancel
202 util.prompt = function(text, defaultInputText, makeLinkMarkdown){
204 // These variables need to be declared at this level since they are used
205 // in multiple functions.
206 var dialog; // The dialog box.
207 var background; // The background beind the dialog box.
208 var input; // The text box where you enter the hyperlink.
211 if (defaultInputText === undefined) {
212 defaultInputText = "";
215 // Used as a keydown event handler. Esc dismisses the prompt.
216 // Key code 27 is ESC.
217 var checkEscape = function(key){
218 var code = (key.charCode || key.keyCode);
224 // Dismisses the hyperlink input box.
225 // isCancel is true if we don't care about the input text.
226 // isCancel is false if we are going to keep the text.
227 var close = function(isCancel){
228 util.removeEvent(doc.body, "keydown", checkEscape);
229 var text = input.value;
235 // Fixes common pasting errors.
236 text = text.replace('http://http://', 'http://');
237 text = text.replace('http://https://', 'https://');
238 text = text.replace('http://ftp://', 'ftp://');
240 if (text.indexOf('http://') === -1 && text.indexOf('ftp://') === -1 && text.indexOf('https://') === -1) {
241 text = 'http://' + text;
245 dialog.parentNode.removeChild(dialog);
246 background.parentNode.removeChild(background);
247 makeLinkMarkdown(text);
251 // Creates the background behind the hyperlink text entry box.
252 // Most of this has been moved to CSS but the div creation and
253 // browser-specific hacks remain here.
254 var createBackground = function(){
256 background = doc.createElement("div");
257 background.className = "wmd-prompt-background";
258 style = background.style;
259 style.position = "absolute";
262 style.zIndex = "1000";
264 // Some versions of Konqueror don't support transparent colors
265 // so we make the whole window transparent.
267 // Is this necessary on modern konqueror browsers?
268 if (global.isKonqueror){
269 style.backgroundColor = "transparent";
271 else if (global.isIE){
272 style.filter = "alpha(opacity=50)";
275 style.opacity = "0.5";
278 var pageSize = position.getPageSize();
279 style.height = pageSize[1] + "px";
282 style.left = doc.documentElement.scrollLeft;
283 style.width = doc.documentElement.clientWidth;
287 style.width = "100%";
290 doc.body.appendChild(background);
293 // Create the text input box form/window.
294 var createDialog = function(){
296 // The main dialog box.
297 dialog = doc.createElement("div");
298 dialog.className = "wmd-prompt-dialog";
299 dialog.style.padding = "10px;";
300 dialog.style.position = "fixed";
301 dialog.style.width = "400px";
302 dialog.style.zIndex = "1001";
305 var question = doc.createElement("div");
306 question.innerHTML = text;
307 question.style.padding = "5px";
308 dialog.appendChild(question);
310 // The web form container for the text box and buttons.
311 var form = doc.createElement("form");
312 form.onsubmit = function(){ return close(false); };
316 style.cssFloat = "left";
317 style.width = "100%";
318 style.textAlign = "center";
319 style.position = "relative";
320 dialog.appendChild(form);
322 // The input text box
323 input = doc.createElement("input");
325 input.value = defaultInputText;
327 style.display = "block";
329 style.marginLeft = style.marginRight = "auto";
330 form.appendChild(input);
333 var okButton = doc.createElement("input");
334 okButton.type = "button";
335 okButton.onclick = function(){ return close(false); };
336 okButton.value = "OK";
337 style = okButton.style;
338 style.margin = "10px";
339 style.display = "inline";
344 var cancelButton = doc.createElement("input");
345 cancelButton.type = "button";
346 cancelButton.onclick = function(){ return close(true); };
347 cancelButton.value = "Cancel";
348 style = cancelButton.style;
349 style.margin = "10px";
350 style.display = "inline";
353 // The order of these buttons is different on macs.
354 if (/mac/.test(nav.platform.toLowerCase())) {
355 form.appendChild(cancelButton);
356 form.appendChild(okButton);
359 form.appendChild(okButton);
360 form.appendChild(cancelButton);
363 util.addEvent(doc.body, "keydown", checkEscape);
364 dialog.style.top = "50%";
365 dialog.style.left = "50%";
366 dialog.style.display = "block";
367 if(global.isIE_5or6){
368 dialog.style.position = "absolute";
369 dialog.style.top = doc.documentElement.scrollTop + 200 + "px";
370 dialog.style.left = "50%";
372 doc.body.appendChild(dialog);
374 // This has to be done AFTER adding the dialog to the form if you
375 // want it to be centered.
376 dialog.style.marginTop = -(position.getHeight(dialog) / 2) + "px";
377 dialog.style.marginLeft = -(position.getWidth(dialog) / 2) + "px";
383 // Why is this in a zero-length timeout?
384 // Is it working around a browser bug?
385 top.setTimeout(function(){
389 var defTextLen = defaultInputText.length;
390 if (input.selectionStart !== undefined) {
391 input.selectionStart = 0;
392 input.selectionEnd = defTextLen;
394 else if (input.createTextRange) {
395 var range = input.createTextRange();
396 range.collapse(false);
397 range.moveStart("character", -defTextLen);
398 range.moveEnd("character", defTextLen);
408 // The assignment in the while loop makes jslint cranky.
409 // I'll change it to a better loop later.
410 position.getTop = function(elem, isInner){
411 var result = elem.offsetTop;
413 while (elem = elem.offsetParent) {
414 result += elem.offsetTop;
420 position.getHeight = function (elem) {
421 return elem.offsetHeight || elem.scrollHeight;
424 position.getWidth = function (elem) {
425 return elem.offsetWidth || elem.scrollWidth;
428 position.getPageSize = function(){
430 var scrollWidth, scrollHeight;
431 var innerWidth, innerHeight;
433 // It's not very clear which blocks work with which browsers.
434 if(self.innerHeight && self.scrollMaxY){
435 scrollWidth = doc.body.scrollWidth;
436 scrollHeight = self.innerHeight + self.scrollMaxY;
438 else if(doc.body.scrollHeight > doc.body.offsetHeight){
439 scrollWidth = doc.body.scrollWidth;
440 scrollHeight = doc.body.scrollHeight;
443 scrollWidth = doc.body.offsetWidth;
444 scrollHeight = doc.body.offsetHeight;
447 if(self.innerHeight){
449 innerWidth = self.innerWidth;
450 innerHeight = self.innerHeight;
452 else if(doc.documentElement && doc.documentElement.clientHeight){
453 // Some versions of IE (IE 6 w/ a DOCTYPE declaration)
454 innerWidth = doc.documentElement.clientWidth;
455 innerHeight = doc.documentElement.clientHeight;
458 // Other versions of IE
459 innerWidth = doc.body.clientWidth;
460 innerHeight = doc.body.clientHeight;
463 var maxWidth = Math.max(scrollWidth, innerWidth);
464 var maxHeight = Math.max(scrollHeight, innerHeight);
465 return [maxWidth, maxHeight, innerWidth, innerHeight];
468 // Watches the input textarea, polling at an interval and runs
469 // a callback function if anything has changed.
470 wmd.inputPoller = function(callback, interval){
472 var pollerObj = this;
473 var inputArea = wmd.panels.input;
475 // Stored start, end and text. Used to see if there are changes to the input.
480 var killHandle; // Used to cancel monitoring on destruction.
481 // Checks to see if anything has changed in the textarea.
482 // If so, it runs the callback.
483 this.tick = function(){
485 if (!util.isVisible(inputArea)) {
489 // Update the selection start and end, text.
490 if (inputArea.selectionStart || inputArea.selectionStart === 0) {
491 var start = inputArea.selectionStart;
492 var end = inputArea.selectionEnd;
493 if (start != lastStart || end != lastEnd) {
497 if (markdown != inputArea.value) {
498 markdown = inputArea.value;
507 var doTickCallback = function(){
509 if (!util.isVisible(inputArea)) {
513 // If anything has changed, call the function.
514 if (pollerObj.tick()) {
519 // Set how often we poll the textarea for changes.
520 var assignInterval = function(){
521 // previewPollInterval is set at the top of the namespace.
522 killHandle = top.setInterval(doTickCallback, interval);
525 this.destroy = function(){
526 top.clearInterval(killHandle);
532 // Handles pushing and popping TextareaStates for undo/redo commands.
533 // I should rename the stack variables to list.
534 wmd.undoManager = function(callback){
537 var undoStack = []; // A stack of undo states
538 var stackPtr = 0; // The index of the current state
540 var lastState; // The last state
542 var timer; // The setTimeout handle for cancelling the timer
545 // Set the mode for later logic steps.
546 var setMode = function(newMode, noSave){
548 if (mode != newMode) {
555 if (!global.isIE || mode != "moving") {
556 timer = top.setTimeout(refreshState, 1);
559 inputStateObj = null;
563 var refreshState = function(){
564 inputStateObj = new wmd.TextareaState();
569 this.setCommandMode = function(){
572 timer = top.setTimeout(refreshState, 0);
575 this.canUndo = function(){
579 this.canRedo = function(){
580 if (undoStack[stackPtr + 1]) {
586 // Removes the last state and restores it.
587 this.undo = function(){
589 if (undoObj.canUndo()) {
591 // What about setting state -1 to null or checking for undefined?
596 undoStack[stackPtr] = new wmd.TextareaState();
597 undoStack[--stackPtr].restore();
606 wmd.panels.input.focus();
611 this.redo = function(){
613 if (undoObj.canRedo()) {
615 undoStack[++stackPtr].restore();
623 wmd.panels.input.focus();
627 // Push the input area state to the stack.
628 var saveState = function(){
630 var currState = inputStateObj || new wmd.TextareaState();
635 if (mode == "moving") {
637 lastState = currState;
642 if (undoStack[stackPtr - 1].text != lastState.text) {
643 undoStack[stackPtr++] = lastState;
647 undoStack[stackPtr++] = currState;
648 undoStack[stackPtr + 1] = null;
654 var handleCtrlYZ = function(event){
658 if (event.ctrlKey || event.metaKey) {
660 // IE and Opera do not support charCode.
661 var keyCode = event.charCode || event.keyCode;
662 var keyCodeChar = String.fromCharCode(keyCode);
664 switch (keyCodeChar) {
672 if (!event.shiftKey) {
684 if (event.preventDefault) {
685 event.preventDefault();
688 top.event.returnValue = false;
694 // Set the mode depending on what is going on in the input area.
695 var handleModeChange = function(event){
697 if (!event.ctrlKey && !event.metaKey) {
699 var keyCode = event.keyCode;
701 if ((keyCode >= 33 && keyCode <= 40) || (keyCode >= 63232 && keyCode <= 63235)) {
702 // 33 - 40: page up/dn and arrow keys
703 // 63232 - 63235: page up/dn and arrow keys on safari
706 else if (keyCode == 8 || keyCode == 46 || keyCode == 127) {
712 else if (keyCode == 13) {
716 else if (keyCode == 27) {
720 else if ((keyCode < 16 || keyCode > 20) && keyCode != 91) {
721 // 16-20 are shift, etc.
722 // 91: left window key
723 // I think this might be a little messed up since there are
724 // a lot of nonprinting keys above 20.
730 var setEventHandlers = function(){
732 util.addEvent(wmd.panels.input, "keypress", function(event){
735 if ((event.ctrlKey || event.metaKey) && (event.keyCode == 89 || event.keyCode == 90)) {
736 event.preventDefault();
740 var handlePaste = function(){
741 if (global.isIE || (inputStateObj && inputStateObj.text != wmd.panels.input.value)) {
742 if (timer == undefined) {
750 // pastePollInterval is specified at the beginning of this namespace.
751 poller = new wmd.inputPoller(handlePaste, pastePollInterval);
753 util.addEvent(wmd.panels.input, "keydown", handleCtrlYZ);
754 util.addEvent(wmd.panels.input, "keydown", handleModeChange);
756 util.addEvent(wmd.panels.input, "mousedown", function(){
759 wmd.panels.input.onpaste = handlePaste;
760 wmd.panels.input.ondrop = handlePaste;
763 var init = function(){
769 this.destroy = function(){
778 // I think my understanding of how the buttons and callbacks are stored in the array is incomplete.
779 wmd.editor = function(previewRefreshCallback){
781 if (!previewRefreshCallback) {
782 previewRefreshCallback = function(){};
785 var inputBox = wmd.panels.input;
787 var offsetHeight = 0;
794 var div; // This name is pretty ambiguous. I should rename this.
796 // Used to cancel recurring events from setInterval.
799 var undoMgr; // The undo manager
801 // Perform the button's action.
802 var doClick = function(button){
809 undoMgr.setCommandMode();
812 var state = new wmd.TextareaState();
818 var chunks = state.getChunks();
820 // Some commands launch a "modal" prompt dialog. Javascript
821 // can't really make a modal dialog box and the WMD code
822 // will continue to execute while the dialog is displayed.
823 // This prevents the dialog pattern I'm used to and means
824 // I can't do something like this:
826 // var link = CreateLinkDialog();
827 // makeMarkdownLink(link);
829 // Instead of this straightforward method of handling a
830 // dialog I have to pass any code which would execute
831 // after the dialog is dismissed (e.g. link creation)
832 // in a function parameter.
834 // Yes this is awkward and I think it sucks, but there's
835 // no real workaround. Only the image and link code
836 // create dialogs and require the function pointers.
837 var fixupInputArea = function(){
842 state.setChunks(chunks);
846 previewRefreshCallback();
849 var useDefaultText = true;
850 var noCleanup = button.textOp(chunks, fixupInputArea, useDefaultText);
858 if (button.execute) {
859 button.execute(editObj);
863 var setUndoRedoButtonStates = function(){
865 setupButton(document.getElementById("wmd-undo-button"), undoMgr.canUndo());
866 setupButton(document.getElementById("wmd-redo-button"), undoMgr.canRedo());
870 var setupButton = function(button, isEnabled) {
872 var normalYShift = "0px";
873 var disabledYShift = "-20px";
874 var highlightYShift = "-40px";
877 button.style.backgroundPosition = button.XShift + " " + normalYShift;
878 button.onmouseover = function(){
879 this.style.backgroundPosition = this.XShift + " " + highlightYShift;
882 button.onmouseout = function(){
883 this.style.backgroundPosition = this.XShift + " " + normalYShift;
886 // IE tries to select the background image "button" text (it's
887 // implemented in a list item) so we have to cache the selection
890 button.onmousedown = function() {
891 wmd.ieRetardedClick = true;
892 wmd.ieCachedRange = document.selection.createRange();
898 button.onclick = function() {
899 if (this.onmouseout) {
908 button.style.backgroundPosition = button.XShift + " " + disabledYShift;
909 button.onmouseover = button.onmouseout = button.onclick = function(){};
913 var makeSpritedButtonRow = function(){
915 var buttonBar = document.getElementById("wmd-button-bar");
917 var normalYShift = "0px";
918 var disabledYShift = "-20px";
919 var highlightYShift = "-40px";
921 var buttonRow = document.createElement("ul");
922 buttonRow.id = "wmd-button-row";
923 buttonRow = buttonBar.appendChild(buttonRow);
926 var boldButton = document.createElement("li");
927 boldButton.className = "wmd-button";
928 boldButton.id = "wmd-bold-button";
929 boldButton.title = "Strong <strong> Ctrl+B";
930 boldButton.XShift = "0px";
931 boldButton.textOp = command.doBold;
932 setupButton(boldButton, true);
933 buttonRow.appendChild(boldButton);
935 var italicButton = document.createElement("li");
936 italicButton.className = "wmd-button";
937 italicButton.id = "wmd-italic-button";
938 italicButton.title = "Emphasis <em> Ctrl+I";
939 italicButton.XShift = "-20px";
940 italicButton.textOp = command.doItalic;
941 setupButton(italicButton, true);
942 buttonRow.appendChild(italicButton);
944 var spacer1 = document.createElement("li");
945 spacer1.className = "wmd-spacer";
946 spacer1.id = "wmd-spacer1";
947 buttonRow.appendChild(spacer1);
949 var linkButton = document.createElement("li");
950 linkButton.className = "wmd-button";
951 linkButton.id = "wmd-link-button";
952 linkButton.title = "Hyperlink <a> Ctrl+L";
953 linkButton.XShift = "-40px";
954 linkButton.textOp = function(chunk, postProcessing, useDefaultText){
955 return command.doLinkOrImage(chunk, postProcessing, false);
957 setupButton(linkButton, true);
958 buttonRow.appendChild(linkButton);
960 var quoteButton = document.createElement("li");
961 quoteButton.className = "wmd-button";
962 quoteButton.id = "wmd-quote-button";
963 quoteButton.title = "Blockquote <blockquote> Ctrl+Q";
964 quoteButton.XShift = "-60px";
965 quoteButton.textOp = command.doBlockquote;
966 setupButton(quoteButton, true);
967 buttonRow.appendChild(quoteButton);
969 var codeButton = document.createElement("li");
970 codeButton.className = "wmd-button";
971 codeButton.id = "wmd-code-button";
972 codeButton.title = "Code Sample <pre><code> Ctrl+K";
973 codeButton.XShift = "-80px";
974 codeButton.textOp = command.doCode;
975 setupButton(codeButton, true);
976 buttonRow.appendChild(codeButton);
978 var imageButton = document.createElement("li");
979 imageButton.className = "wmd-button";
980 imageButton.id = "wmd-image-button";
981 imageButton.title = "Image <img> Ctrl+G";
982 imageButton.XShift = "-100px";
983 imageButton.textOp = function(chunk, postProcessing, useDefaultText){
984 return command.doLinkOrImage(chunk, postProcessing, true);
986 setupButton(imageButton, true);
987 buttonRow.appendChild(imageButton);
989 var spacer2 = document.createElement("li");
990 spacer2.className = "wmd-spacer";
991 spacer2.id = "wmd-spacer2";
992 buttonRow.appendChild(spacer2);
994 var olistButton = document.createElement("li");
995 olistButton.className = "wmd-button";
996 olistButton.id = "wmd-olist-button";
997 olistButton.title = "Numbered List <ol> Ctrl+O";
998 olistButton.XShift = "-120px";
999 olistButton.textOp = function(chunk, postProcessing, useDefaultText){
1000 command.doList(chunk, postProcessing, true, useDefaultText);
1002 setupButton(olistButton, true);
1003 buttonRow.appendChild(olistButton);
1005 var ulistButton = document.createElement("li");
1006 ulistButton.className = "wmd-button";
1007 ulistButton.id = "wmd-ulist-button";
1008 ulistButton.title = "Bulleted List <ul> Ctrl+U";
1009 ulistButton.XShift = "-140px";
1010 ulistButton.textOp = function(chunk, postProcessing, useDefaultText){
1011 command.doList(chunk, postProcessing, false, useDefaultText);
1013 setupButton(ulistButton, true);
1014 buttonRow.appendChild(ulistButton);
1016 var headingButton = document.createElement("li");
1017 headingButton.className = "wmd-button";
1018 headingButton.id = "wmd-heading-button";
1019 headingButton.title = "Heading <h1>/<h2> Ctrl+H";
1020 headingButton.XShift = "-160px";
1021 headingButton.textOp = command.doHeading;
1022 setupButton(headingButton, true);
1023 buttonRow.appendChild(headingButton);
1025 var hrButton = document.createElement("li");
1026 hrButton.className = "wmd-button";
1027 hrButton.id = "wmd-hr-button";
1028 hrButton.title = "Horizontal Rule <hr> Ctrl+R";
1029 hrButton.XShift = "-180px";
1030 hrButton.textOp = command.doHorizontalRule;
1031 setupButton(hrButton, true);
1032 buttonRow.appendChild(hrButton);
1034 var spacer3 = document.createElement("li");
1035 spacer3.className = "wmd-spacer";
1036 spacer3.id = "wmd-spacer3";
1037 buttonRow.appendChild(spacer3);
1039 var undoButton = document.createElement("li");
1040 undoButton.className = "wmd-button";
1041 undoButton.id = "wmd-undo-button";
1042 undoButton.title = "Undo - Ctrl+Z";
1043 undoButton.XShift = "-200px";
1044 undoButton.execute = function(manager){
1047 setupButton(undoButton, true);
1048 buttonRow.appendChild(undoButton);
1050 var redoButton = document.createElement("li");
1051 redoButton.className = "wmd-button";
1052 redoButton.id = "wmd-redo-button";
1053 redoButton.title = "Redo - Ctrl+Y";
1054 if (/win/.test(nav.platform.toLowerCase())) {
1055 redoButton.title = "Redo - Ctrl+Y";
1058 // mac and other non-Windows platforms
1059 redoButton.title = "Redo - Ctrl+Shift+Z";
1061 redoButton.XShift = "-220px";
1062 redoButton.execute = function(manager){
1065 setupButton(redoButton, true);
1066 buttonRow.appendChild(redoButton);
1068 setUndoRedoButtonStates();
1071 var setupEditor = function(){
1073 if (/\?noundo/.test(doc.location.href)) {
1074 wmd.nativeUndo = true;
1077 if (!wmd.nativeUndo) {
1078 undoMgr = new wmd.undoManager(function(){
1079 previewRefreshCallback();
1080 setUndoRedoButtonStates();
1084 makeSpritedButtonRow();
1087 var keyEvent = "keydown";
1088 if (global.isOpera) {
1089 keyEvent = "keypress";
1092 util.addEvent(inputBox, keyEvent, function(key){
1094 // Check to see if we have a button key and, if so execute the callback.
1095 if (key.ctrlKey || key.metaKey) {
1097 var keyCode = key.charCode || key.keyCode;
1098 var keyCodeStr = String.fromCharCode(keyCode).toLowerCase();
1100 // Bugfix for messed up DEL and .
1101 if (keyCode === 46) {
1104 if (keyCode === 190) {
1108 switch(keyCodeStr) {
1110 doClick(document.getElementById("wmd-bold-button"));
1113 doClick(document.getElementById("wmd-italic-button"));
1116 doClick(document.getElementById("wmd-link-button"));
1119 doClick(document.getElementById("wmd-quote-button"));
1122 doClick(document.getElementById("wmd-code-button"));
1125 doClick(document.getElementById("wmd-image-button"));
1128 doClick(document.getElementById("wmd-olist-button"));
1131 doClick(document.getElementById("wmd-ulist-button"));
1134 doClick(document.getElementById("wmd-heading-button"));
1137 doClick(document.getElementById("wmd-hr-button"));
1140 doClick(document.getElementById("wmd-redo-button"));
1144 doClick(document.getElementById("wmd-redo-button"));
1147 doClick(document.getElementById("wmd-undo-button"));
1155 if (key.preventDefault) {
1156 key.preventDefault();
1160 top.event.returnValue = false;
1165 // Auto-continue lists, code blocks and block quotes when
1166 // the enter key is pressed.
1167 util.addEvent(inputBox, "keyup", function(key){
1168 if (!key.shiftKey && !key.ctrlKey && !key.metaKey) {
1169 var keyCode = key.charCode || key.keyCode;
1170 // Key code 13 is Enter
1171 if (keyCode === 13) {
1173 fakeButton.textOp = command.doAutoindent;
1174 doClick(fakeButton);
1179 // Disable ESC clearing the input textarea on IE
1181 util.addEvent(inputBox, "keydown", function(key){
1182 var code = key.keyCode;
1183 // Key code 27 is ESC
1190 if (inputBox.form) {
1191 var submitCallback = inputBox.form.onsubmit;
1192 inputBox.form.onsubmit = function(){
1194 if (submitCallback) {
1195 return submitCallback.apply(this, arguments);
1201 // Convert the contents of the input textarea to HTML in the output/preview panels.
1202 var convertToHtml = function(){
1205 var markdownConverter = new wmd.showdown.converter();
1207 var text = inputBox.value;
1209 var callback = function(){
1210 inputBox.value = text;
1213 if (!/markdown/.test(wmd.wmd_env.output.toLowerCase())) {
1214 if (markdownConverter) {
1215 inputBox.value = markdownConverter.makeHtml(text);
1216 top.setTimeout(callback, 0);
1223 this.undo = function(){
1229 this.redo = function(){
1235 // This is pretty useless. The setupEditor function contents
1236 // should just be copied here.
1237 var init = function(){
1241 this.destroy = function(){
1245 if (div.parentNode) {
1246 div.parentNode.removeChild(div);
1249 inputBox.style.marginTop = "";
1251 top.clearInterval(creationHandle);
1257 // The input textarea state/contents.
1258 // This is used to implement undo/redo by the undo manager.
1259 wmd.TextareaState = function(){
1262 var stateObj = this;
1263 var inputArea = wmd.panels.input;
1265 this.init = function() {
1267 if (!util.isVisible(inputArea)) {
1271 this.setInputAreaSelectionStartEnd();
1272 this.scrollTop = inputArea.scrollTop;
1273 if (!this.text && inputArea.selectionStart || inputArea.selectionStart === 0) {
1274 this.text = inputArea.value;
1279 // Sets the selected text in the input box after we've performed an
1281 this.setInputAreaSelection = function(){
1283 if (!util.isVisible(inputArea)) {
1287 if (inputArea.selectionStart !== undefined && !global.isOpera) {
1290 inputArea.selectionStart = stateObj.start;
1291 inputArea.selectionEnd = stateObj.end;
1292 inputArea.scrollTop = stateObj.scrollTop;
1294 else if (doc.selection) {
1296 if (doc.activeElement && doc.activeElement !== inputArea) {
1301 var range = inputArea.createTextRange();
1302 range.moveStart("character", -inputArea.value.length);
1303 range.moveEnd("character", -inputArea.value.length);
1304 range.moveEnd("character", stateObj.end);
1305 range.moveStart("character", stateObj.start);
1310 this.setInputAreaSelectionStartEnd = function(){
1312 if (inputArea.selectionStart || inputArea.selectionStart === 0) {
1314 stateObj.start = inputArea.selectionStart;
1315 stateObj.end = inputArea.selectionEnd;
1317 else if (doc.selection) {
1319 stateObj.text = util.fixEolChars(inputArea.value);
1321 // IE loses the selection in the textarea when buttons are
1322 // clicked. On IE we cache the selection and set a flag
1323 // which we check for here.
1325 if(wmd.ieRetardedClick && wmd.ieCachedRange) {
1326 range = wmd.ieCachedRange;
1327 wmd.ieRetardedClick = false;
1330 range = doc.selection.createRange();
1333 var fixedRange = util.fixEolChars(range.text);
1334 var marker = "\x07";
1335 var markedRange = marker + fixedRange + marker;
1336 range.text = markedRange;
1337 var inputText = util.fixEolChars(inputArea.value);
1339 range.moveStart("character", -markedRange.length);
1340 range.text = fixedRange;
1342 stateObj.start = inputText.indexOf(marker);
1343 stateObj.end = inputText.lastIndexOf(marker) - marker.length;
1345 var len = stateObj.text.length - util.fixEolChars(inputArea.value).length;
1348 range.moveStart("character", -fixedRange.length);
1353 range.text = fixedRange;
1356 this.setInputAreaSelection();
1360 // Restore this state into the input area.
1361 this.restore = function(){
1363 if (stateObj.text != undefined && stateObj.text != inputArea.value) {
1364 inputArea.value = stateObj.text;
1366 this.setInputAreaSelection();
1367 inputArea.scrollTop = stateObj.scrollTop;
1370 // Gets a collection of HTML chunks from the inptut textarea.
1371 this.getChunks = function(){
1373 var chunk = new wmd.Chunks();
1375 chunk.before = util.fixEolChars(stateObj.text.substring(0, stateObj.start));
1376 chunk.startTag = "";
1377 chunk.selection = util.fixEolChars(stateObj.text.substring(stateObj.start, stateObj.end));
1379 chunk.after = util.fixEolChars(stateObj.text.substring(stateObj.end));
1380 chunk.scrollTop = stateObj.scrollTop;
1385 // Sets the TextareaState properties given a chunk of markdown.
1386 this.setChunks = function(chunk){
1388 chunk.before = chunk.before + chunk.startTag;
1389 chunk.after = chunk.endTag + chunk.after;
1391 if (global.isOpera) {
1392 chunk.before = chunk.before.replace(/\n/g, "\r\n");
1393 chunk.selection = chunk.selection.replace(/\n/g, "\r\n");
1394 chunk.after = chunk.after.replace(/\n/g, "\r\n");
1397 this.start = chunk.before.length;
1398 this.end = chunk.before.length + chunk.selection.length;
1399 this.text = chunk.before + chunk.selection + chunk.after;
1400 this.scrollTop = chunk.scrollTop;
1406 // before: contains all the text in the input box BEFORE the selection.
1407 // after: contains all the text in the input box AFTER the selection.
1408 wmd.Chunks = function(){
1411 // startRegex: a regular expression to find the start tag
1412 // endRegex: a regular expresssion to find the end tag
1413 wmd.Chunks.prototype.findTags = function(startRegex, endRegex){
1415 var chunkObj = this;
1420 regex = util.extendRegExp(startRegex, "", "$");
1422 this.before = this.before.replace(regex,
1424 chunkObj.startTag = chunkObj.startTag + match;
1428 regex = util.extendRegExp(startRegex, "^", "");
1430 this.selection = this.selection.replace(regex,
1432 chunkObj.startTag = chunkObj.startTag + match;
1439 regex = util.extendRegExp(endRegex, "", "$");
1441 this.selection = this.selection.replace(regex,
1443 chunkObj.endTag = match + chunkObj.endTag;
1447 regex = util.extendRegExp(endRegex, "^", "");
1449 this.after = this.after.replace(regex,
1451 chunkObj.endTag = match + chunkObj.endTag;
1457 // If remove is false, the whitespace is transferred
1458 // to the before/after regions.
1460 // If remove is true, the whitespace disappears.
1461 wmd.Chunks.prototype.trimWhitespace = function(remove){
1463 this.selection = this.selection.replace(/^(\s*)/, "");
1466 this.before += re.$1;
1469 this.selection = this.selection.replace(/(\s*)$/, "");
1472 this.after = re.$1 + this.after;
1477 wmd.Chunks.prototype.addBlankLines = function(nLinesBefore, nLinesAfter, findExtraNewlines){
1479 if (nLinesBefore === undefined) {
1483 if (nLinesAfter === undefined) {
1491 var replacementText;
1493 this.selection = this.selection.replace(/(^\n*)/, "");
1494 this.startTag = this.startTag + re.$1;
1495 this.selection = this.selection.replace(/(\n*$)/, "");
1496 this.endTag = this.endTag + re.$1;
1497 this.startTag = this.startTag.replace(/(^\n*)/, "");
1498 this.before = this.before + re.$1;
1499 this.endTag = this.endTag.replace(/(\n*$)/, "");
1500 this.after = this.after + re.$1;
1504 regexText = replacementText = "";
1506 while (nLinesBefore--) {
1507 regexText += "\\n?";
1508 replacementText += "\n";
1511 if (findExtraNewlines) {
1514 this.before = this.before.replace(new re(regexText + "$", ""), replacementText);
1519 regexText = replacementText = "";
1521 while (nLinesAfter--) {
1522 regexText += "\\n?";
1523 replacementText += "\n";
1525 if (findExtraNewlines) {
1529 this.after = this.after.replace(new re(regexText, ""), replacementText);
1533 // The markdown symbols - 4 spaces = code, > = blockquote, etc.
1534 command.prefixes = "(?:\\s{4,}|\\s*>|\\s*-\\s+|\\s*\\d+\\.|=|\\+|-|_|\\*|#|\\s*\\[[^\n]]+\\]:)";
1536 // Remove markdown symbols from the chunk selection.
1537 command.unwrap = function(chunk){
1538 var txt = new re("([^\\n])\\n(?!(\\n|" + command.prefixes + "))", "g");
1539 chunk.selection = chunk.selection.replace(txt, "$1 $2");
1542 command.wrap = function(chunk, len){
1543 command.unwrap(chunk);
1544 var regex = new re("(.{1," + len + "})( +|$\\n?)", "gm");
1546 chunk.selection = chunk.selection.replace(regex, function(line, marked){
1547 if (new re("^" + command.prefixes, "").test(line)) {
1550 return marked + "\n";
1553 chunk.selection = chunk.selection.replace(/\s+$/, "");
1556 command.doBold = function(chunk, postProcessing, useDefaultText){
1557 return command.doBorI(chunk, 2, "strong text");
1560 command.doItalic = function(chunk, postProcessing, useDefaultText){
1561 return command.doBorI(chunk, 1, "emphasized text");
1564 // chunk: The selected region that will be enclosed with */**
1565 // nStars: 1 for italics, 2 for bold
1566 // insertText: If you just click the button without highlighting text, this gets inserted
1567 command.doBorI = function(chunk, nStars, insertText){
1569 // Get rid of whitespace and fixup newlines.
1570 chunk.trimWhitespace();
1571 chunk.selection = chunk.selection.replace(/\n{2,}/g, "\n");
1573 // Look for stars before and after. Is the chunk already marked up?
1574 chunk.before.search(/(\**$)/);
1575 var starsBefore = re.$1;
1577 chunk.after.search(/(^\**)/);
1578 var starsAfter = re.$1;
1580 var prevStars = Math.min(starsBefore.length, starsAfter.length);
1582 // Remove stars if we have to since the button acts as a toggle.
1583 if ((prevStars >= nStars) && (prevStars != 2 || nStars != 1)) {
1584 chunk.before = chunk.before.replace(re("[*]{" + nStars + "}$", ""), "");
1585 chunk.after = chunk.after.replace(re("^[*]{" + nStars + "}", ""), "");
1587 else if (!chunk.selection && starsAfter) {
1588 // It's not really clear why this code is necessary. It just moves
1589 // some arbitrary stuff around.
1590 chunk.after = chunk.after.replace(/^([*_]*)/, "");
1591 chunk.before = chunk.before.replace(/(\s?)$/, "");
1592 var whitespace = re.$1;
1593 chunk.before = chunk.before + starsAfter + whitespace;
1597 // In most cases, if you don't have any selected text and click the button
1598 // you'll get a selected, marked up region with the default text inserted.
1599 if (!chunk.selection && !starsAfter) {
1600 chunk.selection = insertText;
1603 // Add the true markup.
1604 var markup = nStars <= 1 ? "*" : "**"; // shouldn't the test be = ?
1605 chunk.before = chunk.before + markup;
1606 chunk.after = markup + chunk.after;
1612 command.stripLinkDefs = function(text, defsToAdd){
1614 text = text.replace(/^[ ]{0,3}\[(\d+)\]:[ \t]*\n?[ \t]*<?(\S+?)>?[ \t]*\n?[ \t]*(?:(\n*)["(](.+?)[")][ \t]*)?(?:\n+|$)/gm,
1615 function(totalMatch, id, link, newlines, title){
1616 defsToAdd[id] = totalMatch.replace(/\s*$/, "");
1618 // Strip the title and return that separately.
1619 defsToAdd[id] = totalMatch.replace(/["(](.+?)[")]$/, "");
1620 return newlines + title;
1628 command.addLinkDef = function(chunk, linkDef){
1630 var refNumber = 0; // The current reference number
1631 var defsToAdd = {}; //
1632 // Start with a clean slate by removing all previous link definitions.
1633 chunk.before = command.stripLinkDefs(chunk.before, defsToAdd);
1634 chunk.selection = command.stripLinkDefs(chunk.selection, defsToAdd);
1635 chunk.after = command.stripLinkDefs(chunk.after, defsToAdd);
1638 var regex = /(\[(?:\[[^\]]*\]|[^\[\]])*\][ ]?(?:\n[ ]*)?\[)(\d+)(\])/g;
1640 var addDefNumber = function(def){
1642 def = def.replace(/^[ ]{0,3}\[(\d+)\]:/, " [" + refNumber + "]:");
1646 var getLink = function(wholeMatch, link, id, end){
1648 if (defsToAdd[id]) {
1649 addDefNumber(defsToAdd[id]);
1650 return link + refNumber + end;
1656 chunk.before = chunk.before.replace(regex, getLink);
1659 addDefNumber(linkDef);
1662 chunk.selection = chunk.selection.replace(regex, getLink);
1665 var refOut = refNumber;
1667 chunk.after = chunk.after.replace(regex, getLink);
1670 chunk.after = chunk.after.replace(/\n*$/, "");
1673 chunk.selection = chunk.selection.replace(/\n*$/, "");
1676 chunk.after += "\n\n" + defs;
1681 command.doLinkOrImage = function(chunk, postProcessing, isImage){
1683 chunk.trimWhitespace();
1684 chunk.findTags(/\s*!?\[/, /\][ ]?(?:\n[ ]*)?(\[.*?\])?/);
1686 if (chunk.endTag.length > 1) {
1688 chunk.startTag = chunk.startTag.replace(/!?\[/, "");
1690 command.addLinkDef(chunk, null);
1695 if (/\n\n/.test(chunk.selection)) {
1696 command.addLinkDef(chunk, null);
1700 // The function to be executed when you enter a link and press OK or Cancel.
1701 // Marks up the link and adds the ref.
1702 var makeLinkMarkdown = function(link){
1704 if (link !== null) {
1706 chunk.startTag = chunk.endTag = "";
1707 var linkDef = " [999]: " + link;
1709 var num = command.addLinkDef(chunk, linkDef);
1710 chunk.startTag = isImage ? "![" : "[";
1711 chunk.endTag = "][" + num + "]";
1713 if (!chunk.selection) {
1715 chunk.selection = "alt text";
1718 chunk.selection = "link text";
1726 util.prompt(imageDialogText, imageDefaultText, makeLinkMarkdown);
1729 util.prompt(linkDialogText, linkDefaultText, makeLinkMarkdown);
1735 util.makeAPI = function(){
1737 wmd.wmd.editor = wmd.editor;
1738 wmd.wmd.previewManager = wmd.previewManager;
1741 util.startEditor = function(){
1743 if (wmd.wmd_env.autostart === false) {
1748 var edit; // The editor (buttons + input + outputs) - the main object.
1749 var previewMgr; // The preview manager.
1751 // Fired after the page has fully loaded.
1752 var loadListener = function(){
1754 wmd.panels = new wmd.PanelCollection();
1756 previewMgr = new wmd.previewManager();
1757 var previewRefreshCallback = previewMgr.refresh;
1759 edit = new wmd.editor(previewRefreshCallback);
1761 previewMgr.refresh(true);
1765 util.addEvent(top, "load", loadListener);
1768 wmd.previewManager = function(){
1770 var managerObj = this;
1777 var maxDelay = 3000;
1778 var startType = "delayed"; // The other legal value is "manual"
1780 // Adds event listeners to elements and creates the input poller.
1781 var setupEvents = function(inputElem, listener){
1783 util.addEvent(inputElem, "input", listener);
1784 inputElem.onpaste = listener;
1785 inputElem.ondrop = listener;
1787 util.addEvent(inputElem, "keypress", listener);
1788 util.addEvent(inputElem, "keydown", listener);
1789 // previewPollInterval is set at the top of this file.
1790 poller = new wmd.inputPoller(listener, previewPollInterval);
1793 var getDocScrollTop = function(){
1797 if (top.innerHeight) {
1798 result = top.pageYOffset;
1801 if (doc.documentElement && doc.documentElement.scrollTop) {
1802 result = doc.documentElement.scrollTop;
1806 result = doc.body.scrollTop;
1812 var makePreviewHtml = function(){
1814 // If there are no registered preview and output panels
1815 // there is nothing to do.
1816 if (!wmd.panels.preview && !wmd.panels.output) {
1820 var text = wmd.panels.input.value;
1821 if (text && text == oldInputText) {
1822 return; // Input text hasn't changed.
1825 oldInputText = text;
1828 var prevTime = new Date().getTime();
1830 if (!converter && wmd.showdown) {
1831 converter = new wmd.showdown.converter();
1835 text = converter.makeHtml(text);
1838 // Calculate the processing time of the HTML creation.
1839 // It's used as the delay time in the event listener.
1840 var currTime = new Date().getTime();
1841 elapsedTime = currTime - prevTime;
1843 pushPreviewHtml(text);
1847 // setTimeout is already used. Used as an event listener.
1848 var applyTimeout = function(){
1851 top.clearTimeout(timeout);
1852 timeout = undefined;
1855 if (startType !== "manual") {
1859 if (startType === "delayed") {
1860 delay = elapsedTime;
1863 if (delay > maxDelay) {
1866 timeout = top.setTimeout(makePreviewHtml, delay);
1870 var getScaleFactor = function(panel){
1871 if (panel.scrollHeight <= panel.clientHeight) {
1874 return panel.scrollTop / (panel.scrollHeight - panel.clientHeight);
1877 var setPanelScrollTops = function(){
1879 if (wmd.panels.preview) {
1880 wmd.panels.preview.scrollTop = (wmd.panels.preview.scrollHeight - wmd.panels.preview.clientHeight) * getScaleFactor(wmd.panels.preview);
1884 if (wmd.panels.output) {
1885 wmd.panels.output.scrollTop = (wmd.panels.output.scrollHeight - wmd.panels.output.clientHeight) * getScaleFactor(wmd.panels.output);
1890 this.refresh = function(requiresRefresh){
1892 if (requiresRefresh) {
1901 this.processingTime = function(){
1906 this.output = function(){
1910 // The mode can be "manual" or "delayed"
1911 this.setUpdateMode = function(mode){
1913 managerObj.refresh();
1916 var isFirstTimeFilled = true;
1918 var pushPreviewHtml = function(text){
1920 var emptyTop = position.getTop(wmd.panels.input) - getDocScrollTop();
1922 // Send the encoded HTML to the output textarea/div.
1923 if (wmd.panels.output) {
1924 // The value property is only defined if the output is a textarea.
1925 if (wmd.panels.output.value !== undefined) {
1926 wmd.panels.output.value = text;
1927 wmd.panels.output.readOnly = true;
1929 // Otherwise we are just replacing the text in a div.
1930 // Send the HTML wrapped in <pre><code>
1932 var newText = text.replace(/&/g, "&");
1933 newText = newText.replace(/</g, "<");
1934 wmd.panels.output.innerHTML = "<pre><code>" + newText + "</code></pre>";
1938 if (wmd.panels.preview) {
1939 wmd.panels.preview.innerHTML = text;
1942 setPanelScrollTops();
1944 if (isFirstTimeFilled) {
1945 isFirstTimeFilled = false;
1949 var fullTop = position.getTop(wmd.panels.input) - getDocScrollTop();
1952 top.setTimeout(function(){
1953 top.scrollBy(0, fullTop - emptyTop);
1957 top.scrollBy(0, fullTop - emptyTop);
1961 var init = function(){
1963 setupEvents(wmd.panels.input, applyTimeout);
1966 if (wmd.panels.preview) {
1967 wmd.panels.preview.scrollTop = 0;
1969 if (wmd.panels.output) {
1970 wmd.panels.output.scrollTop = 0;
1974 this.destroy = function(){
1983 // Moves the cursor to the next line and continues lists, quotes and code.
1984 command.doAutoindent = function(chunk, postProcessing, useDefaultText){
1986 chunk.before = chunk.before.replace(/(\n|^)[ ]{0,3}([*+-]|\d+[.])[ \t]*\n$/, "\n\n");
1987 chunk.before = chunk.before.replace(/(\n|^)[ ]{0,3}>[ \t]*\n$/, "\n\n");
1988 chunk.before = chunk.before.replace(/(\n|^)[ \t]+\n$/, "\n\n");
1990 useDefaultText = false;
1992 if(/(\n|^)[ ]{0,3}([*+-])[ \t]+.*\n$/.test(chunk.before)){
1994 command.doList(chunk, postProcessing, false, true);
1997 if(/(\n|^)[ ]{0,3}(\d+[.])[ \t]+.*\n$/.test(chunk.before)){
1999 command.doList(chunk, postProcessing, true, true);
2002 if(/(\n|^)[ ]{0,3}>[ \t]+.*\n$/.test(chunk.before)){
2003 if(command.doBlockquote){
2004 command.doBlockquote(chunk, postProcessing, useDefaultText);
2007 if(/(\n|^)(\t|[ ]{4,}).*\n$/.test(chunk.before)){
2009 command.doCode(chunk, postProcessing, useDefaultText);
2014 command.doBlockquote = function(chunk, postProcessing, useDefaultText){
2016 chunk.selection = chunk.selection.replace(/^(\n*)([^\r]+?)(\n*)$/,
2017 function(totalMatch, newlinesBefore, text, newlinesAfter){
2018 chunk.before += newlinesBefore;
2019 chunk.after = newlinesAfter + chunk.after;
2023 chunk.before = chunk.before.replace(/(>[ \t]*)$/,
2024 function(totalMatch, blankLine){
2025 chunk.selection = blankLine + chunk.selection;
2029 var defaultText = useDefaultText ? "Blockquote" : "";
2030 chunk.selection = chunk.selection.replace(/^(\s|>)+$/ ,"");
2031 chunk.selection = chunk.selection || defaultText;
2034 chunk.before = chunk.before.replace(/\n?$/,"\n");
2037 chunk.after = chunk.after.replace(/^\n?/,"\n");
2040 chunk.before = chunk.before.replace(/(((\n|^)(\n[ \t]*)*>(.+\n)*.*)+(\n[ \t]*)*$)/,
2041 function(totalMatch){
2042 chunk.startTag = totalMatch;
2046 chunk.after = chunk.after.replace(/^(((\n|^)(\n[ \t]*)*>(.+\n)*.*)+(\n[ \t]*)*)/,
2047 function(totalMatch){
2048 chunk.endTag = totalMatch;
2052 var replaceBlanksInTags = function(useBracket){
2054 var replacement = useBracket ? "> " : "";
2057 chunk.startTag = chunk.startTag.replace(/\n((>|\s)*)\n$/,
2058 function(totalMatch, markdown){
2059 return "\n" + markdown.replace(/^[ ]{0,3}>?[ \t]*$/gm, replacement) + "\n";
2063 chunk.endTag = chunk.endTag.replace(/^\n((>|\s)*)\n/,
2064 function(totalMatch, markdown){
2065 return "\n" + markdown.replace(/^[ ]{0,3}>?[ \t]*$/gm, replacement) + "\n";
2070 if(/^(?![ ]{0,3}>)/m.test(chunk.selection)){
2071 command.wrap(chunk, wmd.wmd_env.lineLength - 2);
2072 chunk.selection = chunk.selection.replace(/^/gm, "> ");
2073 replaceBlanksInTags(true);
2074 chunk.addBlankLines();
2077 chunk.selection = chunk.selection.replace(/^[ ]{0,3}> ?/gm, "");
2078 command.unwrap(chunk);
2079 replaceBlanksInTags(false);
2081 if(!/^(\n|^)[ ]{0,3}>/.test(chunk.selection) && chunk.startTag){
2082 chunk.startTag = chunk.startTag.replace(/\n{0,2}$/, "\n\n");
2085 if(!/(\n|^)[ ]{0,3}>.*$/.test(chunk.selection) && chunk.endTag){
2086 chunk.endTag=chunk.endTag.replace(/^\n{0,2}/, "\n\n");
2090 if(!/\n/.test(chunk.selection)){
2091 chunk.selection = chunk.selection.replace(/^(> *)/,
2092 function(wholeMatch, blanks){
2093 chunk.startTag += blanks;
2099 command.doCode = function(chunk, postProcessing, useDefaultText){
2101 var hasTextBefore = /\S[ ]*$/.test(chunk.before);
2102 var hasTextAfter = /^[ ]*\S/.test(chunk.after);
2104 // Use 'four space' markdown if the selection is on its own
2105 // line or is multiline.
2106 if((!hasTextAfter && !hasTextBefore) || /\n/.test(chunk.selection)){
2108 chunk.before = chunk.before.replace(/[ ]{4}$/,
2109 function(totalMatch){
2110 chunk.selection = totalMatch + chunk.selection;
2114 var nLinesBefore = 1;
2115 var nLinesAfter = 1;
2118 if(/\n(\t|[ ]{4,}).*\n$/.test(chunk.before) || chunk.after === ""){
2121 if(/^\n(\t|[ ]{4,})/.test(chunk.after)){
2122 nLinesAfter = 0; // This needs to happen on line 1
2125 chunk.addBlankLines(nLinesBefore, nLinesAfter);
2127 if(!chunk.selection){
2128 chunk.startTag = " ";
2129 chunk.selection = useDefaultText ? "enter code here" : "";
2132 if(/^[ ]{0,3}\S/m.test(chunk.selection)){
2133 chunk.selection = chunk.selection.replace(/^/gm, " ");
2136 chunk.selection = chunk.selection.replace(/^[ ]{4}/gm, "");
2141 // Use backticks (`) to delimit the code block.
2143 chunk.trimWhitespace();
2144 chunk.findTags(/`/, /`/);
2146 if(!chunk.startTag && !chunk.endTag){
2147 chunk.startTag = chunk.endTag="`";
2148 if(!chunk.selection){
2149 chunk.selection = useDefaultText ? "enter code here" : "";
2152 else if(chunk.endTag && !chunk.startTag){
2153 chunk.before += chunk.endTag;
2157 chunk.startTag = chunk.endTag="";
2162 command.doList = function(chunk, postProcessing, isNumberedList, useDefaultText){
2164 // These are identical except at the very beginning and end.
2165 // Should probably use the regex extension function to make this clearer.
2166 var previousItemsRegex = /(\n|^)(([ ]{0,3}([*+-]|\d+[.])[ \t]+.*)(\n.+|\n{2,}([*+-].*|\d+[.])[ \t]+.*|\n{2,}[ \t]+\S.*)*)\n*$/;
2167 var nextItemsRegex = /^\n*(([ ]{0,3}([*+-]|\d+[.])[ \t]+.*)(\n.+|\n{2,}([*+-].*|\d+[.])[ \t]+.*|\n{2,}[ \t]+\S.*)*)\n*/;
2169 // The default bullet is a dash but others are possible.
2170 // This has nothing to do with the particular HTML bullet,
2171 // it's just a markdown bullet.
2174 // The number in a numbered list.
2177 // Get the item prefix - e.g. " 1. " for a numbered list, " - " for a bulleted list.
2178 var getItemPrefix = function(){
2181 prefix = " " + num + ". ";
2185 prefix = " " + bullet + " ";
2190 // Fixes the prefixes of the other list items.
2191 var getPrefixedItem = function(itemText){
2193 // The numbering flag is unset when called by autoindent.
2194 if(isNumberedList === undefined){
2195 isNumberedList = /^\s*\d/.test(itemText);
2198 // Renumber/bullet the list element.
2199 itemText = itemText.replace(/^[ ]{0,3}([*+-]|\d+[.])\s/gm,
2201 return getItemPrefix();
2207 chunk.findTags(/(\n|^)*[ ]{0,3}([*+-]|\d+[.])\s+/, null);
2209 if(chunk.before && !/\n$/.test(chunk.before) && !/^\n/.test(chunk.startTag)){
2210 chunk.before += chunk.startTag;
2211 chunk.startTag = "";
2216 var hasDigits = /\d+[.]/.test(chunk.startTag);
2217 chunk.startTag = "";
2218 chunk.selection = chunk.selection.replace(/\n[ ]{4}/g, "\n");
2219 command.unwrap(chunk);
2220 chunk.addBlankLines();
2223 // Have to renumber the bullet points if this is a numbered list.
2224 chunk.after = chunk.after.replace(nextItemsRegex, getPrefixedItem);
2226 if(isNumberedList == hasDigits){
2231 var nLinesBefore = 1;
2233 chunk.before = chunk.before.replace(previousItemsRegex,
2235 if(/^\s*([*+-])/.test(itemText)){
2238 nLinesBefore = /[^\n]\n\n[^\n]/.test(itemText) ? 1 : 0;
2239 return getPrefixedItem(itemText);
2242 if(!chunk.selection){
2243 chunk.selection = useDefaultText ? "List item" : " ";
2246 var prefix = getItemPrefix();
2248 var nLinesAfter = 1;
2250 chunk.after = chunk.after.replace(nextItemsRegex,
2252 nLinesAfter = /[^\n]\n\n[^\n]/.test(itemText) ? 1 : 0;
2253 return getPrefixedItem(itemText);
2256 chunk.trimWhitespace(true);
2257 chunk.addBlankLines(nLinesBefore, nLinesAfter, true);
2258 chunk.startTag = prefix;
2259 var spaces = prefix.replace(/./g, " ");
2260 command.wrap(chunk, wmd.wmd_env.lineLength - spaces.length);
2261 chunk.selection = chunk.selection.replace(/\n/g, "\n" + spaces);
2265 command.doHeading = function(chunk, postProcessing, useDefaultText){
2267 // Remove leading/trailing whitespace and reduce internal spaces to single spaces.
2268 chunk.selection = chunk.selection.replace(/\s+/g, " ");
2269 chunk.selection = chunk.selection.replace(/(^\s+|\s+$)/g, "");
2271 // If we clicked the button with no selected text, we just
2272 // make a level 2 hash header around some default text.
2273 if(!chunk.selection){
2274 chunk.startTag = "## ";
2275 chunk.selection = "Heading";
2276 chunk.endTag = " ##";
2280 var headerLevel = 0; // The existing header level of the selected text.
2282 // Remove any existing hash heading markdown and save the header level.
2283 chunk.findTags(/#+[ ]*/, /[ ]*#+/);
2284 if(/#+/.test(chunk.startTag)){
2285 headerLevel = re.lastMatch.length;
2287 chunk.startTag = chunk.endTag = "";
2289 // Try to get the current header level by looking for - and = in the line
2290 // below the selection.
2291 chunk.findTags(null, /\s?(-+|=+)/);
2292 if(/=+/.test(chunk.endTag)){
2295 if(/-+/.test(chunk.endTag)){
2299 // Skip to the next line so we can create the header markdown.
2300 chunk.startTag = chunk.endTag = "";
2301 chunk.addBlankLines(1, 1);
2303 // We make a level 2 header if there is no current header.
2304 // If there is a header level, we substract one from the header level.
2305 // If it's already a level 1 header, it's removed.
2306 var headerLevelToCreate = headerLevel == 0 ? 2 : headerLevel - 1;
2308 if(headerLevelToCreate > 0){
2310 // The button only creates level 1 and 2 underline headers.
2311 // Why not have it iterate over hash header levels? Wouldn't that be easier and cleaner?
2312 var headerChar = headerLevelToCreate >= 2 ? "-" : "=";
2313 var len = chunk.selection.length;
2314 if(len > wmd.wmd_env.lineLength){
2315 len = wmd.wmd_env.lineLength;
2317 chunk.endTag = "\n";
2319 chunk.endTag += headerChar;
2324 command.doHorizontalRule = function(chunk, postProcessing, useDefaultText){
2325 chunk.startTag = "----------\n";
2326 chunk.selection = "";
2327 chunk.addBlankLines(2, 1, true);
2332 Attacklab.wmd_env = {};
2333 Attacklab.account_options = {};
2334 Attacklab.wmd_defaults = {version:1, output:"Markdown", lineLength:40, delayLoad:false};
2338 Attacklab.wmd = function()
2340 Attacklab.loadEnv = function()
2342 var mergeEnv = function(env)
2351 Attacklab.wmd_env[key] = env[key];
2355 mergeEnv(Attacklab.wmd_defaults);
2356 mergeEnv(Attacklab.account_options);
2357 mergeEnv(top["wmd_options"]);
2358 Attacklab.full = true;
2360 var defaultButtons = "bold italic link blockquote code image ol ul heading hr";
2361 Attacklab.wmd_env.buttons = Attacklab.wmd_env.buttons || defaultButtons;
2363 Attacklab.loadEnv();
2368 Attacklab.wmdBase();
2369 Attacklab.Util.startEditor();