2 * editor_plugin_src.js
\r
4 * Copyright 2009, Moxiecode Systems AB
\r
5 * Released under LGPL License.
\r
7 * License: http://tinymce.moxiecode.com/license
\r
8 * Contributing: http://tinymce.moxiecode.com/contributing
\r
12 var each = tinymce.each,
\r
15 paste_auto_cleanup_on_paste : true,
\r
16 paste_block_drop : false,
\r
17 paste_retain_style_properties : "none",
\r
18 paste_strip_class_attributes : "mso",
\r
19 paste_remove_spans : false,
\r
20 paste_remove_styles : false,
\r
21 paste_remove_styles_if_webkit : true,
\r
22 paste_convert_middot_lists : true,
\r
23 paste_convert_headers_to_strong : false,
\r
24 paste_dialog_width : "450",
\r
25 paste_dialog_height : "400",
\r
26 paste_text_use_dialog : false,
\r
27 paste_text_sticky : false,
\r
28 paste_text_notifyalways : false,
\r
29 paste_text_linebreaktype : "p",
\r
30 paste_text_replacements : [
\r
32 [/[\x93\x94\u201c\u201d]/g, '"'],
\r
33 [/[\x60\x91\x92\u2018\u2019]/g, "'"]
\r
37 function getParam(ed, name) {
\r
38 return ed.getParam(name, defs[name]);
\r
41 tinymce.create('tinymce.plugins.PastePlugin', {
\r
42 init : function(ed, url) {
\r
48 // Setup plugin events
\r
49 t.onPreProcess = new tinymce.util.Dispatcher(t);
\r
50 t.onPostProcess = new tinymce.util.Dispatcher(t);
\r
52 // Register default handlers
\r
53 t.onPreProcess.add(t._preProcess);
\r
54 t.onPostProcess.add(t._postProcess);
\r
56 // Register optional preprocess handler
\r
57 t.onPreProcess.add(function(pl, o) {
\r
58 ed.execCallback('paste_preprocess', pl, o);
\r
61 // Register optional postprocess
\r
62 t.onPostProcess.add(function(pl, o) {
\r
63 ed.execCallback('paste_postprocess', pl, o);
\r
66 // Initialize plain text flag
\r
67 ed.pasteAsPlainText = false;
\r
69 // This function executes the process handlers and inserts the contents
\r
70 // force_rich overrides plain text mode set by user, important for pasting with execCommand
\r
71 function process(o, force_rich) {
\r
74 // Execute pre process handlers
\r
75 t.onPreProcess.dispatch(t, o);
\r
77 // Create DOM structure
\r
78 o.node = dom.create('div', 0, o.content);
\r
80 // Execute post process handlers
\r
81 t.onPostProcess.dispatch(t, o);
\r
83 // Serialize content
\r
84 o.content = ed.serializer.serialize(o.node, {getInner : 1});
\r
86 // Plain text option active?
\r
87 if ((!force_rich) && (ed.pasteAsPlainText)) {
\r
88 t._insertPlainText(ed, dom, o.content);
\r
90 if (!getParam(ed, "paste_text_sticky")) {
\r
91 ed.pasteAsPlainText = false;
\r
92 ed.controlManager.setActive("pastetext", false);
\r
94 } else if (/<(p|h[1-6]|ul|ol)/.test(o.content)) {
\r
95 // Handle insertion of contents containing block elements separately
\r
96 t._insertBlockContent(ed, dom, o.content);
\r
98 t._insert(o.content);
\r
102 // Add command for external usage
\r
103 ed.addCommand('mceInsertClipboardContent', function(u, o) {
\r
107 if (!getParam(ed, "paste_text_use_dialog")) {
\r
108 ed.addCommand('mcePasteText', function(u, v) {
\r
109 var cookie = tinymce.util.Cookie;
\r
111 ed.pasteAsPlainText = !ed.pasteAsPlainText;
\r
112 ed.controlManager.setActive('pastetext', ed.pasteAsPlainText);
\r
114 if ((ed.pasteAsPlainText) && (!cookie.get("tinymcePasteText"))) {
\r
115 if (getParam(ed, "paste_text_sticky")) {
\r
116 ed.windowManager.alert("Paste is now in plain text mode. Click again to toggle back to regular paste mode. After you paste something you will be returned to regular paste mode.");
\r
118 ed.windowManager.alert("Paste is now in plain text mode. Click again to toggle back to regular paste mode.");
\r
121 if (!getParam(ed, "paste_text_notifyalways")) {
\r
122 cookie.set("tinymcePasteText", "1", new Date(new Date().getFullYear() + 1, 12, 31))
\r
128 ed.addButton('pastetext', {title: 'paste.paste_text_desc', cmd: 'mcePasteText'});
\r
129 ed.addButton('selectall', {title: 'paste.selectall_desc', cmd: 'selectall'});
\r
131 // This function grabs the contents from the clipboard by adding a
\r
132 // hidden div and placing the caret inside it and after the browser paste
\r
133 // is done it grabs that contents and processes that
\r
134 function grabContent(e) {
\r
135 var n, or, rng, sel = ed.selection, dom = ed.dom, body = ed.getBody(), posY;
\r
137 if (dom.get('_mcePaste'))
\r
140 // Create container to paste into
\r
141 n = dom.add(body, 'div', {id : '_mcePaste', 'class' : 'mcePaste'}, '\uFEFF');
\r
143 // If contentEditable mode we need to find out the position of the closest element
\r
144 if (body != ed.getDoc().body)
\r
145 posY = dom.getPos(ed.selection.getStart(), body).y;
\r
147 posY = body.scrollTop;
\r
149 // Styles needs to be applied after the element is added to the document since WebKit will otherwise remove all styles
\r
151 position : 'absolute',
\r
156 overflow : 'hidden'
\r
159 if (tinymce.isIE) {
\r
160 // Select the container
\r
161 rng = dom.doc.body.createTextRange();
\r
162 rng.moveToElementText(n);
\r
163 rng.execCommand('Paste');
\r
165 // Remove container
\r
168 // Check if the contents was changed, if it wasn't then clipboard extraction failed probably due
\r
169 // to IE security settings so we pass the junk though better than nothing right
\r
170 if (n.innerHTML === '\uFEFF') {
\r
171 ed.execCommand('mcePasteWord');
\r
172 e.preventDefault();
\r
176 // Process contents
\r
177 process({content : n.innerHTML});
\r
179 // Block the real paste event
\r
180 return tinymce.dom.Event.cancel(e);
\r
182 function block(e) {
\r
183 e.preventDefault();
\r
186 // Block mousedown and click to prevent selection change
\r
187 dom.bind(ed.getDoc(), 'mousedown', block);
\r
188 dom.bind(ed.getDoc(), 'keydown', block);
\r
190 or = ed.selection.getRng();
\r
192 // Move caret into hidden div
\r
194 rng = ed.getDoc().createRange();
\r
195 rng.setStart(n, 0);
\r
199 // Wait a while and grab the pasted contents
\r
200 window.setTimeout(function() {
\r
201 var h = '', nl = dom.select('div.mcePaste');
\r
203 // WebKit will split the div into multiple ones so this will loop through then all and join them to get the whole HTML string
\r
204 each(nl, function(n) {
\r
205 // WebKit duplicates the divs so we need to remove them
\r
206 each(dom.select('div.mcePaste', n), function(n) {
\r
210 // Contents in WebKit is sometimes wrapped in a apple style span so we need to grab it from that one
\r
211 h += (dom.select('> span.Apple-style-span div', n)[0] || dom.select('> span.Apple-style-span', n)[0] || n).innerHTML;
\r
214 // Remove the nodes
\r
215 each(nl, function(n) {
\r
219 // Restore the old selection
\r
223 process({content : h});
\r
225 // Unblock events ones we got the contents
\r
226 dom.unbind(ed.getDoc(), 'mousedown', block);
\r
227 dom.unbind(ed.getDoc(), 'keydown', block);
\r
232 // Check if we should use the new auto process method
\r
233 if (getParam(ed, "paste_auto_cleanup_on_paste")) {
\r
234 // Is it's Opera or older FF use key handler
\r
235 if (tinymce.isOpera || /Firefox\/2/.test(navigator.userAgent)) {
\r
236 ed.onKeyDown.add(function(ed, e) {
\r
237 if (((tinymce.isMac ? e.metaKey : e.ctrlKey) && e.keyCode == 86) || (e.shiftKey && e.keyCode == 45))
\r
241 // Grab contents on paste event on Gecko and WebKit
\r
242 ed.onPaste.addToTop(function(ed, e) {
\r
243 return grabContent(e);
\r
248 // Block all drag/drop events
\r
249 if (getParam(ed, "paste_block_drop")) {
\r
250 ed.onInit.add(function() {
\r
251 ed.dom.bind(ed.getBody(), ['dragend', 'dragover', 'draggesture', 'dragdrop', 'drop', 'drag'], function(e) {
\r
252 e.preventDefault();
\r
253 e.stopPropagation();
\r
260 // Add legacy support
\r
261 t._legacySupport();
\r
264 getInfo : function() {
\r
266 longname : 'Paste text/word',
\r
267 author : 'Moxiecode Systems AB',
\r
268 authorurl : 'http://tinymce.moxiecode.com',
\r
269 infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/paste',
\r
270 version : tinymce.majorVersion + "." + tinymce.minorVersion
\r
274 _preProcess : function(pl, o) {
\r
275 //console.log('Before preprocess:' + o.content);
\r
277 var ed = this.editor,
\r
279 grep = tinymce.grep,
\r
280 explode = tinymce.explode,
\r
281 trim = tinymce.trim,
\r
284 function process(items) {
\r
285 each(items, function(v) {
\r
286 // Remove or replace
\r
287 if (v.constructor == RegExp)
\r
288 h = h.replace(v, '');
\r
290 h = h.replace(v[0], v[1]);
\r
294 // Detect Word content and process it more aggressive
\r
295 if (/class="?Mso|style="[^"]*\bmso-|w:WordDocument/i.test(h) || o.wordContent) {
\r
296 o.wordContent = true; // Mark the pasted contents as word specific content
\r
297 //console.log('Word contents detected.');
\r
299 // Process away some basic content
\r
301 /^\s*( )+/gi, // entities at the start of contents
\r
302 /( |<br[^>]*>)+\s*$/gi // entities at the end of contents
\r
305 if (getParam(ed, "paste_convert_headers_to_strong")) {
\r
306 h = h.replace(/<p [^>]*class="?MsoHeading"?[^>]*>(.*?)<\/p>/gi, "<p><strong>$1</strong></p>");
\r
309 if (getParam(ed, "paste_convert_middot_lists")) {
\r
311 [/<!--\[if !supportLists\]-->/gi, '$&__MCE_ITEM__'], // Convert supportLists to a list item marker
\r
312 [/(<span[^>]+(?:mso-list:|:\s*symbol)[^>]+>)/gi, '$1__MCE_ITEM__'] // Convert mso-list and symbol spans to item markers
\r
317 // Word comments like conditional comments etc
\r
318 /<!--[\s\S]+?-->/gi,
\r
320 // Remove comments, scripts (e.g., msoShowComment), XML tag, VML content, MS Office namespaced tags, and a few other tags
\r
321 /<(!|script[^>]*>.*?<\/script(?=[>\s])|\/?(\?xml(:\w+)?|img|meta|link|style|\w:\w+)(?=[\s\/>]))[^>]*>/gi,
\r
323 // Convert <s> into <strike> for line-though
\r
324 [/<(\/?)s>/gi, "<$1strike>"],
\r
326 // Replace nsbp entites to char since it's easier to handle
\r
327 [/ /gi, "\u00a0"]
\r
330 // Remove bad attributes, with or without quotes, ensuring that attribute text is really inside a tag.
\r
331 // 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.
\r
334 h = h.replace(/(<[a-z][^>]*\s)(?:id|name|language|type|on\w+|\w+:\w+)=(?:"[^"]*"|\w+)\s?/gi, "$1");
\r
335 } while (len != h.length);
\r
337 // Remove all spans if no styles is to be retained
\r
338 if (getParam(ed, "paste_retain_style_properties").replace(/^none$/i, "").length == 0) {
\r
339 h = h.replace(/<\/?span[^>]*>/gi, "");
\r
341 // We're keeping styles, so at least clean them up.
\r
342 // CSS Reference: http://msdn.microsoft.com/en-us/library/aa155477.aspx
\r
345 // Convert <span style="mso-spacerun:yes">___</span> to string of alternating breaking/non-breaking spaces of same length
\r
346 [/<span\s+style\s*=\s*"\s*mso-spacerun\s*:\s*yes\s*;?\s*"\s*>([\s\u00a0]*)<\/span>/gi,
\r
347 function(str, spaces) {
\r
348 return (spaces.length > 0)? spaces.replace(/./, " ").slice(Math.floor(spaces.length/2)).split("").join("\u00a0") : "";
\r
352 // Examine all styles: delete junk, transform some, and keep the rest
\r
353 [/(<[a-z][^>]*)\sstyle="([^"]*)"/gi,
\r
354 function(str, tag, style) {
\r
357 s = explode(trim(style).replace(/"/gi, "'"), ";");
\r
359 // Examine each style definition within the tag's style attribute
\r
360 each(s, function(v) {
\r
362 parts = explode(v, ":");
\r
364 function ensureUnits(v) {
\r
365 return v + ((v !== "0") && (/\d$/.test(v)))? "px" : "";
\r
368 if (parts.length == 2) {
\r
369 name = parts[0].toLowerCase();
\r
370 value = parts[1].toLowerCase();
\r
372 // Translate certain MS Office styles into their CSS equivalents
\r
374 case "mso-padding-alt":
\r
375 case "mso-padding-top-alt":
\r
376 case "mso-padding-right-alt":
\r
377 case "mso-padding-bottom-alt":
\r
378 case "mso-padding-left-alt":
\r
379 case "mso-margin-alt":
\r
380 case "mso-margin-top-alt":
\r
381 case "mso-margin-right-alt":
\r
382 case "mso-margin-bottom-alt":
\r
383 case "mso-margin-left-alt":
\r
384 case "mso-table-layout-alt":
\r
387 case "mso-vertical-align-alt":
\r
388 n[i++] = name.replace(/^mso-|-alt$/g, "") + ":" + ensureUnits(value);
\r
391 case "horiz-align":
\r
392 n[i++] = "text-align:" + value;
\r
396 n[i++] = "vertical-align:" + value;
\r
400 case "mso-foreground":
\r
401 n[i++] = "color:" + value;
\r
404 case "mso-background":
\r
405 case "mso-highlight":
\r
406 n[i++] = "background:" + value;
\r
409 case "mso-default-height":
\r
410 n[i++] = "min-height:" + ensureUnits(value);
\r
413 case "mso-default-width":
\r
414 n[i++] = "min-width:" + ensureUnits(value);
\r
417 case "mso-padding-between-alt":
\r
418 n[i++] = "border-collapse:separate;border-spacing:" + ensureUnits(value);
\r
421 case "text-line-through":
\r
422 if ((value == "single") || (value == "double")) {
\r
423 n[i++] = "text-decoration:line-through";
\r
427 case "mso-zero-height":
\r
428 if (value == "yes") {
\r
429 n[i++] = "display:none";
\r
434 // Eliminate all MS Office style definitions that have no CSS equivalent by examining the first characters in the name
\r
435 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)) {
\r
439 // If it reached this point, it must be a valid CSS style
\r
440 n[i++] = name + ":" + parts[1]; // Lower-case name, but keep value case
\r
444 // If style attribute contained any valid styles the re-write it; otherwise delete style attribute.
\r
446 return tag + ' style="' + n.join(';') + '"';
\r
456 // Replace headers with <strong>
\r
457 if (getParam(ed, "paste_convert_headers_to_strong")) {
\r
459 [/<h[1-6][^>]*>/gi, "<p><strong>"],
\r
460 [/<\/h[1-6][^>]*>/gi, "</strong></p>"]
\r
464 // Class attribute options are: leave all as-is ("none"), remove all ("all"), or remove only those starting with mso ("mso").
\r
465 // Note:- paste_strip_class_attributes: "none", verify_css_classes: true is also a good variation.
\r
466 stripClass = getParam(ed, "paste_strip_class_attributes");
\r
468 if (stripClass !== "none") {
\r
469 function removeClasses(match, g1) {
\r
470 if (stripClass === "all")
\r
473 var cls = grep(explode(g1.replace(/^(["'])(.*)\1$/, "$2"), " "),
\r
475 return (/^(?!mso)/i.test(v));
\r
479 return cls.length ? ' class="' + cls.join(" ") + '"' : '';
\r
482 h = h.replace(/ class="([^"]+)"/gi, removeClasses);
\r
483 h = h.replace(/ class=(\w+)/gi, removeClasses);
\r
486 // Remove spans option
\r
487 if (getParam(ed, "paste_remove_spans")) {
\r
488 h = h.replace(/<\/?span[^>]*>/gi, "");
\r
491 //console.log('After preprocess:' + h);
\r
497 * Various post process items.
\r
499 _postProcess : function(pl, o) {
\r
500 var t = this, ed = t.editor, dom = ed.dom, styleProps;
\r
502 if (o.wordContent) {
\r
503 // Remove named anchors or TOC links
\r
504 each(dom.select('a', o.node), function(a) {
\r
505 if (!a.href || a.href.indexOf('#_Toc') != -1)
\r
509 if (getParam(ed, "paste_convert_middot_lists")) {
\r
510 t._convertLists(pl, o);
\r
514 styleProps = getParam(ed, "paste_retain_style_properties"); // retained properties
\r
516 // Process only if a string was specified and not equal to "all" or "*"
\r
517 if ((tinymce.is(styleProps, "string")) && (styleProps !== "all") && (styleProps !== "*")) {
\r
518 styleProps = tinymce.explode(styleProps.replace(/^none$/i, ""));
\r
520 // Retains some style properties
\r
521 each(dom.select('*', o.node), function(el) {
\r
522 var newStyle = {}, npc = 0, i, sp, sv;
\r
524 // Store a subset of the existing styles
\r
526 for (i = 0; i < styleProps.length; i++) {
\r
527 sp = styleProps[i];
\r
528 sv = dom.getStyle(el, sp);
\r
537 // Remove all of the existing styles
\r
538 dom.setAttrib(el, 'style', '');
\r
540 if (styleProps && npc > 0)
\r
541 dom.setStyles(el, newStyle); // Add back the stored subset of styles
\r
542 else // Remove empty span tags that do not have class attributes
\r
543 if (el.nodeName == 'SPAN' && !el.className)
\r
544 dom.remove(el, true);
\r
549 // Remove all style information or only specifically on WebKit to avoid the style bug on that browser
\r
550 if (getParam(ed, "paste_remove_styles") || (getParam(ed, "paste_remove_styles_if_webkit") && tinymce.isWebKit)) {
\r
551 each(dom.select('*[style]', o.node), function(el) {
\r
552 el.removeAttribute('style');
\r
553 el.removeAttribute('_mce_style');
\r
556 if (tinymce.isWebKit) {
\r
557 // 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 ..." />
\r
558 // Removing the mce_style that contains the real value will force the Serializer engine to compress the styles
\r
559 each(dom.select('*', o.node), function(el) {
\r
560 el.removeAttribute('_mce_style');
\r
567 * Converts the most common bullet and number formats in Office into a real semantic UL/LI list.
\r
569 _convertLists : function(pl, o) {
\r
570 var dom = pl.editor.dom, listElm, li, lastMargin = -1, margin, levels = [], lastType, html;
\r
572 // Convert middot lists into real semantic lists
\r
573 each(dom.select('p', o.node), function(p) {
\r
574 var sib, val = '', type, html, idx, parents;
\r
576 // Get text node value at beginning of paragraph
\r
577 for (sib = p.firstChild; sib && sib.nodeType == 3; sib = sib.nextSibling)
\r
578 val += sib.nodeValue;
\r
580 val = p.innerHTML.replace(/<\/?\w+[^>]*>/gi, '').replace(/ /g, '\u00a0');
\r
582 // Detect unordered lists look for bullets
\r
583 if (/^(__MCE_ITEM__)+[\u2022\u00b7\u00a7\u00d8o]\s*\u00a0*/.test(val))
\r
586 // Detect ordered lists 1., a. or ixv.
\r
587 if (/^__MCE_ITEM__\s*\w+\.\s*\u00a0{2,}/.test(val))
\r
590 // Check if node value matches the list pattern: o
\r
592 margin = parseFloat(p.style.marginLeft || 0);
\r
594 if (margin > lastMargin)
\r
595 levels.push(margin);
\r
597 if (!listElm || type != lastType) {
\r
598 listElm = dom.create(type);
\r
599 dom.insertAfter(listElm, p);
\r
601 // Nested list element
\r
602 if (margin > lastMargin) {
\r
603 listElm = li.appendChild(dom.create(type));
\r
604 } else if (margin < lastMargin) {
\r
605 // Find parent level based on margin value
\r
606 idx = tinymce.inArray(levels, margin);
\r
607 parents = dom.getParents(listElm.parentNode, type);
\r
608 listElm = parents[parents.length - 1 - idx] || listElm;
\r
612 // Remove middot or number spans if they exists
\r
613 each(dom.select('span', p), function(span) {
\r
614 var html = span.innerHTML.replace(/<\/?\w+[^>]*>/gi, '');
\r
616 // Remove span with the middot or the number
\r
617 if (type == 'ul' && /^[\u2022\u00b7\u00a7\u00d8o]/.test(html))
\r
619 else if (/^[\s\S]*\w+\.( |\u00a0)*\s*/.test(html))
\r
623 html = p.innerHTML;
\r
625 // Remove middot/list items
\r
627 html = p.innerHTML.replace(/__MCE_ITEM__/g, '').replace(/^[\u2022\u00b7\u00a7\u00d8o]\s*( |\u00a0)+\s*/, '');
\r
629 html = p.innerHTML.replace(/__MCE_ITEM__/g, '').replace(/^\s*\w+\.( |\u00a0)+\s*/, '');
\r
631 // Create li and add paragraph data into the new li
\r
632 li = listElm.appendChild(dom.create('li', 0, html));
\r
635 lastMargin = margin;
\r
638 listElm = lastMargin = 0; // End list element
\r
641 // Remove any left over makers
\r
642 html = o.node.innerHTML;
\r
643 if (html.indexOf('__MCE_ITEM__') != -1)
\r
644 o.node.innerHTML = html.replace(/__MCE_ITEM__/g, '');
\r
648 * This method will split the current block parent and insert the contents inside the split position.
\r
649 * This logic can be improved so text nodes at the start/end remain in the start/end block elements
\r
651 _insertBlockContent : function(ed, dom, content) {
\r
652 var parentBlock, marker, sel = ed.selection, last, elm, vp, y, elmHeight, markerId = 'mce_marker';
\r
654 function select(n) {
\r
657 if (tinymce.isIE) {
\r
658 r = ed.getDoc().body.createTextRange();
\r
659 r.moveToElementText(n);
\r
664 sel.collapse(false);
\r
668 // Insert a marker for the caret position
\r
669 this._insert('<span id="' + markerId + '"> </span>', 1);
\r
670 marker = dom.get(markerId);
\r
671 parentBlock = dom.getParent(marker, 'p,h1,h2,h3,h4,h5,h6,ul,ol,th,td');
\r
673 // If it's a parent block but not a table cell
\r
674 if (parentBlock && !/TD|TH/.test(parentBlock.nodeName)) {
\r
675 // Split parent block
\r
676 marker = dom.split(parentBlock, marker);
\r
678 // Insert nodes before the marker
\r
679 each(dom.create('div', 0, content).childNodes, function(n) {
\r
680 last = marker.parentNode.insertBefore(n.cloneNode(true), marker);
\r
683 // Move caret after marker
\r
686 dom.setOuterHTML(marker, content);
\r
687 sel.select(ed.getBody(), 1);
\r
691 // Remove marker if it's left
\r
692 while (elm = dom.get(markerId))
\r
695 // Get element, position and height
\r
696 elm = sel.getStart();
\r
697 vp = dom.getViewPort(ed.getWin());
\r
698 y = ed.dom.getPos(elm).y;
\r
699 elmHeight = elm.clientHeight;
\r
701 // Is element within viewport if not then scroll it into view
\r
702 if (y < vp.y || y + elmHeight > vp.y + vp.h)
\r
703 ed.getDoc().body.scrollTop = y < vp.y ? y : y - vp.h + 25;
\r
707 * Inserts the specified contents at the caret position.
\r
709 _insert : function(h, skip_undo) {
\r
710 var ed = this.editor;
\r
712 // First delete the contents seems to work better on WebKit
\r
713 if (!ed.selection.isCollapsed())
\r
714 ed.getDoc().execCommand('Delete', false, null);
\r
716 // It's better to use the insertHTML method on Gecko since it will combine paragraphs correctly before inserting the contents
\r
717 ed.execCommand(tinymce.isGecko ? 'insertHTML' : 'mceInsertContent', false, h, {skip_undo : skip_undo});
\r
721 * Instead of the old plain text method which tried to re-create a paste operation, the
\r
722 * new approach adds a plain text mode toggle switch that changes the behavior of paste.
\r
723 * This function is passed the same input that the regular paste plugin produces.
\r
724 * It performs additional scrubbing and produces (and inserts) the plain text.
\r
725 * This approach leverages all of the great existing functionality in the paste
\r
726 * plugin, and requires minimal changes to add the new functionality.
\r
727 * Speednet - June 2009
\r
729 _insertPlainText : function(ed, dom, h) {
\r
730 var i, len, pos, rpos, node, breakElms, before, after,
\r
733 sel = ed.selection,
\r
735 inArray = tinymce.inArray,
\r
736 linebr = getParam(ed, "paste_text_linebreaktype"),
\r
737 rl = getParam(ed, "paste_text_replacements");
\r
739 function process(items) {
\r
740 each(items, function(v) {
\r
741 if (v.constructor == RegExp)
\r
742 h = h.replace(v, "");
\r
744 h = h.replace(v[0], v[1]);
\r
748 if ((typeof(h) === "string") && (h.length > 0)) {
\r
750 entities = ("34,quot,38,amp,39,apos,60,lt,62,gt," + ed.serializer.settings.entities).split(",");
\r
752 // If HTML content with line-breaking tags, then remove all cr/lf chars because only tags will break a line
\r
753 if (/<(?:p|br|h[1-6]|ul|ol|dl|table|t[rdh]|div|blockquote|fieldset|pre|address|center)[^>]*>/i.test(h)) {
\r
758 // Otherwise just get rid of carriage returns (only need linefeeds)
\r
765 [/<\/(?: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
\r
766 [/<br[^>]*>|<\/tr>/gi, "\n"], // Single linebreak for <br /> tags and table rows
\r
767 [/<\/t[dh]>\s*<t[dh][^>]*>/gi, "\t"], // Table cells get tabs betweem them
\r
768 /<[a-z!\/?][^>]*>/gi, // Delete all remaining tags
\r
769 [/ /gi, " "], // Convert non-break spaces to regular spaces (remember, *plain text*)
\r
772 /&(#\d+|[a-z0-9]{1,10});/gi,
\r
774 // Replace with actual character
\r
776 if (s.charAt(0) === "#") {
\r
777 return String.fromCharCode(s.slice(1));
\r
780 return ((e = inArray(entities, s)) > 0)? String.fromCharCode(entities[e-1]) : " ";
\r
784 [/(?:(?!\n)\s)*(\n+)(?:(?!\n)\s)*/gi, "$1"], // Cool little RegExp deletes whitespace around linebreak chars.
\r
785 [/\n{3,}/g, "\n\n"], // Max. 2 consecutive linebreaks
\r
786 /^\s+|\s+$/g // Trim the front & back
\r
791 // Delete any highlighted text before pasting
\r
792 if (!sel.isCollapsed()) {
\r
793 d.execCommand("Delete", false, null);
\r
796 // Perform default or custom replacements
\r
797 if (is(rl, "array") || (is(rl, "array"))) {
\r
800 else if (is(rl, "string")) {
\r
801 process(new RegExp(rl, "gi"));
\r
804 // Treat paragraphs as specified in the config
\r
805 if (linebr == "none") {
\r
810 else if (linebr == "br") {
\r
818 [/\n\n/g, "</p><p>"],
\r
823 // This next piece of code handles the situation where we're pasting more than one paragraph of plain
\r
824 // text, and we are pasting the content into the middle of a block node in the editor. The block
\r
825 // node gets split at the selection point into "Para A" and "Para B" (for the purposes of explaining).
\r
826 // The first paragraph of the pasted text is appended to "Para A", and the last paragraph of the
\r
827 // pasted text is prepended to "Para B". Any other paragraphs of pasted text are placed between
\r
828 // "Para A" and "Para B". This code solves a host of problems with the original plain text plugin and
\r
829 // now handles styles correctly. (Pasting plain text into a styled paragraph is supposed to make the
\r
830 // plain text take the same style as the existing paragraph.)
\r
831 if ((pos = h.indexOf("</p><p>")) != -1) {
\r
832 rpos = h.lastIndexOf("</p><p>");
\r
833 node = sel.getNode();
\r
834 breakElms = []; // Get list of elements to break
\r
837 if (node.nodeType == 1) {
\r
838 // Don't break tables and break at body
\r
839 if (node.nodeName == "TD" || node.nodeName == "BODY") {
\r
843 breakElms[breakElms.length] = node;
\r
845 } while (node = node.parentNode);
\r
847 // Are we in the middle of a block node?
\r
848 if (breakElms.length > 0) {
\r
849 before = h.substring(0, pos);
\r
852 for (i=0, len=breakElms.length; i<len; i++) {
\r
853 before += "</" + breakElms[i].nodeName.toLowerCase() + ">";
\r
854 after += "<" + breakElms[breakElms.length-i-1].nodeName.toLowerCase() + ">";
\r
858 h = before + after + h.substring(pos+7);
\r
861 h = before + h.substring(pos+4, rpos+4) + after + h.substring(rpos+7);
\r
866 // Insert content at the caret, plus add a marker for repositioning the caret
\r
867 ed.execCommand("mceInsertRawHTML", false, h + '<span id="_plain_text_marker"> </span>');
\r
869 // Reposition the caret to the marker, which was placed immediately after the inserted content.
\r
870 // Needs to be done asynchronously (in window.setTimeout) or else it doesn't work in all browsers.
\r
871 // The second part of the code scrolls the content up if the caret is positioned off-screen.
\r
872 // This is only necessary for WebKit browsers, but it doesn't hurt to use for all.
\r
873 window.setTimeout(function() {
\r
874 var marker = dom.get('_plain_text_marker'),
\r
875 elm, vp, y, elmHeight;
\r
877 sel.select(marker, false);
\r
878 d.execCommand("Delete", false, null);
\r
881 // Get element, position and height
\r
882 elm = sel.getStart();
\r
883 vp = dom.getViewPort(w);
\r
884 y = dom.getPos(elm).y;
\r
885 elmHeight = elm.clientHeight;
\r
887 // Is element within viewport if not then scroll it into view
\r
888 if ((y < vp.y) || (y + elmHeight > vp.y + vp.h)) {
\r
889 d.body.scrollTop = y < vp.y ? y : y - vp.h + 25;
\r
896 * This method will open the old style paste dialogs. Some users might want the old behavior but still use the new cleanup engine.
\r
898 _legacySupport : function() {
\r
899 var t = this, ed = t.editor;
\r
901 // Register command(s) for backwards compatibility
\r
902 ed.addCommand("mcePasteWord", function() {
\r
903 ed.windowManager.open({
\r
904 file: t.url + "/pasteword.htm",
\r
905 width: parseInt(getParam(ed, "paste_dialog_width")),
\r
906 height: parseInt(getParam(ed, "paste_dialog_height")),
\r
911 if (getParam(ed, "paste_text_use_dialog")) {
\r
912 ed.addCommand("mcePasteText", function() {
\r
913 ed.windowManager.open({
\r
914 file : t.url + "/pastetext.htm",
\r
915 width: parseInt(getParam(ed, "paste_dialog_width")),
\r
916 height: parseInt(getParam(ed, "paste_dialog_height")),
\r
922 // Register button for backwards compatibility
\r
923 ed.addButton("pasteword", {title : "paste.paste_word_desc", cmd : "mcePasteWord"});
\r
928 tinymce.PluginManager.add("paste", tinymce.plugins.PastePlugin);
\r