thomascube
2011-04-20 a9251be2f09fb5f18a85d201c67668c70980efe3
commit | author | age
d9344f 1 /**
69d05c 2  * editor_plugin_src.js
d9344f 3  *
69d05c 4  * Copyright 2009, Moxiecode Systems AB
A 5  * Released under LGPL License.
6  *
7  * License: http://tinymce.moxiecode.com/license
8  * Contributing: http://tinymce.moxiecode.com/contributing
d9344f 9  */
S 10
11 (function() {
69d05c 12     var each = tinymce.each,
A 13         defs = {
14             paste_auto_cleanup_on_paste : true,
a9251b 15             paste_enable_default_filters : true,
69d05c 16             paste_block_drop : false,
A 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,
a9251b 28             paste_text_sticky_default : false,
69d05c 29             paste_text_notifyalways : false,
A 30             paste_text_linebreaktype : "p",
31             paste_text_replacements : [
32                 [/\u2026/g, "..."],
33                 [/[\x93\x94\u201c\u201d]/g, '"'],
34                 [/[\x60\x91\x92\u2018\u2019]/g, "'"]
35             ]
36         };
37
38     function getParam(ed, name) {
39         return ed.getParam(name, defs[name]);
40     }
d9344f 41
S 42     tinymce.create('tinymce.plugins.PastePlugin', {
43         init : function(ed, url) {
69d05c 44             var t = this;
d9344f 45
29da64 46             t.editor = ed;
A 47             t.url = url;
d9344f 48
29da64 49             // Setup plugin events
A 50             t.onPreProcess = new tinymce.util.Dispatcher(t);
51             t.onPostProcess = new tinymce.util.Dispatcher(t);
52
53             // Register default handlers
54             t.onPreProcess.add(t._preProcess);
55             t.onPostProcess.add(t._postProcess);
56
57             // Register optional preprocess handler
58             t.onPreProcess.add(function(pl, o) {
59                 ed.execCallback('paste_preprocess', pl, o);
d9344f 60             });
S 61
29da64 62             // Register optional postprocess
A 63             t.onPostProcess.add(function(pl, o) {
64                 ed.execCallback('paste_postprocess', pl, o);
d9344f 65             });
S 66
a9251b 67             ed.onKeyDown.addToTop(function(ed, e) {
T 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
71             });
72
69d05c 73             // Initialize plain text flag
a9251b 74             ed.pasteAsPlainText = getParam(ed, 'paste_text_sticky_default');
69d05c 75
29da64 76             // This function executes the process handlers and inserts the contents
69d05c 77             // force_rich overrides plain text mode set by user, important for pasting with execCommand
A 78             function process(o, force_rich) {
a9251b 79                 var dom = ed.dom, rng, nodes;
29da64 80
A 81                 // Execute pre process handlers
82                 t.onPreProcess.dispatch(t, o);
83
84                 // Create DOM structure
85                 o.node = dom.create('div', 0, o.content);
a9251b 86
T 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);
93
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);
97                     }
98                 }
29da64 99
A 100                 // Execute post process handlers
101                 t.onPostProcess.dispatch(t, o);
102
103                 // Serialize content
104                 o.content = ed.serializer.serialize(o.node, {getInner : 1});
105
69d05c 106                 // Plain text option active?
A 107                 if ((!force_rich) && (ed.pasteAsPlainText)) {
108                     t._insertPlainText(ed, dom, o.content);
109
110                     if (!getParam(ed, "paste_text_sticky")) {
111                         ed.pasteAsPlainText = false;
112                         ed.controlManager.setActive("pastetext", false);
113                     }
114                 } else {
29da64 115                     t._insert(o.content);
69d05c 116                 }
A 117             }
29da64 118
A 119             // Add command for external usage
58fb65 120             ed.addCommand('mceInsertClipboardContent', function(u, o) {
69d05c 121                 process(o, true);
d9344f 122             });
69d05c 123
A 124             if (!getParam(ed, "paste_text_use_dialog")) {
125                 ed.addCommand('mcePasteText', function(u, v) {
126                     var cookie = tinymce.util.Cookie;
127
128                     ed.pasteAsPlainText = !ed.pasteAsPlainText;
129                     ed.controlManager.setActive('pastetext', ed.pasteAsPlainText);
130
131                     if ((ed.pasteAsPlainText) && (!cookie.get("tinymcePasteText"))) {
132                         if (getParam(ed, "paste_text_sticky")) {
2011be 133                             ed.windowManager.alert(ed.translate('paste.plaintext_mode_sticky'));
69d05c 134                         } else {
2011be 135                             ed.windowManager.alert(ed.translate('paste.plaintext_mode_sticky'));
69d05c 136                         }
A 137
138                         if (!getParam(ed, "paste_text_notifyalways")) {
139                             cookie.set("tinymcePasteText", "1", new Date(new Date().getFullYear() + 1, 12, 31))
140                         }
141                     }
142                 });
143             }
144
145             ed.addButton('pastetext', {title: 'paste.paste_text_desc', cmd: 'mcePasteText'});
146             ed.addButton('selectall', {title: 'paste.selectall_desc', cmd: 'selectall'});
d9344f 147
29da64 148             // This function grabs the contents from the clipboard by adding a
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) {
a9251b 152                 var n, or, rng, oldRng, sel = ed.selection, dom = ed.dom, body = ed.getBody(), posY, textContent;
2011be 153
A 154                 // Check if browser supports direct plaintext access
a9251b 155                 if (e.clipboardData || dom.doc.dataTransfer) {
T 156                     textContent = (e.clipboardData || dom.doc.dataTransfer).getData('Text');
157
158                     if (ed.pasteAsPlainText) {
159                         e.preventDefault();
160                         process({content : textContent.replace(/\r?\n/g, '<br />')});
161                         return;
162                     }
2011be 163                 }
d9344f 164
29da64 165                 if (dom.get('_mcePaste'))
A 166                     return;
167
168                 // Create container to paste into
a9251b 169                 n = dom.add(body, 'div', {id : '_mcePaste', 'class' : 'mcePaste', 'data-mce-bogus' : '1'}, '\uFEFF\uFEFF');
29da64 170
A 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;
174                 else
a9251b 175                     posY = body.scrollTop + dom.getViewPort().y;
29da64 176
A 177                 // Styles needs to be applied after the element is added to the document since WebKit will otherwise remove all styles
178                 dom.setStyles(n, {
179                     position : 'absolute',
180                     left : -10000,
181                     top : posY,
182                     width : 1,
183                     height : 1,
184                     overflow : 'hidden'
d9344f 185                 });
29da64 186
A 187                 if (tinymce.isIE) {
a9251b 188                     // Store away the old range
T 189                     oldRng = sel.getRng();
190
29da64 191                     // Select the container
A 192                     rng = dom.doc.body.createTextRange();
193                     rng.moveToElementText(n);
194                     rng.execCommand('Paste');
195
196                     // Remove container
197                     dom.remove(n);
198
58fb65 199                     // Check if the contents was changed, if it wasn't then clipboard extraction failed probably due
A 200                     // to IE security settings so we pass the junk though better than nothing right
a9251b 201                     if (n.innerHTML === '\uFEFF\uFEFF') {
58fb65 202                         ed.execCommand('mcePasteWord');
A 203                         e.preventDefault();
204                         return;
205                     }
29da64 206
a9251b 207                     // Restore the old range and clear the contents before pasting
T 208                     sel.setRng(oldRng);
209                     sel.setContent('');
210
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() {
215                         // Process contents
216                         process({content : n.innerHTML});
217                     }, 0);
58fb65 218
A 219                     // Block the real paste event
29da64 220                     return tinymce.dom.Event.cancel(e);
A 221                 } else {
69d05c 222                     function block(e) {
A 223                         e.preventDefault();
224                     };
225
226                     // Block mousedown and click to prevent selection change
227                     dom.bind(ed.getDoc(), 'mousedown', block);
228                     dom.bind(ed.getDoc(), 'keydown', block);
229
29da64 230                     or = ed.selection.getRng();
A 231
a9251b 232                     // Move select contents inside DIV
29da64 233                     n = n.firstChild;
A 234                     rng = ed.getDoc().createRange();
235                     rng.setStart(n, 0);
a9251b 236                     rng.setEnd(n, 2);
29da64 237                     sel.setRng(rng);
A 238
239                     // Wait a while and grab the pasted contents
240                     window.setTimeout(function() {
a9251b 241                         var h = '', nl;
29da64 242
a9251b 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
T 244                         if (!dom.select('div.mcePaste > div.mcePaste').length) {
245                             nl = dom.select('div.mcePaste');
246
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;
250
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);
254                                 }
255
256                                 // Remove apply style spans
257                                 each(dom.select('span.Apple-style-span', n), function(n) {
258                                     dom.remove(n, 1);
259                                 });
260
261                                 // Remove bogus br elements
262                                 each(dom.select('br[data-mce-bogus]', n), function(n) {
263                                     dom.remove(n);
264                                 });
265
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')
268                                     h += n.innerHTML;
69d05c 269                             });
a9251b 270                         } else {
T 271                             // Found WebKit weirdness so force the content into plain text mode
272                             h = '<pre>' + dom.encode(textContent).replace(/\r?\n/g, '<br />') + '</pre>';
273                         }
29da64 274
58fb65 275                         // Remove the nodes
a9251b 276                         each(dom.select('div.mcePaste'), function(n) {
58fb65 277                             dom.remove(n);
A 278                         });
29da64 279
A 280                         // Restore the old selection
281                         if (or)
282                             sel.setRng(or);
283
58fb65 284                         process({content : h});
69d05c 285
A 286                         // Unblock events ones we got the contents
287                         dom.unbind(ed.getDoc(), 'mousedown', block);
288                         dom.unbind(ed.getDoc(), 'keydown', block);
29da64 289                     }, 0);
A 290                 }
69d05c 291             }
29da64 292
A 293             // Check if we should use the new auto process method            
69d05c 294             if (getParam(ed, "paste_auto_cleanup_on_paste")) {
29da64 295                 // Is it's Opera or older FF use key handler
A 296                 if (tinymce.isOpera || /Firefox\/2/.test(navigator.userAgent)) {
a9251b 297                     ed.onKeyDown.addToTop(function(ed, e) {
29da64 298                         if (((tinymce.isMac ? e.metaKey : e.ctrlKey) && e.keyCode == 86) || (e.shiftKey && e.keyCode == 45))
A 299                             grabContent(e);
300                     });
301                 } else {
302                     // Grab contents on paste event on Gecko and WebKit
303                     ed.onPaste.addToTop(function(ed, e) {
304                         return grabContent(e);
305                     });
306                 }
d9344f 307             }
S 308
a9251b 309             ed.onInit.add(function() {
T 310                 ed.controlManager.setActive("pastetext", ed.pasteAsPlainText);
311
312                 // Block all drag/drop events
313                 if (getParam(ed, "paste_block_drop")) {
58fb65 314                     ed.dom.bind(ed.getBody(), ['dragend', 'dragover', 'draggesture', 'dragdrop', 'drop', 'drag'], function(e) {
A 315                         e.preventDefault();
316                         e.stopPropagation();
317
318                         return false;
319                     });
a9251b 320                 }
T 321             });
58fb65 322
29da64 323             // Add legacy support
A 324             t._legacySupport();
d9344f 325         },
S 326
327         getInfo : function() {
328             return {
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
334             };
335         },
336
29da64 337         _preProcess : function(pl, o) {
69d05c 338             var ed = this.editor,
A 339                 h = o.content,
340                 grep = tinymce.grep,
341                 explode = tinymce.explode,
342                 trim = tinymce.trim,
343                 len, stripClass;
a9251b 344
T 345             //console.log('Before preprocess:' + o.content);
d9344f 346
29da64 347             function process(items) {
A 348                 each(items, function(v) {
349                     // Remove or replace
350                     if (v.constructor == RegExp)
351                         h = h.replace(v, '');
352                     else
353                         h = h.replace(v[0], v[1]);
354                 });
69d05c 355             }
a9251b 356             
T 357             if (ed.settings.paste_enable_default_filters == false) {
358                 return;
359             }
360
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>&nbsp;[\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>&nbsp;[\s\r\n]+|<br>)*/g, '$1']]);
d9344f 364
58fb65 365             // Detect Word content and process it more aggressive
69d05c 366             if (/class="?Mso|style="[^"]*\bmso-|w:WordDocument/i.test(h) || o.wordContent) {
A 367                 o.wordContent = true;            // Mark the pasted contents as word specific content
29da64 368                 //console.log('Word contents detected.');
A 369
58fb65 370                 // Process away some basic content
A 371                 process([
69d05c 372                     /^\s*(&nbsp;)+/gi,                // &nbsp; entities at the start of contents
A 373                     /(&nbsp;|<br[^>]*>)+\s*$/gi        // &nbsp; entities at the end of contents
58fb65 374                 ]);
A 375
69d05c 376                 if (getParam(ed, "paste_convert_headers_to_strong")) {
A 377                     h = h.replace(/<p [^>]*class="?MsoHeading"?[^>]*>(.*?)<\/p>/gi, "<p><strong>$1</strong></p>");
378                 }
379
380                 if (getParam(ed, "paste_convert_middot_lists")) {
58fb65 381                     process([
69d05c 382                         [/<!--\[if !supportLists\]-->/gi, '$&__MCE_ITEM__'],                    // Convert supportLists to a list item marker
a9251b 383                         [/(<span[^>]+(?:mso-list:|:\s*symbol)[^>]+>)/gi, '$1__MCE_ITEM__'],        // Convert mso-list and symbol spans to item markers
T 384                         [/(<p[^>]+(?:MsoListParagraph)[^>]+>)/gi, '$1__MCE_ITEM__']                // Convert mso-list and symbol paragraphs to item markers (FF)
58fb65 385                     ]);
A 386                 }
387
29da64 388                 process([
69d05c 389                     // Word comments like conditional comments etc
A 390                     /<!--[\s\S]+?-->/gi,
391
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,
394
395                     // Convert <s> into <strike> for line-though
396                     [/<(\/?)s>/gi, "<$1strike>"],
397
398                     // Replace nsbp entites to char since it's easier to handle
399                     [/&nbsp;/gi, "\u00a0"]
58fb65 400                 ]);
A 401
69d05c 402                 // Remove bad attributes, with or without quotes, ensuring that attribute text is really inside a tag.
A 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.
404                 do {
405                     len = h.length;
406                     h = h.replace(/(<[a-z][^>]*\s)(?:id|name|language|type|on\w+|\w+:\w+)=(?:"[^"]*"|\w+)\s?/gi, "$1");
407                 } while (len != h.length);
408
58fb65 409                 // Remove all spans if no styles is to be retained
69d05c 410                 if (getParam(ed, "paste_retain_style_properties").replace(/^none$/i, "").length == 0) {
A 411                     h = h.replace(/<\/?span[^>]*>/gi, "");
412                 } else {
413                     // We're keeping styles, so at least clean them up.
414                     // CSS Reference: http://msdn.microsoft.com/en-us/library/aa155477.aspx
415
58fb65 416                     process([
69d05c 417                         // Convert <span style="mso-spacerun:yes">___</span> to string of alternating breaking/non-breaking spaces of same length
A 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") : "";
421                             }
422                         ],
423
424                         // Examine all styles: delete junk, transform some, and keep the rest
425                         [/(<[a-z][^>]*)\sstyle="([^"]*)"/gi,
426                             function(str, tag, style) {
427                                 var n = [],
428                                     i = 0,
429                                     s = explode(trim(style).replace(/&quot;/gi, "'"), ";");
430
431                                 // Examine each style definition within the tag's style attribute
432                                 each(s, function(v) {
433                                     var name, value,
434                                         parts = explode(v, ":");
435
436                                     function ensureUnits(v) {
437                                         return v + ((v !== "0") && (/\d$/.test(v)))? "px" : "";
438                                     }
439
440                                     if (parts.length == 2) {
441                                         name = parts[0].toLowerCase();
442                                         value = parts[1].toLowerCase();
443
444                                         // Translate certain MS Office styles into their CSS equivalents
445                                         switch (name) {
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":
457                                             case "mso-height":
458                                             case "mso-width":
459                                             case "mso-vertical-align-alt":
460                                                 n[i++] = name.replace(/^mso-|-alt$/g, "") + ":" + ensureUnits(value);
461                                                 return;
462
463                                             case "horiz-align":
464                                                 n[i++] = "text-align:" + value;
465                                                 return;
466
467                                             case "vert-align":
468                                                 n[i++] = "vertical-align:" + value;
469                                                 return;
470
471                                             case "font-color":
472                                             case "mso-foreground":
473                                                 n[i++] = "color:" + value;
474                                                 return;
475
476                                             case "mso-background":
477                                             case "mso-highlight":
478                                                 n[i++] = "background:" + value;
479                                                 return;
480
481                                             case "mso-default-height":
482                                                 n[i++] = "min-height:" + ensureUnits(value);
483                                                 return;
484
485                                             case "mso-default-width":
486                                                 n[i++] = "min-width:" + ensureUnits(value);
487                                                 return;
488
489                                             case "mso-padding-between-alt":
490                                                 n[i++] = "border-collapse:separate;border-spacing:" + ensureUnits(value);
491                                                 return;
492
493                                             case "text-line-through":
494                                                 if ((value == "single") || (value == "double")) {
495                                                     n[i++] = "text-decoration:line-through";
496                                                 }
497                                                 return;
498
499                                             case "mso-zero-height":
500                                                 if (value == "yes") {
501                                                     n[i++] = "display:none";
502                                                 }
503                                                 return;
504                                         }
505
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)) {
508                                             return;
509                                         }
510
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
513                                     }
514                                 });
515
516                                 // If style attribute contained any valid styles the re-write it; otherwise delete style attribute.
517                                 if (i > 0) {
518                                     return tag + ' style="' + n.join(';') + '"';
519                                 } else {
520                                     return tag;
521                                 }
522                             }
523                         ]
58fb65 524                     ]);
A 525                 }
526             }
527
69d05c 528             // Replace headers with <strong>
A 529             if (getParam(ed, "paste_convert_headers_to_strong")) {
530                 process([
531                     [/<h[1-6][^>]*>/gi, "<p><strong>"],
532                     [/<\/h[1-6][^>]*>/gi, "</strong></p>"]
533                 ]);
534             }
58fb65 535
a9251b 536             process([
T 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, '']
539             ]);
540
69d05c 541             // Class attribute options are: leave all as-is ("none"), remove all ("all"), or remove only those starting with mso ("mso").
A 542             // Note:-  paste_strip_class_attributes: "none", verify_css_classes: true is also a good variation.
543             stripClass = getParam(ed, "paste_strip_class_attributes");
58fb65 544
69d05c 545             if (stripClass !== "none") {
A 546                 function removeClasses(match, g1) {
547                         if (stripClass === "all")
548                             return '';
58fb65 549
69d05c 550                         var cls = grep(explode(g1.replace(/^(["'])(.*)\1$/, "$2"), " "),
A 551                             function(v) {
552                                 return (/^(?!mso)/i.test(v));
553                             }
554                         );
58fb65 555
69d05c 556                         return cls.length ? ' class="' + cls.join(" ") + '"' : '';
58fb65 557                 };
A 558
69d05c 559                 h = h.replace(/ class="([^"]+)"/gi, removeClasses);
a9251b 560                 h = h.replace(/ class=([\-\w]+)/gi, removeClasses);
58fb65 561             }
A 562
563             // Remove spans option
69d05c 564             if (getParam(ed, "paste_remove_spans")) {
A 565                 h = h.replace(/<\/?span[^>]*>/gi, "");
29da64 566             }
A 567
568             //console.log('After preprocess:' + h);
569
570             o.content = h;
d9344f 571         },
S 572
29da64 573         /**
A 574          * Various post process items.
575          */
576         _postProcess : function(pl, o) {
58fb65 577             var t = this, ed = t.editor, dom = ed.dom, styleProps;
18240a 578
a9251b 579             if (ed.settings.paste_enable_default_filters == false) {
T 580                 return;
581             }
582             
29da64 583             if (o.wordContent) {
A 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)
587                         dom.remove(a, 1);
588                 });
d9344f 589
69d05c 590                 if (getParam(ed, "paste_convert_middot_lists")) {
29da64 591                     t._convertLists(pl, o);
69d05c 592                 }
d9344f 593
58fb65 594                 // Process styles
69d05c 595                 styleProps = getParam(ed, "paste_retain_style_properties"); // retained properties
58fb65 596
69d05c 597                 // Process only if a string was specified and not equal to "all" or "*"
A 598                 if ((tinymce.is(styleProps, "string")) && (styleProps !== "all") && (styleProps !== "*")) {
599                     styleProps = tinymce.explode(styleProps.replace(/^none$/i, ""));
58fb65 600
69d05c 601                     // Retains some style properties
A 602                     each(dom.select('*', o.node), function(el) {
603                         var newStyle = {}, npc = 0, i, sp, sv;
58fb65 604
69d05c 605                         // Store a subset of the existing styles
A 606                         if (styleProps) {
607                             for (i = 0; i < styleProps.length; i++) {
608                                 sp = styleProps[i];
609                                 sv = dom.getStyle(el, sp);
58fb65 610
69d05c 611                                 if (sv) {
A 612                                     newStyle[sp] = sv;
613                                     npc++;
614                                 }
58fb65 615                             }
A 616                         }
617
69d05c 618                         // Remove all of the existing styles
A 619                         dom.setAttrib(el, 'style', '');
58fb65 620
69d05c 621                         if (styleProps && npc > 0)
A 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);
626                     });
627                 }
29da64 628             }
d9344f 629
58fb65 630             // Remove all style information or only specifically on WebKit to avoid the style bug on that browser
69d05c 631             if (getParam(ed, "paste_remove_styles") || (getParam(ed, "paste_remove_styles_if_webkit") && tinymce.isWebKit)) {
58fb65 632                 each(dom.select('*[style]', o.node), function(el) {
A 633                     el.removeAttribute('style');
a9251b 634                     el.removeAttribute('data-mce-style');
29da64 635                 });
58fb65 636             } else {
A 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) {
a9251b 641                         el.removeAttribute('data-mce-style');
58fb65 642                     });
A 643                 }
d9344f 644             }
S 645         },
646
29da64 647         /**
A 648          * Converts the most common bullet and number formats in Office into a real semantic UL/LI list.
649          */
650         _convertLists : function(pl, o) {
58fb65 651             var dom = pl.editor.dom, listElm, li, lastMargin = -1, margin, levels = [], lastType, html;
29da64 652
58fb65 653             // Convert middot lists into real semantic lists
29da64 654             each(dom.select('p', o.node), function(p) {
A 655                 var sib, val = '', type, html, idx, parents;
656
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;
660
58fb65 661                 val = p.innerHTML.replace(/<\/?\w+[^>]*>/gi, '').replace(/&nbsp;/g, '\u00a0');
A 662
29da64 663                 // Detect unordered lists look for bullets
a9251b 664                 if (/^(__MCE_ITEM__)+[\u2022\u00b7\u00a7\u00d8o\u25CF]\s*\u00a0*/.test(val))
29da64 665                     type = 'ul';
A 666
667                 // Detect ordered lists 1., a. or ixv.
a9251b 668                 if (/^__MCE_ITEM__\s*\w+\.\s*\u00a0+/.test(val))
29da64 669                     type = 'ol';
A 670
671                 // Check if node value matches the list pattern: o&nbsp;&nbsp;
672                 if (type) {
673                     margin = parseFloat(p.style.marginLeft || 0);
674
675                     if (margin > lastMargin)
676                         levels.push(margin);
677
678                     if (!listElm || type != lastType) {
679                         listElm = dom.create(type);
680                         dom.insertAfter(listElm, p);
681                     } else {
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;
690                         }
691                     }
692
58fb65 693                     // Remove middot or number spans if they exists
A 694                     each(dom.select('span', p), function(span) {
695                         var html = span.innerHTML.replace(/<\/?\w+[^>]*>/gi, '');
29da64 696
58fb65 697                         // Remove span with the middot or the number
a9251b 698                         if (type == 'ul' && /^__MCE_ITEM__[\u2022\u00b7\u00a7\u00d8o\u25CF]/.test(html))
58fb65 699                             dom.remove(span);
a9251b 700                         else if (/^__MCE_ITEM__[\s\S]*\w+\.(&nbsp;|\u00a0)*\s*/.test(html))
58fb65 701                             dom.remove(span);
A 702                     });
703
704                     html = p.innerHTML;
705
706                     // Remove middot/list items
707                     if (type == 'ul')
a9251b 708                         html = p.innerHTML.replace(/__MCE_ITEM__/g, '').replace(/^[\u2022\u00b7\u00a7\u00d8o\u25CF]\s*(&nbsp;|\u00a0)+\s*/, '');
58fb65 709                     else
A 710                         html = p.innerHTML.replace(/__MCE_ITEM__/g, '').replace(/^\s*\w+\.(&nbsp;|\u00a0)+\s*/, '');
711
712                     // Create li and add paragraph data into the new li
29da64 713                     li = listElm.appendChild(dom.create('li', 0, html));
A 714                     dom.remove(p);
715
716                     lastMargin = margin;
717                     lastType = type;
718                 } else
719                     listElm = lastMargin = 0; // End list element
720             });
58fb65 721
A 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, '');
29da64 726         },
A 727
728         /**
729          * Inserts the specified contents at the caret position.
730          */
731         _insert : function(h, skip_undo) {
2011be 732             var ed = this.editor, r = ed.selection.getRng();
29da64 733
2011be 734             // First delete the contents seems to work better on WebKit when the selection spans multiple list items or multiple table cells.
A 735             if (!ed.selection.isCollapsed() && r.startContainer != r.endContainer)
58fb65 736                 ed.getDoc().execCommand('Delete', false, null);
29da64 737
a9251b 738             ed.execCommand('mceInsertContent', false, h, {skip_undo : skip_undo});
29da64 739         },
A 740
741         /**
69d05c 742          * Instead of the old plain text method which tried to re-create a paste operation, the
A 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
749          */
750         _insertPlainText : function(ed, dom, h) {
751             var i, len, pos, rpos, node, breakElms, before, after,
752                 w = ed.getWin(),
753                 d = ed.getDoc(),
754                 sel = ed.selection,
755                 is = tinymce.is,
756                 inArray = tinymce.inArray,
757                 linebr = getParam(ed, "paste_text_linebreaktype"),
758                 rl = getParam(ed, "paste_text_replacements");
759
760             function process(items) {
761                 each(items, function(v) {
762                     if (v.constructor == RegExp)
763                         h = h.replace(v, "");
764                     else
765                         h = h.replace(v[0], v[1]);
766                 });
767             };
768
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)) {
772                     process([
773                         /[\n\r]+/g
774                     ]);
775                 } else {
776                     // Otherwise just get rid of carriage returns (only need linefeeds)
777                     process([
778                         /\r+/g
779                     ]);
780                 }
781
782                 process([
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                     [/&nbsp;/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
791                 ]);
792
a9251b 793                 h = dom.decode(tinymce.html.Entities.encodeRaw(h));
69d05c 794
A 795                 // Delete any highlighted text before pasting
796                 if (!sel.isCollapsed()) {
797                     d.execCommand("Delete", false, null);
798                 }
799
800                 // Perform default or custom replacements
801                 if (is(rl, "array") || (is(rl, "array"))) {
802                     process(rl);
803                 }
804                 else if (is(rl, "string")) {
805                     process(new RegExp(rl, "gi"));
806                 }
807
808                 // Treat paragraphs as specified in the config
809                 if (linebr == "none") {
810                     process([
811                         [/\n+/g, " "]
812                     ]);
813                 }
814                 else if (linebr == "br") {
815                     process([
816                         [/\n/g, "<br />"]
817                     ]);
818                 }
819                 else {
820                     process([
821                         /^\s+|\s+$/g,
822                         [/\n\n/g, "</p><p>"],
823                         [/\n/g, "<br />"]
824                     ]);
825                 }
826
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 
839
840                     do {
841                         if (node.nodeType == 1) {
842                             // Don't break tables and break at body
843                             if (node.nodeName == "TD" || node.nodeName == "BODY") {
844                                 break;
845                             }
846
847                             breakElms[breakElms.length] = node;
848                         }
849                     } while (node = node.parentNode);
850
851                     // Are we in the middle of a block node?
852                     if (breakElms.length > 0) {
853                         before = h.substring(0, pos);
854                         after = "";
855
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() + ">";
859                         }
860
861                         if (pos == rpos) {
862                             h = before + after + h.substring(pos+7);
863                         }
864                         else {
865                             h = before + h.substring(pos+4, rpos+4) + after + h.substring(rpos+7);
866                         }
867                     }
868                 }
869
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">&nbsp;</span>');
872
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;
880
881                     sel.select(marker, false);
882                     d.execCommand("Delete", false, null);
883                     marker = null;
884
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;
890
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;
894                     }
895                 }, 0);
896             }
897         },
898
899         /**
29da64 900          * This method will open the old style paste dialogs. Some users might want the old behavior but still use the new cleanup engine.
A 901          */
902         _legacySupport : function() {
d9344f 903             var t = this, ed = t.editor;
S 904
69d05c 905             // Register command(s) for backwards compatibility
A 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")),
911                     inline: 1
29da64 912                 });
A 913             });
d9344f 914
69d05c 915             if (getParam(ed, "paste_text_use_dialog")) {
A 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")),
921                         inline : 1
922                     });
923                 });
924             }
925
926             // Register button for backwards compatibility
927             ed.addButton("pasteword", {title : "paste.paste_word_desc", cmd : "mcePasteWord"});
d9344f 928         }
S 929     });
930
931     // Register plugin
69d05c 932     tinymce.PluginManager.add("paste", tinymce.plugins.PastePlugin);
A 933 })();