1 // ----------------------------------------------------------------------------
2 // markItUp! Universal MarkUp Engine, JQuery plugin
4 // Dual licensed under the MIT and GPL licenses.
5 // ----------------------------------------------------------------------------
6 // Copyright (C) 2007-2011 Jay Salvat
7 // http://markitup.jaysalvat.com/
8 // ----------------------------------------------------------------------------
9 // Permission is hereby granted, free of charge, to any person obtaining a copy
10 // of this software and associated documentation files (the "Software"), to deal
11 // in the Software without restriction, including without limitation the rights
12 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13 // copies of the Software, and to permit persons to whom the Software is
14 // furnished to do so, subject to the following conditions:
16 // The above copyright notice and this permission notice shall be included in
17 // all copies or substantial portions of the Software.
19 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
26 // ----------------------------------------------------------------------------
28 Modified on 4-26-12 by SugarCRM
29 get and insert functions modifed for better IE8 compatibility.
30 Various global varaible cleanups
33 $.fn.markItUp = function(settings, extraSettings) {
34 var options, ctrlKey, shiftKey, altKey, selection, caretPosition;
35 ctrlKey = shiftKey = altKey = false;
40 previewInWindow: '', // 'width=800, height=600, resizable=yes, scrollbars=yes'
41 previewAutoRefresh: true,
42 previewPosition: 'after',
43 previewTemplatePath: '~/templates/preview.html',
45 previewParserPath: '',
46 previewParserVar: 'data',
54 markupSet: [ { /* set */ } ]
56 $.extend(options, settings, extraSettings);
58 // compute markItUp! path
60 $('script').each(function(a, tag) {
61 var miuScript = $(tag).get(0).src.match(/(.*)jquery\.markitup(\.pack)?\.js$/);
62 if (miuScript !== null) {
63 options.root = miuScript[1];
68 return this.each(function() {
69 var $$, textarea, levels, scrollPosition, caretPosition, caretOffset,
70 clicked, hash, header, footer, previewWindow, template, iFrame, abort;
75 scrollPosition = caretPosition = 0;
78 options.previewParserPath = localize(options.previewParserPath);
79 options.previewTemplatePath = localize(options.previewTemplatePath);
81 // apply the computed path to ~/
82 function localize(data, inText) {
84 return data.replace(/("|')~\//g, "$1"+options.root);
86 return data.replace(/^~\//, options.root);
89 // init and build editor
91 id = ''; nameSpace = '';
93 id = 'id="'+options.id+'"';
94 } else if ($$.attr("id")) {
95 id = 'id="markItUp'+($$.attr("id").substr(0, 1).toUpperCase())+($$.attr("id").substr(1))+'"';
98 if (options.nameSpace) {
99 nameSpace = 'class="'+options.nameSpace+'"';
101 $$.wrap('<div '+nameSpace+'></div>');
102 $$.wrap('<div '+id+' class="markItUp"></div>');
103 $$.wrap('<div class="markItUpContainer"></div>');
104 $$.addClass("markItUpEditor");
106 // add the header before the textarea
107 header = $('<div class="markItUpHeader"></div>').insertBefore($$);
108 $(dropMenus(options.markupSet)).appendTo(header);
110 // add the footer after the textarea
111 footer = $('<div class="markItUpFooter"></div>').insertAfter($$);
113 // add the resize handle after textarea
114 if (options.resizeHandle === true && $.browser.safari !== true) {
115 var resizeHandle = $('<div class="markItUpResizeHandle"></div>')
117 .bind("mousedown", function(e) {
118 var h = $$.height(), y = e.clientY, mouseMove, mouseUp;
119 mouseMove = function(e) {
120 $$.css("height", Math.max(20, e.clientY+h-y)+"px");
123 mouseUp = function(e) {
124 $("html").unbind("mousemove", mouseMove).unbind("mouseup", mouseUp);
127 $("html").bind("mousemove", mouseMove).bind("mouseup", mouseUp);
129 footer.append(resizeHandle);
133 $$.keydown(keyPressed).keyup(keyPressed);
135 // bind an event to catch external calls
136 $$.bind("insertion", function(e, settings) {
137 if (settings.target !== false) {
140 if (textarea === $.markItUp.focused) {
145 // remember the last focus
146 $$.focus(function() {
147 $.markItUp.focused = this;
151 // recursively build header with dropMenus from markupset
152 function dropMenus(markupSet) {
153 var ul = $('<ul></ul>'), i = 0;
154 $('li:hover > ul', ul).css('display', 'block');
155 $.each(markupSet, function() {
156 var button = this, t = '', title, li, j, key;
157 title = (button.key) ? (button.name||'')+' [Ctrl+'+button.key+']' : (button.name||'');
158 key = (button.key) ? 'accesskey="'+button.key+'"' : '';
159 if (button.separator) {
160 li = $('<li class="markItUpSeparator">'+(button.separator||'')+'</li>').appendTo(ul);
163 for (j = levels.length -1; j >= 0; j--) {
166 li = $('<li class="markItUpButton markItUpButton'+t+(i)+' '+(button.className||'')+'"><a href="" '+key+' title="'+title+'">'+(button.name||'')+'</a></li>')
167 .bind("contextmenu", function() { // prevent contextmenu on mac and allow ctrl+click
169 }).click(function() {
171 }).bind("focusin", function(){
173 }).mouseup(function() {
177 setTimeout(function() { markup(button) },1);
179 }).hover(function() {
180 $('> ul', this).show();
181 $(document).one('click', function() { // close dropmenu if click outside
182 $('ul ul', header).hide();
186 $('> ul', this).hide();
189 if (button.dropMenu) {
191 $(li).addClass('markItUpDropMenu').append(dropMenus(button.dropMenu));
200 function magicMarkups(string) {
202 string = string.toString();
203 string = string.replace(/\(\!\(([\s\S]*?)\)\!\)/g,
205 var b = a.split('|!|');
206 if (altKey === true) {
207 return (b[1] !== undefined) ? b[1] : b[0];
209 return (b[1] === undefined) ? "" : b[0];
213 // [![prompt]!], [![prompt:!:value]!]
214 string = string.replace(/\[\!\[([\s\S]*?)\]\!\]/g,
216 var b = a.split(':!:');
217 if (abort === true) {
220 value = prompt(b[0], (b[1]) ? b[1] : '');
221 if (value === null) {
233 function prepare(action) {
234 if ($.isFunction(action)) {
235 action = action(hash);
237 return magicMarkups(action);
240 // build block to insert
241 function build(string) {
243 var openWith = prepare(clicked.openWith);
244 var placeHolder = prepare(clicked.placeHolder);
245 var replaceWith = prepare(clicked.replaceWith);
246 var closeWith = prepare(clicked.closeWith);
247 var openBlockWith = prepare(clicked.openBlockWith);
248 var closeBlockWith = prepare(clicked.closeBlockWith);
249 var multiline = clicked.multiline;
251 if (replaceWith !== "") {
252 block = openWith + replaceWith + closeWith;
253 } else if (selection === '' && placeHolder !== '') {
254 block = openWith + placeHolder + closeWith;
256 string = string || selection;
258 var lines = selection.split(/\r?\n/), blocks = [];
260 for (var l=0; l < lines.length; l++) {
263 if (trailingSpaces = line.match(/ *$/)) {
264 blocks.push(openWith + line.replace(/ *$/g, '') + closeWith + trailingSpaces);
266 blocks.push(openWith + line + closeWith);
270 block = blocks.join("\n");
273 block = openBlockWith + block + closeBlockWith;
275 return { block:block,
277 replaceWith:replaceWith,
278 placeHolder:placeHolder,
283 // define markup to insert
284 function markup(button) {
285 var len, j, n, i, lines, string, start;
286 hash = clicked = button;
288 $.extend(hash, { line:"",
291 selection:(selection||''),
292 caretPosition:caretPosition,
298 // callbacks before insertion
299 prepare(options.beforeInsert);
300 prepare(clicked.beforeInsert);
301 if ((ctrlKey === true && shiftKey === true) || button.multiline === true) {
302 prepare(clicked.beforeMultiInsert);
304 $.extend(hash, { line:1 });
306 if ((ctrlKey === true && shiftKey === true)) {
307 lines = selection.split(/\r?\n/);
308 for (j = 0, n = lines.length, i = 0; i < n; i++) {
309 if ($.trim(lines[i]) !== '') {
310 $.extend(hash, { line:++j, selection:lines[i] } );
311 lines[i] = build(lines[i]).block;
316 string = { block:lines.join('\n')};
317 start = caretPosition;
318 len = string.block.length + (($.browser.opera) ? n-1 : 0);
319 } else if (ctrlKey === true) {
320 string = build(selection);
321 start = caretPosition + string.openWith.length;
322 len = string.block.length - string.openWith.length - string.closeWith.length;
323 len = len - (string.block.match(/ $/) ? 1 : 0);
324 len -= fixIeBug(string.block);
325 } else if (shiftKey === true) {
326 string = build(selection);
327 start = caretPosition;
328 len = string.block.length;
329 len -= fixIeBug(string.block);
331 string = build(selection);
332 start = caretPosition + string.block.length ;
334 start -= fixIeBug(string.block);
336 if ((selection === '' && string.replaceWith === '')) {
337 caretOffset += fixOperaBug(string.block);
339 start = caretPosition + string.openWith.length;
340 len = string.block.length - string.openWith.length - string.closeWith.length;
342 caretOffset = $$.val().substring(caretPosition, $$.val().length).length;
343 caretOffset -= fixOperaBug($$.val().substring(0, caretPosition));
345 $.extend(hash, { caretPosition:caretPosition, scrollPosition:scrollPosition } );
347 if (string.block !== selection && abort === false) {
348 insert(string.block);
355 $.extend(hash, { line:'', selection:selection });
357 // callbacks after insertion
358 if ((ctrlKey === true && shiftKey === true) || button.multiline === true) {
359 prepare(clicked.afterMultiInsert);
361 prepare(clicked.afterInsert);
362 prepare(options.afterInsert);
364 // refresh preview if opened
365 if (previewWindow && options.previewAutoRefresh) {
370 shiftKey = altKey = ctrlKey = abort = false;
373 // Substract linefeed in Opera
374 function fixOperaBug(string) {
375 if ($.browser.opera) {
376 return string.length - string.replace(/\n*/g, '').length;
380 // Substract linefeed in IE
381 function fixIeBug(string) {
382 if ($.browser.msie) {
383 return string.length - string.replace(/\r*/g, '').length;
389 function insert(block) {
390 textarea.value = textarea.value.substring(0, caretPosition) + block
391 + textarea.value.substring(caretPosition + selection.length, textarea.value.length);
395 function set(start, len) {
397 if (textarea.createTextRange){
398 // quick fix to make it work on Opera 9.5
399 if ($.browser.opera && $.browser.version >= 9.5 && len == 0) {
402 range = textarea.createTextRange();
403 range.collapse(true);
404 range.moveStart('character', start);
405 range.moveEnd('character', len);
407 } else if (textarea.setSelectionRange ){
408 textarea.setSelectionRange(start, start + len);
410 textarea.scrollTop = scrollPosition;
418 scrollPosition = textarea.scrollTop;
419 if (document.selection) {
420 selection = document.selection.createRange().text;
421 if ($.browser.msie) { // ie
422 var range = document.selection.createRange(),
423 rangeCopy = range.duplicate();
424 //If nothing is selected, we have to use a different technique to find the caret position
425 if (document.selection.type =="None")
428 range = textarea.createTextRange();
429 rangeCopy = range.duplicate();
430 range.moveToBookmark(sel.getBookmark());
431 rangeCopy.setEndPoint("EndToStart", range);
432 if (rangeCopy.parentElement() == textarea)
433 caretPosition = rangeCopy.text.length;
436 rangeCopy.moveToElementText(textarea);
439 while(rangeCopy.inRange(range, inrange)) {
440 rangeCopy.moveStart('character');
445 caretPosition = textarea.selectionStart;
447 } else { // gecko & webkit
448 caretPosition = textarea.selectionStart;
450 selection = textarea.value.substring(caretPosition, textarea.selectionEnd);
455 // open preview window
457 if (!previewWindow || previewWindow.closed) {
458 if (options.previewInWindow) {
459 previewWindow = window.open('', 'preview', options.previewInWindow);
460 $(window).unload(function() {
461 previewWindow.close();
464 iFrame = $('<iframe class="markItUpPreviewFrame"></iframe>');
465 if (options.previewPosition == 'after') {
466 iFrame.insertAfter(footer);
468 iFrame.insertBefore(header);
470 previewWindow = iFrame[iFrame.length - 1].contentWindow || frame[iFrame.length - 1];
472 } else if (altKey === true) {
476 previewWindow.close();
478 previewWindow = iFrame = false;
480 if (!options.previewAutoRefresh) {
483 if (options.previewInWindow) {
484 previewWindow.focus();
488 // refresh Preview window
489 function refreshPreview() {
493 function renderPreview() {
495 if (options.previewParser && typeof options.previewParser === 'function') {
496 var data = options.previewParser( $$.val() );
497 writeInPreview( localize(data, 1) );
498 } else if (options.previewParserPath !== '') {
503 url: options.previewParserPath,
504 data: options.previewParserVar+'='+encodeURIComponent($$.val()),
505 success: function(data) {
506 writeInPreview( localize(data, 1) );
512 url: options.previewTemplatePath,
515 success: function(data) {
516 writeInPreview( localize(data, 1).replace(/<!-- content -->/g, $$.val()) );
524 function writeInPreview(data) {
525 if (previewWindow.document) {
527 sp = previewWindow.document.documentElement.scrollTop
531 previewWindow.document.open();
532 previewWindow.document.write(data);
533 previewWindow.document.close();
534 previewWindow.document.documentElement.scrollTop = sp;
539 function keyPressed(e) {
540 shiftKey = e.shiftKey;
542 ctrlKey = (!(e.altKey && e.ctrlKey)) ? (e.ctrlKey || e.metaKey) : false;
544 if (e.type === 'keydown') {
545 if (ctrlKey === true) {
546 li = $('a[accesskey="'+String.fromCharCode(e.keyCode)+'"]', header).parent('li');
547 if (li.length !== 0) {
549 setTimeout(function() {
550 li.triggerHandler('mouseup');
555 if (e.keyCode === 13 || e.keyCode === 10) { // Enter key
556 if (ctrlKey === true) { // Enter + Ctrl
558 markup(options.onCtrlEnter);
559 return options.onCtrlEnter.keepDefault;
560 } else if (shiftKey === true) { // Enter + Shift
562 markup(options.onShiftEnter);
563 return options.onShiftEnter.keepDefault;
564 } else { // only Enter
565 markup(options.onEnter);
566 return options.onEnter.keepDefault;
569 if (e.keyCode === 9) { // Tab key
570 if (shiftKey == true || ctrlKey == true || altKey == true) {
573 if (caretOffset !== -1) {
575 caretOffset = $$.val().length - caretOffset;
580 markup(options.onTab);
581 return options.onTab.keepDefault;
591 $.fn.markItUpRemove = function() {
592 return this.each(function() {
593 var $$ = $(this).unbind().removeClass('markItUpEditor');
594 $$.parent('div').parent('div.markItUp').parent('div').replaceWith($$);
599 $.markItUp = function(settings) {
600 var options = { target:false };
601 $.extend(options, settings);
602 if (options.target) {
603 return $(options.target).each(function() {
605 $(this).trigger('insertion', [options]);
608 $('textarea').trigger('insertion', [options]);