1 // ----------------------------------------------------------------------------
2 // markItUp! Universal MarkUp Engine, JQuery plugin
4 // Dual licensed under the MIT and GPL licenses.
5 // ----------------------------------------------------------------------------
6 // Copyright (C) 2007-2010 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 $.fn.markItUp = function(settings, extraSettings) {
29 var options, ctrlKey, shiftKey, altKey;
30 ctrlKey = shiftKey = altKey = false;
35 previewInWindow: '', // 'width=800, height=600, resizable=yes, scrollbars=yes'
36 previewAutoRefresh: true,
37 previewPosition: 'after',
38 previewTemplatePath: '~/templates/preview.html',
39 previewParserPath: '',
40 previewParserVar: 'data',
48 markupSet: [ { /* set */ } ]
50 $.extend(options, settings, extraSettings);
52 // compute markItUp! path
54 $('script').each(function(a, tag) {
55 miuScript = $(tag).get(0).src.match(/(.*)jquery\.markitup(\.pack)?\.js$/);
56 if (miuScript !== null) {
57 options.root = miuScript[1];
62 return this.each(function() {
63 var $$, textarea, levels, scrollPosition, caretPosition, caretOffset,
64 clicked, hash, header, footer, previewWindow, template, iFrame, abort;
69 scrollPosition = caretPosition = 0;
72 options.previewParserPath = localize(options.previewParserPath);
73 options.previewTemplatePath = localize(options.previewTemplatePath);
75 // apply the computed path to ~/
76 function localize(data, inText) {
78 return data.replace(/("|')~\//g, "$1"+options.root);
80 return data.replace(/^~\//, options.root);
83 // init and build editor
85 id = ''; nameSpace = '';
87 id = 'id="'+options.id+'"';
88 } else if ($$.attr("id")) {
89 id = 'id="markItUp'+($$.attr("id").substr(0, 1).toUpperCase())+($$.attr("id").substr(1))+'"';
92 if (options.nameSpace) {
93 nameSpace = 'class="'+options.nameSpace+'"';
95 $$.wrap('<div '+nameSpace+'></div>');
96 $$.wrap('<div '+id+' class="markItUp"></div>');
97 $$.wrap('<div class="markItUpContainer"></div>');
98 $$.addClass("markItUpEditor");
100 // add the header before the textarea
101 header = $('<div class="markItUpHeader"></div>').insertBefore($$);
102 $(dropMenus(options.markupSet)).appendTo(header);
104 // add the footer after the textarea
105 footer = $('<div class="markItUpFooter"></div>').insertAfter($$);
107 // add the resize handle after textarea
108 if (options.resizeHandle === true && $.browser.safari !== true) {
109 resizeHandle = $('<div class="markItUpResizeHandle"></div>')
111 .bind("mousedown", function(e) {
112 var h = $$.height(), y = e.clientY, mouseMove, mouseUp;
113 mouseMove = function(e) {
114 $$.css("height", Math.max(20, e.clientY+h-y)+"px");
117 mouseUp = function(e) {
118 $("html").unbind("mousemove", mouseMove).unbind("mouseup", mouseUp);
121 $("html").bind("mousemove", mouseMove).bind("mouseup", mouseUp);
123 footer.append(resizeHandle);
127 $$.keydown(keyPressed).keyup(keyPressed);
129 // bind an event to catch external calls
130 $$.bind("insertion", function(e, settings) {
131 if (settings.target !== false) {
134 if (textarea === $.markItUp.focused) {
139 // remember the last focus
140 $$.focus(function() {
141 $.markItUp.focused = this;
145 // recursively build header with dropMenus from markupset
146 function dropMenus(markupSet) {
147 var ul = $('<ul></ul>'), i = 0;
148 $('li:hover > ul', ul).css('display', 'block');
149 $.each(markupSet, function() {
150 var button = this, t = '', title, li, j;
151 title = (button.key) ? (button.name||'')+' [Ctrl+'+button.key+']' : (button.name||'');
152 key = (button.key) ? 'accesskey="'+button.key+'"' : '';
153 if (button.separator) {
154 li = $('<li class="markItUpSeparator">'+(button.separator||'')+'</li>').appendTo(ul);
157 for (j = levels.length -1; j >= 0; j--) {
160 li = $('<li class="markItUpButton markItUpButton'+t+(i)+' '+(button.className||'')+'"><a href="" '+key+' title="'+title+'">'+(button.name||'')+'</a></li>')
161 .bind("contextmenu", function() { // prevent contextmenu on mac and allow ctrl+click
163 }).click(function() {
165 }).mousedown(function() {
169 setTimeout(function() { markup(button) },1);
171 }).hover(function() {
172 $('> ul', this).show();
173 $(document).one('click', function() { // close dropmenu if click outside
174 $('ul ul', header).hide();
178 $('> ul', this).hide();
181 if (button.dropMenu) {
183 $(li).addClass('markItUpDropMenu').append(dropMenus(button.dropMenu));
192 function magicMarkups(string) {
194 string = string.toString();
195 string = string.replace(/\(\!\(([\s\S]*?)\)\!\)/g,
197 var b = a.split('|!|');
198 if (altKey === true) {
199 return (b[1] !== undefined) ? b[1] : b[0];
201 return (b[1] === undefined) ? "" : b[0];
205 // [![prompt]!], [![prompt:!:value]!]
206 string = string.replace(/\[\!\[([\s\S]*?)\]\!\]/g,
208 var b = a.split(':!:');
209 if (abort === true) {
212 value = prompt(b[0], (b[1]) ? b[1] : '');
213 if (value === null) {
225 function prepare(action) {
226 if ($.isFunction(action)) {
227 action = action(hash);
229 return magicMarkups(action);
232 // build block to insert
233 function build(string) {
234 openWith = prepare(clicked.openWith);
235 placeHolder = prepare(clicked.placeHolder);
236 replaceWith = prepare(clicked.replaceWith);
237 closeWith = prepare(clicked.closeWith);
238 if (replaceWith !== "") {
239 block = openWith + replaceWith + closeWith;
240 } else if (selection === '' && placeHolder !== '') {
241 block = openWith + placeHolder + closeWith;
243 block = openWith + (string||selection) + closeWith;
245 return { block:block,
247 replaceWith:replaceWith,
248 placeHolder:placeHolder,
253 // define markup to insert
254 function markup(button) {
256 hash = clicked = button;
259 $.extend(hash, { line:"",
262 selection:(selection||''),
263 caretPosition:caretPosition,
269 // callbacks before insertion
270 prepare(options.beforeInsert);
271 prepare(clicked.beforeInsert);
272 if (ctrlKey === true && shiftKey === true) {
273 prepare(clicked.beforeMultiInsert);
275 $.extend(hash, { line:1 });
277 if (ctrlKey === true && shiftKey === true) {
278 lines = selection.split(/\r?\n/);
279 for (j = 0, n = lines.length, i = 0; i < n; i++) {
280 if ($.trim(lines[i]) !== '') {
281 $.extend(hash, { line:++j, selection:lines[i] } );
282 lines[i] = build(lines[i]).block;
287 string = { block:lines.join('\n')};
288 start = caretPosition;
289 len = string.block.length + (($.browser.opera) ? n : 0);
290 } else if (ctrlKey === true) {
291 string = build(selection);
292 start = caretPosition + string.openWith.length;
293 len = string.block.length - string.openWith.length - string.closeWith.length;
294 len -= fixIeBug(string.block);
295 } else if (shiftKey === true) {
296 string = build(selection);
297 start = caretPosition;
298 len = string.block.length;
299 len -= fixIeBug(string.block);
301 string = build(selection);
302 start = caretPosition + string.block.length ;
304 start -= fixIeBug(string.block);
306 if ((selection === '' && string.replaceWith === '')) {
307 caretOffset += fixOperaBug(string.block);
309 start = caretPosition + string.openWith.length;
310 len = string.block.length - string.openWith.length - string.closeWith.length;
312 caretOffset = $$.val().substring(caretPosition, $$.val().length).length;
313 caretOffset -= fixOperaBug($$.val().substring(0, caretPosition));
315 $.extend(hash, { caretPosition:caretPosition, scrollPosition:scrollPosition } );
317 if (string.block !== selection && abort === false) {
318 insert(string.block);
325 $.extend(hash, { line:'', selection:selection });
327 // callbacks after insertion
328 if (ctrlKey === true && shiftKey === true) {
329 prepare(clicked.afterMultiInsert);
331 prepare(clicked.afterInsert);
332 prepare(options.afterInsert);
334 // refresh preview if opened
335 if (previewWindow && options.previewAutoRefresh) {
340 shiftKey = altKey = ctrlKey = abort = false;
343 // Substract linefeed in Opera
344 function fixOperaBug(string) {
345 if ($.browser.opera) {
346 return string.length - string.replace(/\n*/g, '').length;
350 // Substract linefeed in IE
351 function fixIeBug(string) {
352 if ($.browser.msie) {
353 return string.length - string.replace(/\r*/g, '').length;
359 function insert(block) {
360 if (document.selection) {
361 var newSelection = document.selection.createRange();
362 newSelection.text = block;
364 $$.val($$.val().substring(0, caretPosition) + block + $$.val().substring(caretPosition + selection.length, $$.val().length));
369 function set(start, len) {
370 if (textarea.createTextRange){
371 // quick fix to make it work on Opera 9.5
372 if ($.browser.opera && $.browser.version >= 9.5 && len == 0) {
375 range = textarea.createTextRange();
376 range.collapse(true);
377 range.moveStart('character', start);
378 range.moveEnd('character', len);
380 } else if (textarea.setSelectionRange ){
381 textarea.setSelectionRange(start, start + len);
383 textarea.scrollTop = scrollPosition;
391 scrollPosition = textarea.scrollTop;
392 if (document.selection) {
393 selection = document.selection.createRange().text;
394 if ($.browser.msie) { // ie
395 var range = document.selection.createRange(), rangeCopy = range.duplicate();
396 rangeCopy.moveToElementText(textarea);
398 while(rangeCopy.inRange(range)) { // fix most of the ie bugs with linefeeds...
399 rangeCopy.moveStart('character');
403 caretPosition = textarea.selectionStart;
405 } else { // gecko & webkit
406 caretPosition = textarea.selectionStart;
407 selection = $$.val().substring(caretPosition, textarea.selectionEnd);
412 // open preview window
414 if (!previewWindow || previewWindow.closed) {
415 if (options.previewInWindow) {
416 previewWindow = window.open('', 'preview', options.previewInWindow);
418 iFrame = $('<iframe class="markItUpPreviewFrame"></iframe>');
419 if (options.previewPosition == 'after') {
420 iFrame.insertAfter(footer);
422 iFrame.insertBefore(header);
424 previewWindow = iFrame[iFrame.length - 1].contentWindow || frame[iFrame.length - 1];
426 } else if (altKey === true) {
427 // Thx Stephen M. Redd for the IE8 fix
431 previewWindow.close();
433 previewWindow = iFrame = false;
435 if (!options.previewAutoRefresh) {
440 // refresh Preview window
441 function refreshPreview() {
445 function renderPreview() {
447 if (options.previewParserPath !== '') {
450 url: options.previewParserPath,
451 data: options.previewParserVar+'='+encodeURIComponent($$.val()),
452 success: function(data) {
453 writeInPreview( localize(data, 1) );
459 url: options.previewTemplatePath,
460 success: function(data) {
461 writeInPreview( localize(data, 1).replace(/<!-- content -->/g, $$.val()) );
469 function writeInPreview(data) {
470 if (previewWindow.document) {
472 sp = previewWindow.document.documentElement.scrollTop
476 previewWindow.document.open();
477 previewWindow.document.write(data);
478 previewWindow.document.close();
479 previewWindow.document.documentElement.scrollTop = sp;
481 if (options.previewInWindow) {
482 previewWindow.focus();
487 function keyPressed(e) {
488 shiftKey = e.shiftKey;
490 ctrlKey = (!(e.altKey && e.ctrlKey)) ? e.ctrlKey : false;
492 if (e.type === 'keydown') {
493 if (ctrlKey === true) {
494 li = $("a[accesskey="+String.fromCharCode(e.keyCode)+"]", header).parent('li');
495 if (li.length !== 0) {
497 setTimeout(function() {
498 li.triggerHandler('mousedown');
503 if (e.keyCode === 13 || e.keyCode === 10) { // Enter key
504 if (ctrlKey === true) { // Enter + Ctrl
506 markup(options.onCtrlEnter);
507 return options.onCtrlEnter.keepDefault;
508 } else if (shiftKey === true) { // Enter + Shift
510 markup(options.onShiftEnter);
511 return options.onShiftEnter.keepDefault;
512 } else { // only Enter
513 markup(options.onEnter);
514 return options.onEnter.keepDefault;
517 if (e.keyCode === 9) { // Tab key
518 if (shiftKey == true || ctrlKey == true || altKey == true) { // Thx Dr Floob.
521 if (caretOffset !== -1) {
523 caretOffset = $$.val().length - caretOffset;
528 markup(options.onTab);
529 return options.onTab.keepDefault;
539 $.fn.markItUpRemove = function() {
540 return this.each(function() {
541 var $$ = $(this).unbind().removeClass('markItUpEditor');
542 $$.parent('div').parent('div.markItUp').parent('div').replaceWith($$);
547 $.markItUp = function(settings) {
548 var options = { target:false };
549 $.extend(options, settings);
550 if (options.target) {
551 return $(options.target).each(function() {
553 $(this).trigger('insertion', [options]);
556 $('textarea').trigger('insertion', [options]);