4 * Copyright 2009, Moxiecode Systems AB
5 * Released under LGPL License.
7 * License: http://tinymce.moxiecode.com/license
8 * Contributing: http://tinymce.moxiecode.com/contributing
12 var each = tinymce.each,
14 paste_auto_cleanup_on_paste : true,
15 paste_enable_default_filters : true,
16 paste_block_drop : false,
17 paste_retain_style_properties : "none",
18 paste_strip_class_attributes : "mso",
19 paste_remove_spans : false,
20 paste_remove_styles : false,
21 paste_remove_styles_if_webkit : true,
22 paste_convert_middot_lists : true,
23 paste_convert_headers_to_strong : false,
24 paste_dialog_width : "450",
25 paste_dialog_height : "400",
26 paste_text_use_dialog : false,
27 paste_text_sticky : false,
28 paste_text_sticky_default : false,
29 paste_text_notifyalways : false,
30 paste_text_linebreaktype : "p",
31 paste_text_replacements : [
33 [/[\x93\x94\u201c\u201d]/g, '"'],
34 [/[\x60\x91\x92\u2018\u2019]/g, "'"]
38 function getParam(ed, name) {
39 return ed.getParam(name, defs[name]);
42 tinymce.create('tinymce.plugins.PastePlugin', {
43 init : function(ed, url) {
49 // Setup plugin events
50 t.onPreProcess = new tinymce.util.Dispatcher(t);
51 t.onPostProcess = new tinymce.util.Dispatcher(t);
53 // Register default handlers
54 t.onPreProcess.add(t._preProcess);
55 t.onPostProcess.add(t._postProcess);
57 // Register optional preprocess handler
58 t.onPreProcess.add(function(pl, o) {
59 ed.execCallback('paste_preprocess', pl, o);
62 // Register optional postprocess
63 t.onPostProcess.add(function(pl, o) {
64 ed.execCallback('paste_postprocess', pl, o);
67 ed.onKeyDown.addToTop(function(ed, e) {
68 // Block ctrl+v from adding an undo level since the default logic in tinymce.Editor will add that
69 if (((tinymce.isMac ? e.metaKey : e.ctrlKey) && e.keyCode == 86) || (e.shiftKey && e.keyCode == 45))
70 return false; // Stop other listeners
73 // Initialize plain text flag
74 ed.pasteAsPlainText = getParam(ed, 'paste_text_sticky_default');
76 // This function executes the process handlers and inserts the contents
77 // force_rich overrides plain text mode set by user, important for pasting with execCommand
78 function process(o, force_rich) {
79 var dom = ed.dom, rng, nodes;
81 // Execute pre process handlers
82 t.onPreProcess.dispatch(t, o);
84 // Create DOM structure
85 o.node = dom.create('div', 0, o.content);
87 // If pasting inside the same element and the contents is only one block
88 // remove the block and keep the text since Firefox will copy parts of pre and h1-h6 as a pre element
89 if (tinymce.isGecko) {
90 rng = ed.selection.getRng(true);
91 if (rng.startContainer == rng.endContainer && rng.startContainer.nodeType == 3) {
92 nodes = dom.select('p,h1,h2,h3,h4,h5,h6,pre', o.node);
94 // Is only one block node and it doesn't contain word stuff
95 if (nodes.length == 1 && o.content.indexOf('__MCE_ITEM__') === -1)
96 dom.remove(nodes.reverse(), true);
100 // Execute post process handlers
101 t.onPostProcess.dispatch(t, o);
104 o.content = ed.serializer.serialize(o.node, {getInner : 1});
106 // Plain text option active?
107 if ((!force_rich) && (ed.pasteAsPlainText)) {
108 t._insertPlainText(ed, dom, o.content);
110 if (!getParam(ed, "paste_text_sticky")) {
111 ed.pasteAsPlainText = false;
112 ed.controlManager.setActive("pastetext", false);
115 t._insert(o.content);
119 // Add command for external usage
120 ed.addCommand('mceInsertClipboardContent', function(u, o) {
124 if (!getParam(ed, "paste_text_use_dialog")) {
125 ed.addCommand('mcePasteText', function(u, v) {
126 var cookie = tinymce.util.Cookie;
128 ed.pasteAsPlainText = !ed.pasteAsPlainText;
129 ed.controlManager.setActive('pastetext', ed.pasteAsPlainText);
131 if ((ed.pasteAsPlainText) && (!cookie.get("tinymcePasteText"))) {
132 if (getParam(ed, "paste_text_sticky")) {
133 ed.windowManager.alert(ed.translate('paste.plaintext_mode_sticky'));
135 ed.windowManager.alert(ed.translate('paste.plaintext_mode_sticky'));
138 if (!getParam(ed, "paste_text_notifyalways")) {
139 cookie.set("tinymcePasteText", "1", new Date(new Date().getFullYear() + 1, 12, 31))
145 ed.addButton('pastetext', {title: 'paste.paste_text_desc', cmd: 'mcePasteText'});
146 ed.addButton('selectall', {title: 'paste.selectall_desc', cmd: 'selectall'});
148 // This function grabs the contents from the clipboard by adding a
149 // hidden div and placing the caret inside it and after the browser paste
150 // is done it grabs that contents and processes that
151 function grabContent(e) {
152 var n, or, rng, oldRng, sel = ed.selection, dom = ed.dom, body = ed.getBody(), posY, textContent;
154 // Check if browser supports direct plaintext access
155 if (e.clipboardData || dom.doc.dataTransfer) {
156 textContent = (e.clipboardData || dom.doc.dataTransfer).getData('Text');
158 if (ed.pasteAsPlainText) {
160 process({content : textContent.replace(/\r?\n/g, '<br />')});
165 if (dom.get('_mcePaste'))
168 // Create container to paste into
169 n = dom.add(body, 'div', {id : '_mcePaste', 'class' : 'mcePaste', 'data-mce-bogus' : '1'}, '\uFEFF\uFEFF');
171 // If contentEditable mode we need to find out the position of the closest element
172 if (body != ed.getDoc().body)
173 posY = dom.getPos(ed.selection.getStart(), body).y;
175 posY = body.scrollTop + dom.getViewPort().y;
177 // Styles needs to be applied after the element is added to the document since WebKit will otherwise remove all styles
179 position : 'absolute',
188 // Store away the old range
189 oldRng = sel.getRng();
191 // Select the container
192 rng = dom.doc.body.createTextRange();
193 rng.moveToElementText(n);
194 rng.execCommand('Paste');
199 // Check if the contents was changed, if it wasn't then clipboard extraction failed probably due
200 // to IE security settings so we pass the junk though better than nothing right
201 if (n.innerHTML === '\uFEFF\uFEFF') {
202 ed.execCommand('mcePasteWord');
207 // Restore the old range and clear the contents before pasting
211 // For some odd reason we need to detach the the mceInsertContent call from the paste event
212 // It's like IE has a reference to the parent element that you paste in and the selection gets messed up
213 // when it tries to restore the selection
214 setTimeout(function() {
216 process({content : n.innerHTML});
219 // Block the real paste event
220 return tinymce.dom.Event.cancel(e);
226 // Block mousedown and click to prevent selection change
227 dom.bind(ed.getDoc(), 'mousedown', block);
228 dom.bind(ed.getDoc(), 'keydown', block);
230 or = ed.selection.getRng();
232 // Move select contents inside DIV
234 rng = ed.getDoc().createRange();
239 // Wait a while and grab the pasted contents
240 window.setTimeout(function() {
243 // Paste divs duplicated in paste divs seems to happen when you paste plain text so lets first look for that broken behavior in WebKit
244 if (!dom.select('div.mcePaste > div.mcePaste').length) {
245 nl = dom.select('div.mcePaste');
247 // WebKit will split the div into multiple ones so this will loop through then all and join them to get the whole HTML string
248 each(nl, function(n) {
249 var child = n.firstChild;
251 // WebKit inserts a DIV container with lots of odd styles
252 if (child && child.nodeName == 'DIV' && child.style.marginTop && child.style.backgroundColor) {
253 dom.remove(child, 1);
256 // Remove apply style spans
257 each(dom.select('span.Apple-style-span', n), function(n) {
261 // Remove bogus br elements
262 each(dom.select('br[data-mce-bogus]', n), function(n) {
266 // WebKit will make a copy of the DIV for each line of plain text pasted and insert them into the DIV
267 if (n.parentNode.className != 'mcePaste')
271 // Found WebKit weirdness so force the content into plain text mode
272 h = '<pre>' + dom.encode(textContent).replace(/\r?\n/g, '<br />') + '</pre>';
276 each(dom.select('div.mcePaste'), function(n) {
280 // Restore the old selection
284 process({content : h});
286 // Unblock events ones we got the contents
287 dom.unbind(ed.getDoc(), 'mousedown', block);
288 dom.unbind(ed.getDoc(), 'keydown', block);
293 // Check if we should use the new auto process method
294 if (getParam(ed, "paste_auto_cleanup_on_paste")) {
295 // Is it's Opera or older FF use key handler
296 if (tinymce.isOpera || /Firefox\/2/.test(navigator.userAgent)) {
297 ed.onKeyDown.addToTop(function(ed, e) {
298 if (((tinymce.isMac ? e.metaKey : e.ctrlKey) && e.keyCode == 86) || (e.shiftKey && e.keyCode == 45))
302 // Grab contents on paste event on Gecko and WebKit
303 ed.onPaste.addToTop(function(ed, e) {
304 return grabContent(e);
309 ed.onInit.add(function() {
310 ed.controlManager.setActive("pastetext", ed.pasteAsPlainText);
312 // Block all drag/drop events
313 if (getParam(ed, "paste_block_drop")) {
314 ed.dom.bind(ed.getBody(), ['dragend', 'dragover', 'draggesture', 'dragdrop', 'drop', 'drag'], function(e) {
323 // Add legacy support
327 getInfo : function() {
329 longname : 'Paste text/word',
330 author : 'Moxiecode Systems AB',
331 authorurl : 'http://tinymce.moxiecode.com',
332 infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/paste',
333 version : tinymce.majorVersion + "." + tinymce.minorVersion
337 _preProcess : function(pl, o) {
338 var ed = this.editor,
341 explode = tinymce.explode,
345 //console.log('Before preprocess:' + o.content);
347 function process(items) {
348 each(items, function(v) {
350 if (v.constructor == RegExp)
351 h = h.replace(v, '');
353 h = h.replace(v[0], v[1]);
357 if (ed.settings.paste_enable_default_filters == false) {
361 // IE9 adds BRs before/after block elements when contents is pasted from word or for example another browser
362 if (tinymce.isIE && document.documentMode >= 9)
363 process([[/(?:<br> [\s\r\n]+|<br>)*(<\/?(h[1-6r]|p|div|address|pre|form|table|tbody|thead|tfoot|th|tr|td|li|ol|ul|caption|blockquote|center|dl|dt|dd|dir|fieldset)[^>]*>)(?:<br> [\s\r\n]+|<br>)*/g, '$1']]);
365 // Detect Word content and process it more aggressive
366 if (/class="?Mso|style="[^"]*\bmso-|w:WordDocument/i.test(h) || o.wordContent) {
367 o.wordContent = true; // Mark the pasted contents as word specific content
368 //console.log('Word contents detected.');
370 // Process away some basic content
372 /^\s*( )+/gi, // entities at the start of contents
373 /( |<br[^>]*>)+\s*$/gi // entities at the end of contents
376 if (getParam(ed, "paste_convert_headers_to_strong")) {
377 h = h.replace(/<p [^>]*class="?MsoHeading"?[^>]*>(.*?)<\/p>/gi, "<p><strong>$1</strong></p>");
380 if (getParam(ed, "paste_convert_middot_lists")) {
382 [/<!--\[if !supportLists\]-->/gi, '$&__MCE_ITEM__'], // Convert supportLists to a list item marker
383 [/(<span[^>]+(?:mso-list:|:\s*symbol)[^>]+>)/gi, '$1__MCE_ITEM__'], // Convert mso-list and symbol spans to item markers
384 [/(<p[^>]+(?:MsoListParagraph)[^>]+>)/gi, '$1__MCE_ITEM__'] // Convert mso-list and symbol paragraphs to item markers (FF)
389 // Word comments like conditional comments etc
392 // Remove comments, scripts (e.g., msoShowComment), XML tag, VML content, MS Office namespaced tags, and a few other tags
393 /<(!|script[^>]*>.*?<\/script(?=[>\s])|\/?(\?xml(:\w+)?|img|meta|link|style|\w:\w+)(?=[\s\/>]))[^>]*>/gi,
395 // Convert <s> into <strike> for line-though
396 [/<(\/?)s>/gi, "<$1strike>"],
398 // Replace nsbp entites to char since it's easier to handle
399 [/ /gi, "\u00a0"]
402 // Remove bad attributes, with or without quotes, ensuring that attribute text is really inside a tag.
403 // If JavaScript had a RegExp look-behind, we could have integrated this with the last process() array and got rid of the loop. But alas, it does not, so we cannot.
406 h = h.replace(/(<[a-z][^>]*\s)(?:id|name|language|type|on\w+|\w+:\w+)=(?:"[^"]*"|\w+)\s?/gi, "$1");
407 } while (len != h.length);
409 // Remove all spans if no styles is to be retained
410 if (getParam(ed, "paste_retain_style_properties").replace(/^none$/i, "").length == 0) {
411 h = h.replace(/<\/?span[^>]*>/gi, "");
413 // We're keeping styles, so at least clean them up.
414 // CSS Reference: http://msdn.microsoft.com/en-us/library/aa155477.aspx
417 // Convert <span style="mso-spacerun:yes">___</span> to string of alternating breaking/non-breaking spaces of same length
418 [/<span\s+style\s*=\s*"\s*mso-spacerun\s*:\s*yes\s*;?\s*"\s*>([\s\u00a0]*)<\/span>/gi,
419 function(str, spaces) {
420 return (spaces.length > 0)? spaces.replace(/./, " ").slice(Math.floor(spaces.length/2)).split("").join("\u00a0") : "";
424 // Examine all styles: delete junk, transform some, and keep the rest
425 [/(<[a-z][^>]*)\sstyle="([^"]*)"/gi,
426 function(str, tag, style) {
429 s = explode(trim(style).replace(/"/gi, "'"), ";");
431 // Examine each style definition within the tag's style attribute
432 each(s, function(v) {
434 parts = explode(v, ":");
436 function ensureUnits(v) {
437 return v + ((v !== "0") && (/\d$/.test(v)))? "px" : "";
440 if (parts.length == 2) {
441 name = parts[0].toLowerCase();
442 value = parts[1].toLowerCase();
444 // Translate certain MS Office styles into their CSS equivalents
446 case "mso-padding-alt":
447 case "mso-padding-top-alt":
448 case "mso-padding-right-alt":
449 case "mso-padding-bottom-alt":
450 case "mso-padding-left-alt":
451 case "mso-margin-alt":
452 case "mso-margin-top-alt":
453 case "mso-margin-right-alt":
454 case "mso-margin-bottom-alt":
455 case "mso-margin-left-alt":
456 case "mso-table-layout-alt":
459 case "mso-vertical-align-alt":
460 n[i++] = name.replace(/^mso-|-alt$/g, "") + ":" + ensureUnits(value);
464 n[i++] = "text-align:" + value;
468 n[i++] = "vertical-align:" + value;
472 case "mso-foreground":
473 n[i++] = "color:" + value;
476 case "mso-background":
477 case "mso-highlight":
478 n[i++] = "background:" + value;
481 case "mso-default-height":
482 n[i++] = "min-height:" + ensureUnits(value);
485 case "mso-default-width":
486 n[i++] = "min-width:" + ensureUnits(value);
489 case "mso-padding-between-alt":
490 n[i++] = "border-collapse:separate;border-spacing:" + ensureUnits(value);
493 case "text-line-through":
494 if ((value == "single") || (value == "double")) {
495 n[i++] = "text-decoration:line-through";
499 case "mso-zero-height":
500 if (value == "yes") {
501 n[i++] = "display:none";
506 // Eliminate all MS Office style definitions that have no CSS equivalent by examining the first characters in the name
507 if (/^(mso|column|font-emph|lang|layout|line-break|list-image|nav|panose|punct|row|ruby|sep|size|src|tab-|table-border|text-(?!align|decor|indent|trans)|top-bar|version|vnd|word-break)/.test(name)) {
511 // If it reached this point, it must be a valid CSS style
512 n[i++] = name + ":" + parts[1]; // Lower-case name, but keep value case
516 // If style attribute contained any valid styles the re-write it; otherwise delete style attribute.
518 return tag + ' style="' + n.join(';') + '"';
528 // Replace headers with <strong>
529 if (getParam(ed, "paste_convert_headers_to_strong")) {
531 [/<h[1-6][^>]*>/gi, "<p><strong>"],
532 [/<\/h[1-6][^>]*>/gi, "</strong></p>"]
537 // Copy paste from Java like Open Office will produce this junk on FF
538 [/Version:[\d.]+\nStartHTML:\d+\nEndHTML:\d+\nStartFragment:\d+\nEndFragment:\d+/gi, '']
541 // Class attribute options are: leave all as-is ("none"), remove all ("all"), or remove only those starting with mso ("mso").
542 // Note:- paste_strip_class_attributes: "none", verify_css_classes: true is also a good variation.
543 stripClass = getParam(ed, "paste_strip_class_attributes");
545 if (stripClass !== "none") {
546 function removeClasses(match, g1) {
547 if (stripClass === "all")
550 var cls = grep(explode(g1.replace(/^(["'])(.*)\1$/, "$2"), " "),
552 return (/^(?!mso)/i.test(v));
556 return cls.length ? ' class="' + cls.join(" ") + '"' : '';
559 h = h.replace(/ class="([^"]+)"/gi, removeClasses);
560 h = h.replace(/ class=([\-\w]+)/gi, removeClasses);
563 // Remove spans option
564 if (getParam(ed, "paste_remove_spans")) {
565 h = h.replace(/<\/?span[^>]*>/gi, "");
568 //console.log('After preprocess:' + h);
574 * Various post process items.
576 _postProcess : function(pl, o) {
577 var t = this, ed = t.editor, dom = ed.dom, styleProps;
579 if (ed.settings.paste_enable_default_filters == false) {
584 // Remove named anchors or TOC links
585 each(dom.select('a', o.node), function(a) {
586 if (!a.href || a.href.indexOf('#_Toc') != -1)
590 if (getParam(ed, "paste_convert_middot_lists")) {
591 t._convertLists(pl, o);
595 styleProps = getParam(ed, "paste_retain_style_properties"); // retained properties
597 // Process only if a string was specified and not equal to "all" or "*"
598 if ((tinymce.is(styleProps, "string")) && (styleProps !== "all") && (styleProps !== "*")) {
599 styleProps = tinymce.explode(styleProps.replace(/^none$/i, ""));
601 // Retains some style properties
602 each(dom.select('*', o.node), function(el) {
603 var newStyle = {}, npc = 0, i, sp, sv;
605 // Store a subset of the existing styles
607 for (i = 0; i < styleProps.length; i++) {
609 sv = dom.getStyle(el, sp);
618 // Remove all of the existing styles
619 dom.setAttrib(el, 'style', '');
621 if (styleProps && npc > 0)
622 dom.setStyles(el, newStyle); // Add back the stored subset of styles
623 else // Remove empty span tags that do not have class attributes
624 if (el.nodeName == 'SPAN' && !el.className)
625 dom.remove(el, true);
630 // Remove all style information or only specifically on WebKit to avoid the style bug on that browser
631 if (getParam(ed, "paste_remove_styles") || (getParam(ed, "paste_remove_styles_if_webkit") && tinymce.isWebKit)) {
632 each(dom.select('*[style]', o.node), function(el) {
633 el.removeAttribute('style');
634 el.removeAttribute('data-mce-style');
637 if (tinymce.isWebKit) {
638 // We need to compress the styles on WebKit since if you paste <img border="0" /> it will become <img border="0" style="... lots of junk ..." />
639 // Removing the mce_style that contains the real value will force the Serializer engine to compress the styles
640 each(dom.select('*', o.node), function(el) {
641 el.removeAttribute('data-mce-style');
648 * Converts the most common bullet and number formats in Office into a real semantic UL/LI list.
650 _convertLists : function(pl, o) {
651 var dom = pl.editor.dom, listElm, li, lastMargin = -1, margin, levels = [], lastType, html;
653 // Convert middot lists into real semantic lists
654 each(dom.select('p', o.node), function(p) {
655 var sib, val = '', type, html, idx, parents;
657 // Get text node value at beginning of paragraph
658 for (sib = p.firstChild; sib && sib.nodeType == 3; sib = sib.nextSibling)
659 val += sib.nodeValue;
661 val = p.innerHTML.replace(/<\/?\w+[^>]*>/gi, '').replace(/ /g, '\u00a0');
663 // Detect unordered lists look for bullets
664 if (/^(__MCE_ITEM__)+[\u2022\u00b7\u00a7\u00d8o\u25CF]\s*\u00a0*/.test(val))
667 // Detect ordered lists 1., a. or ixv.
668 if (/^__MCE_ITEM__\s*\w+\.\s*\u00a0+/.test(val))
671 // Check if node value matches the list pattern: o
673 margin = parseFloat(p.style.marginLeft || 0);
675 if (margin > lastMargin)
678 if (!listElm || type != lastType) {
679 listElm = dom.create(type);
680 dom.insertAfter(listElm, p);
682 // Nested list element
683 if (margin > lastMargin) {
684 listElm = li.appendChild(dom.create(type));
685 } else if (margin < lastMargin) {
686 // Find parent level based on margin value
687 idx = tinymce.inArray(levels, margin);
688 parents = dom.getParents(listElm.parentNode, type);
689 listElm = parents[parents.length - 1 - idx] || listElm;
693 // Remove middot or number spans if they exists
694 each(dom.select('span', p), function(span) {
695 var html = span.innerHTML.replace(/<\/?\w+[^>]*>/gi, '');
697 // Remove span with the middot or the number
698 if (type == 'ul' && /^__MCE_ITEM__[\u2022\u00b7\u00a7\u00d8o\u25CF]/.test(html))
700 else if (/^__MCE_ITEM__[\s\S]*\w+\.( |\u00a0)*\s*/.test(html))
706 // Remove middot/list items
708 html = p.innerHTML.replace(/__MCE_ITEM__/g, '').replace(/^[\u2022\u00b7\u00a7\u00d8o\u25CF]\s*( |\u00a0)+\s*/, '');
710 html = p.innerHTML.replace(/__MCE_ITEM__/g, '').replace(/^\s*\w+\.( |\u00a0)+\s*/, '');
712 // Create li and add paragraph data into the new li
713 li = listElm.appendChild(dom.create('li', 0, html));
719 listElm = lastMargin = 0; // End list element
722 // Remove any left over makers
723 html = o.node.innerHTML;
724 if (html.indexOf('__MCE_ITEM__') != -1)
725 o.node.innerHTML = html.replace(/__MCE_ITEM__/g, '');
729 * Inserts the specified contents at the caret position.
731 _insert : function(h, skip_undo) {
732 var ed = this.editor, r = ed.selection.getRng();
734 // First delete the contents seems to work better on WebKit when the selection spans multiple list items or multiple table cells.
735 if (!ed.selection.isCollapsed() && r.startContainer != r.endContainer)
736 ed.getDoc().execCommand('Delete', false, null);
738 ed.execCommand('mceInsertContent', false, h, {skip_undo : skip_undo});
742 * Instead of the old plain text method which tried to re-create a paste operation, the
743 * new approach adds a plain text mode toggle switch that changes the behavior of paste.
744 * This function is passed the same input that the regular paste plugin produces.
745 * It performs additional scrubbing and produces (and inserts) the plain text.
746 * This approach leverages all of the great existing functionality in the paste
747 * plugin, and requires minimal changes to add the new functionality.
748 * Speednet - June 2009
750 _insertPlainText : function(ed, dom, h) {
751 var i, len, pos, rpos, node, breakElms, before, after,
756 inArray = tinymce.inArray,
757 linebr = getParam(ed, "paste_text_linebreaktype"),
758 rl = getParam(ed, "paste_text_replacements");
760 function process(items) {
761 each(items, function(v) {
762 if (v.constructor == RegExp)
763 h = h.replace(v, "");
765 h = h.replace(v[0], v[1]);
769 if ((typeof(h) === "string") && (h.length > 0)) {
770 // If HTML content with line-breaking tags, then remove all cr/lf chars because only tags will break a line
771 if (/<(?:p|br|h[1-6]|ul|ol|dl|table|t[rdh]|div|blockquote|fieldset|pre|address|center)[^>]*>/i.test(h)) {
776 // Otherwise just get rid of carriage returns (only need linefeeds)
783 [/<\/(?:p|h[1-6]|ul|ol|dl|table|div|blockquote|fieldset|pre|address|center)>/gi, "\n\n"], // Block tags get a blank line after them
784 [/<br[^>]*>|<\/tr>/gi, "\n"], // Single linebreak for <br /> tags and table rows
785 [/<\/t[dh]>\s*<t[dh][^>]*>/gi, "\t"], // Table cells get tabs betweem them
786 /<[a-z!\/?][^>]*>/gi, // Delete all remaining tags
787 [/ /gi, " "], // Convert non-break spaces to regular spaces (remember, *plain text*)
788 [/(?:(?!\n)\s)*(\n+)(?:(?!\n)\s)*/gi, "$1"], // Cool little RegExp deletes whitespace around linebreak chars.
789 [/\n{3,}/g, "\n\n"], // Max. 2 consecutive linebreaks
790 /^\s+|\s+$/g // Trim the front & back
793 h = dom.decode(tinymce.html.Entities.encodeRaw(h));
795 // Delete any highlighted text before pasting
796 if (!sel.isCollapsed()) {
797 d.execCommand("Delete", false, null);
800 // Perform default or custom replacements
801 if (is(rl, "array") || (is(rl, "array"))) {
804 else if (is(rl, "string")) {
805 process(new RegExp(rl, "gi"));
808 // Treat paragraphs as specified in the config
809 if (linebr == "none") {
814 else if (linebr == "br") {
822 [/\n\n/g, "</p><p>"],
827 // This next piece of code handles the situation where we're pasting more than one paragraph of plain
828 // text, and we are pasting the content into the middle of a block node in the editor. The block
829 // node gets split at the selection point into "Para A" and "Para B" (for the purposes of explaining).
830 // The first paragraph of the pasted text is appended to "Para A", and the last paragraph of the
831 // pasted text is prepended to "Para B". Any other paragraphs of pasted text are placed between
832 // "Para A" and "Para B". This code solves a host of problems with the original plain text plugin and
833 // now handles styles correctly. (Pasting plain text into a styled paragraph is supposed to make the
834 // plain text take the same style as the existing paragraph.)
835 if ((pos = h.indexOf("</p><p>")) != -1) {
836 rpos = h.lastIndexOf("</p><p>");
837 node = sel.getNode();
838 breakElms = []; // Get list of elements to break
841 if (node.nodeType == 1) {
842 // Don't break tables and break at body
843 if (node.nodeName == "TD" || node.nodeName == "BODY") {
847 breakElms[breakElms.length] = node;
849 } while (node = node.parentNode);
851 // Are we in the middle of a block node?
852 if (breakElms.length > 0) {
853 before = h.substring(0, pos);
856 for (i=0, len=breakElms.length; i<len; i++) {
857 before += "</" + breakElms[i].nodeName.toLowerCase() + ">";
858 after += "<" + breakElms[breakElms.length-i-1].nodeName.toLowerCase() + ">";
862 h = before + after + h.substring(pos+7);
865 h = before + h.substring(pos+4, rpos+4) + after + h.substring(rpos+7);
870 // Insert content at the caret, plus add a marker for repositioning the caret
871 ed.execCommand("mceInsertRawHTML", false, h + '<span id="_plain_text_marker"> </span>');
873 // Reposition the caret to the marker, which was placed immediately after the inserted content.
874 // Needs to be done asynchronously (in window.setTimeout) or else it doesn't work in all browsers.
875 // The second part of the code scrolls the content up if the caret is positioned off-screen.
876 // This is only necessary for WebKit browsers, but it doesn't hurt to use for all.
877 window.setTimeout(function() {
878 var marker = dom.get('_plain_text_marker'),
879 elm, vp, y, elmHeight;
881 sel.select(marker, false);
882 d.execCommand("Delete", false, null);
885 // Get element, position and height
886 elm = sel.getStart();
887 vp = dom.getViewPort(w);
888 y = dom.getPos(elm).y;
889 elmHeight = elm.clientHeight;
891 // Is element within viewport if not then scroll it into view
892 if ((y < vp.y) || (y + elmHeight > vp.y + vp.h)) {
893 d.body.scrollTop = y < vp.y ? y : y - vp.h + 25;
900 * This method will open the old style paste dialogs. Some users might want the old behavior but still use the new cleanup engine.
902 _legacySupport : function() {
903 var t = this, ed = t.editor;
905 // Register command(s) for backwards compatibility
906 ed.addCommand("mcePasteWord", function() {
907 ed.windowManager.open({
908 file: t.url + "/pasteword.htm",
909 width: parseInt(getParam(ed, "paste_dialog_width")),
910 height: parseInt(getParam(ed, "paste_dialog_height")),
915 if (getParam(ed, "paste_text_use_dialog")) {
916 ed.addCommand("mcePasteText", function() {
917 ed.windowManager.open({
918 file : t.url + "/pastetext.htm",
919 width: parseInt(getParam(ed, "paste_dialog_width")),
920 height: parseInt(getParam(ed, "paste_dialog_height")),
926 // Register button for backwards compatibility
927 ed.addButton("pasteword", {title : "paste.paste_word_desc", cmd : "mcePasteWord"});
932 tinymce.PluginManager.add("paste", tinymce.plugins.PastePlugin);