PageRenderTime 88ms CodeModel.GetById 14ms app.highlight 64ms RepoModel.GetById 2ms app.codeStats 0ms

/BlogEngine/BlogEngine.NET/editors/tiny_mce_3_4_3_1/plugins/paste/editor_plugin_src.js

#
JavaScript | 941 lines | 757 code | 88 blank | 96 comment | 106 complexity | 2caede40468244e2403392c5a2a4d902 MD5 | raw file
  1/**
  2 * editor_plugin_src.js
  3 *
  4 * Copyright 2009, Moxiecode Systems AB
  5 * Released under LGPL License.
  6 *
  7 * License: http://tinymce.moxiecode.com/license
  8 * Contributing: http://tinymce.moxiecode.com/contributing
  9 */
 10
 11(function() {
 12	var each = tinymce.each,
 13		defs = {
 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 : [
 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	}
 41
 42	tinymce.create('tinymce.plugins.PastePlugin', {
 43		init : function(ed, url) {
 44			var t = this;
 45
 46			t.editor = ed;
 47			t.url = url;
 48
 49			// Setup plugin events
 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);
 60			});
 61
 62			// Register optional postprocess
 63			t.onPostProcess.add(function(pl, o) {
 64				ed.execCallback('paste_postprocess', pl, o);
 65			});
 66
 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
 71			});
 72
 73			// Initialize plain text flag
 74			ed.pasteAsPlainText = getParam(ed, 'paste_text_sticky_default');
 75
 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;
 80
 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);
 86
 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						// Is only one block node and it doesn't contain word stuff
 93						if (o.node.childNodes.length === 1 && /^(p|h[1-6]|pre)$/i.test(o.node.firstChild.nodeName) && o.content.indexOf('__MCE_ITEM__') === -1)
 94							dom.remove(o.node.firstChild, true);
 95					}
 96				}
 97
 98				// Execute post process handlers
 99				t.onPostProcess.dispatch(t, o);
100
101				// Serialize content
102				o.content = ed.serializer.serialize(o.node, {getInner : 1, forced_root_block : ''});
103
104				// Plain text option active?
105				if ((!force_rich) && (ed.pasteAsPlainText)) {
106					t._insertPlainText(ed, dom, o.content);
107
108					if (!getParam(ed, "paste_text_sticky")) {
109						ed.pasteAsPlainText = false;
110						ed.controlManager.setActive("pastetext", false);
111					}
112				} else {
113					t._insert(o.content);
114				}
115			}
116
117			// Add command for external usage
118			ed.addCommand('mceInsertClipboardContent', function(u, o) {
119				process(o, true);
120			});
121
122			if (!getParam(ed, "paste_text_use_dialog")) {
123				ed.addCommand('mcePasteText', function(u, v) {
124					var cookie = tinymce.util.Cookie;
125
126					ed.pasteAsPlainText = !ed.pasteAsPlainText;
127					ed.controlManager.setActive('pastetext', ed.pasteAsPlainText);
128
129					if ((ed.pasteAsPlainText) && (!cookie.get("tinymcePasteText"))) {
130						if (getParam(ed, "paste_text_sticky")) {
131							ed.windowManager.alert(ed.translate('paste.plaintext_mode_sticky'));
132						} else {
133							ed.windowManager.alert(ed.translate('paste.plaintext_mode_sticky'));
134						}
135
136						if (!getParam(ed, "paste_text_notifyalways")) {
137							cookie.set("tinymcePasteText", "1", new Date(new Date().getFullYear() + 1, 12, 31))
138						}
139					}
140				});
141			}
142
143			ed.addButton('pastetext', {title: 'paste.paste_text_desc', cmd: 'mcePasteText'});
144			ed.addButton('selectall', {title: 'paste.selectall_desc', cmd: 'selectall'});
145
146			// This function grabs the contents from the clipboard by adding a
147			// hidden div and placing the caret inside it and after the browser paste
148			// is done it grabs that contents and processes that
149			function grabContent(e) {
150				var n, or, rng, oldRng, sel = ed.selection, dom = ed.dom, body = ed.getBody(), posY, textContent;
151
152				// Check if browser supports direct plaintext access
153				if (e.clipboardData || dom.doc.dataTransfer) {
154					textContent = (e.clipboardData || dom.doc.dataTransfer).getData('Text');
155
156					if (ed.pasteAsPlainText) {
157						e.preventDefault();
158						process({content : textContent.replace(/\r?\n/g, '<br />')});
159						return;
160					}
161				}
162
163				if (dom.get('_mcePaste'))
164					return;
165
166				// Create container to paste into
167				n = dom.add(body, 'div', {id : '_mcePaste', 'class' : 'mcePaste', 'data-mce-bogus' : '1'}, '\uFEFF\uFEFF');
168
169				// If contentEditable mode we need to find out the position of the closest element
170				if (body != ed.getDoc().body)
171					posY = dom.getPos(ed.selection.getStart(), body).y;
172				else
173					posY = body.scrollTop + dom.getViewPort(ed.getWin()).y;
174
175				// Styles needs to be applied after the element is added to the document since WebKit will otherwise remove all styles
176				// If also needs to be in view on IE or the paste would fail
177				dom.setStyles(n, {
178					position : 'absolute',
179					left : tinymce.isGecko ? -40 : 0, // Need to move it out of site on Gecko since it will othewise display a ghost resize rect for the div
180					top : posY - 25,
181					width : 1,
182					height : 1,
183					overflow : 'hidden'
184				});
185
186				if (tinymce.isIE) {
187					// Store away the old range
188					oldRng = sel.getRng();
189
190					// Select the container
191					rng = dom.doc.body.createTextRange();
192					rng.moveToElementText(n);
193					rng.execCommand('Paste');
194
195					// Remove container
196					dom.remove(n);
197
198					// Check if the contents was changed, if it wasn't then clipboard extraction failed probably due
199					// to IE security settings so we pass the junk though better than nothing right
200					if (n.innerHTML === '\uFEFF\uFEFF') {
201						ed.execCommand('mcePasteWord');
202						e.preventDefault();
203						return;
204					}
205
206					// Restore the old range and clear the contents before pasting
207					sel.setRng(oldRng);
208					sel.setContent('');
209
210					// For some odd reason we need to detach the the mceInsertContent call from the paste event
211					// It's like IE has a reference to the parent element that you paste in and the selection gets messed up
212					// when it tries to restore the selection
213					setTimeout(function() {
214						// Process contents
215						process({content : n.innerHTML});
216					}, 0);
217
218					// Block the real paste event
219					return tinymce.dom.Event.cancel(e);
220				} else {
221					function block(e) {
222						e.preventDefault();
223					};
224
225					// Block mousedown and click to prevent selection change
226					dom.bind(ed.getDoc(), 'mousedown', block);
227					dom.bind(ed.getDoc(), 'keydown', block);
228
229					or = ed.selection.getRng();
230
231					// Move select contents inside DIV
232					n = n.firstChild;
233					rng = ed.getDoc().createRange();
234					rng.setStart(n, 0);
235					rng.setEnd(n, 2);
236					sel.setRng(rng);
237
238					// Wait a while and grab the pasted contents
239					window.setTimeout(function() {
240						var h = '', nl;
241
242						// Paste divs duplicated in paste divs seems to happen when you paste plain text so lets first look for that broken behavior in WebKit
243						if (!dom.select('div.mcePaste > div.mcePaste').length) {
244							nl = dom.select('div.mcePaste');
245
246							// WebKit will split the div into multiple ones so this will loop through then all and join them to get the whole HTML string
247							each(nl, function(n) {
248								var child = n.firstChild;
249
250								// WebKit inserts a DIV container with lots of odd styles
251								if (child && child.nodeName == 'DIV' && child.style.marginTop && child.style.backgroundColor) {
252									dom.remove(child, 1);
253								}
254
255								// Remove apply style spans
256								each(dom.select('span.Apple-style-span', n), function(n) {
257									dom.remove(n, 1);
258								});
259
260								// Remove bogus br elements
261								each(dom.select('br[data-mce-bogus]', n), function(n) {
262									dom.remove(n);
263								});
264
265								// WebKit will make a copy of the DIV for each line of plain text pasted and insert them into the DIV
266								if (n.parentNode.className != 'mcePaste')
267									h += n.innerHTML;
268							});
269						} else {
270							// Found WebKit weirdness so force the content into plain text mode
271							h = '<pre>' + dom.encode(textContent).replace(/\r?\n/g, '<br />') + '</pre>';
272						}
273
274						// Remove the nodes
275						each(dom.select('div.mcePaste'), function(n) {
276							dom.remove(n);
277						});
278
279						// Restore the old selection
280						if (or)
281							sel.setRng(or);
282
283						process({content : h});
284
285						// Unblock events ones we got the contents
286						dom.unbind(ed.getDoc(), 'mousedown', block);
287						dom.unbind(ed.getDoc(), 'keydown', block);
288					}, 0);
289				}
290			}
291
292			// Check if we should use the new auto process method			
293			if (getParam(ed, "paste_auto_cleanup_on_paste")) {
294				// Is it's Opera or older FF use key handler
295				if (tinymce.isOpera || /Firefox\/2/.test(navigator.userAgent)) {
296					ed.onKeyDown.addToTop(function(ed, e) {
297						if (((tinymce.isMac ? e.metaKey : e.ctrlKey) && e.keyCode == 86) || (e.shiftKey && e.keyCode == 45))
298							grabContent(e);
299					});
300				} else {
301					// Grab contents on paste event on Gecko and WebKit
302					ed.onPaste.addToTop(function(ed, e) {
303						return grabContent(e);
304					});
305				}
306			}
307
308			ed.onInit.add(function() {
309				ed.controlManager.setActive("pastetext", ed.pasteAsPlainText);
310
311				// Block all drag/drop events
312				if (getParam(ed, "paste_block_drop")) {
313					ed.dom.bind(ed.getBody(), ['dragend', 'dragover', 'draggesture', 'dragdrop', 'drop', 'drag'], function(e) {
314						e.preventDefault();
315						e.stopPropagation();
316
317						return false;
318					});
319				}
320			});
321
322			// Add legacy support
323			t._legacySupport();
324		},
325
326		getInfo : function() {
327			return {
328				longname : 'Paste text/word',
329				author : 'Moxiecode Systems AB',
330				authorurl : 'http://tinymce.moxiecode.com',
331				infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/paste',
332				version : tinymce.majorVersion + "." + tinymce.minorVersion
333			};
334		},
335
336		_preProcess : function(pl, o) {
337			var ed = this.editor,
338				h = o.content,
339				grep = tinymce.grep,
340				explode = tinymce.explode,
341				trim = tinymce.trim,
342				len, stripClass;
343
344			//console.log('Before preprocess:' + o.content);
345
346			function process(items) {
347				each(items, function(v) {
348					// Remove or replace
349					if (v.constructor == RegExp)
350						h = h.replace(v, '');
351					else
352						h = h.replace(v[0], v[1]);
353				});
354			}
355			
356			if (ed.settings.paste_enable_default_filters == false) {
357				return;
358			}
359
360			// IE9 adds BRs before/after block elements when contents is pasted from word or for example another browser
361			if (tinymce.isIE && document.documentMode >= 9) {
362				// IE9 adds BRs before/after block elements when contents is pasted from word or for example another browser
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']]);
364
365				// IE9 also adds an extra BR element for each soft-linefeed and it also adds a BR for each word wrap break
366				process([
367					[/<br><br>/g, '<BR><BR>'], // Replace multiple BR elements with uppercase BR to keep them intact
368					[/<br>/g, ' '], // Replace single br elements with space since they are word wrap BR:s
369					[/<BR><BR>/g, '<br>'], // Replace back the double brs but into a single BR
370				]);
371			}
372
373			// Detect Word content and process it more aggressive
374			if (/class="?Mso|style="[^"]*\bmso-|w:WordDocument/i.test(h) || o.wordContent) {
375				o.wordContent = true;			// Mark the pasted contents as word specific content
376				//console.log('Word contents detected.');
377
378				// Process away some basic content
379				process([
380					/^\s*(&nbsp;)+/gi,				// &nbsp; entities at the start of contents
381					/(&nbsp;|<br[^>]*>)+\s*$/gi		// &nbsp; entities at the end of contents
382				]);
383
384				if (getParam(ed, "paste_convert_headers_to_strong")) {
385					h = h.replace(/<p [^>]*class="?MsoHeading"?[^>]*>(.*?)<\/p>/gi, "<p><strong>$1</strong></p>");
386				}
387
388				if (getParam(ed, "paste_convert_middot_lists")) {
389					process([
390						[/<!--\[if !supportLists\]-->/gi, '$&__MCE_ITEM__'],					// Convert supportLists to a list item marker
391						[/(<span[^>]+(?:mso-list:|:\s*symbol)[^>]+>)/gi, '$1__MCE_ITEM__'],		// Convert mso-list and symbol spans to item markers
392						[/(<p[^>]+(?:MsoListParagraph)[^>]+>)/gi, '$1__MCE_ITEM__']				// Convert mso-list and symbol paragraphs to item markers (FF)
393					]);
394				}
395
396				process([
397					// Word comments like conditional comments etc
398					/<!--[\s\S]+?-->/gi,
399
400					// Remove comments, scripts (e.g., msoShowComment), XML tag, VML content, MS Office namespaced tags, and a few other tags
401					/<(!|script[^>]*>.*?<\/script(?=[>\s])|\/?(\?xml(:\w+)?|img|meta|link|style|\w:\w+)(?=[\s\/>]))[^>]*>/gi,
402
403					// Convert <s> into <strike> for line-though
404					[/<(\/?)s>/gi, "<$1strike>"],
405
406					// Replace nsbp entites to char since it's easier to handle
407					[/&nbsp;/gi, "\u00a0"]
408				]);
409
410				// Remove bad attributes, with or without quotes, ensuring that attribute text is really inside a tag.
411				// 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.
412				do {
413					len = h.length;
414					h = h.replace(/(<[a-z][^>]*\s)(?:id|name|language|type|on\w+|\w+:\w+)=(?:"[^"]*"|\w+)\s?/gi, "$1");
415				} while (len != h.length);
416
417				// Remove all spans if no styles is to be retained
418				if (getParam(ed, "paste_retain_style_properties").replace(/^none$/i, "").length == 0) {
419					h = h.replace(/<\/?span[^>]*>/gi, "");
420				} else {
421					// We're keeping styles, so at least clean them up.
422					// CSS Reference: http://msdn.microsoft.com/en-us/library/aa155477.aspx
423
424					process([
425						// Convert <span style="mso-spacerun:yes">___</span> to string of alternating breaking/non-breaking spaces of same length
426						[/<span\s+style\s*=\s*"\s*mso-spacerun\s*:\s*yes\s*;?\s*"\s*>([\s\u00a0]*)<\/span>/gi,
427							function(str, spaces) {
428								return (spaces.length > 0)? spaces.replace(/./, " ").slice(Math.floor(spaces.length/2)).split("").join("\u00a0") : "";
429							}
430						],
431
432						// Examine all styles: delete junk, transform some, and keep the rest
433						[/(<[a-z][^>]*)\sstyle="([^"]*)"/gi,
434							function(str, tag, style) {
435								var n = [],
436									i = 0,
437									s = explode(trim(style).replace(/&quot;/gi, "'"), ";");
438
439								// Examine each style definition within the tag's style attribute
440								each(s, function(v) {
441									var name, value,
442										parts = explode(v, ":");
443
444									function ensureUnits(v) {
445										return v + ((v !== "0") && (/\d$/.test(v)))? "px" : "";
446									}
447
448									if (parts.length == 2) {
449										name = parts[0].toLowerCase();
450										value = parts[1].toLowerCase();
451
452										// Translate certain MS Office styles into their CSS equivalents
453										switch (name) {
454											case "mso-padding-alt":
455											case "mso-padding-top-alt":
456											case "mso-padding-right-alt":
457											case "mso-padding-bottom-alt":
458											case "mso-padding-left-alt":
459											case "mso-margin-alt":
460											case "mso-margin-top-alt":
461											case "mso-margin-right-alt":
462											case "mso-margin-bottom-alt":
463											case "mso-margin-left-alt":
464											case "mso-table-layout-alt":
465											case "mso-height":
466											case "mso-width":
467											case "mso-vertical-align-alt":
468												n[i++] = name.replace(/^mso-|-alt$/g, "") + ":" + ensureUnits(value);
469												return;
470
471											case "horiz-align":
472												n[i++] = "text-align:" + value;
473												return;
474
475											case "vert-align":
476												n[i++] = "vertical-align:" + value;
477												return;
478
479											case "font-color":
480											case "mso-foreground":
481												n[i++] = "color:" + value;
482												return;
483
484											case "mso-background":
485											case "mso-highlight":
486												n[i++] = "background:" + value;
487												return;
488
489											case "mso-default-height":
490												n[i++] = "min-height:" + ensureUnits(value);
491												return;
492
493											case "mso-default-width":
494												n[i++] = "min-width:" + ensureUnits(value);
495												return;
496
497											case "mso-padding-between-alt":
498												n[i++] = "border-collapse:separate;border-spacing:" + ensureUnits(value);
499												return;
500
501											case "text-line-through":
502												if ((value == "single") || (value == "double")) {
503													n[i++] = "text-decoration:line-through";
504												}
505												return;
506
507											case "mso-zero-height":
508												if (value == "yes") {
509													n[i++] = "display:none";
510												}
511												return;
512										}
513
514										// Eliminate all MS Office style definitions that have no CSS equivalent by examining the first characters in the name
515										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)) {
516											return;
517										}
518
519										// If it reached this point, it must be a valid CSS style
520										n[i++] = name + ":" + parts[1];		// Lower-case name, but keep value case
521									}
522								});
523
524								// If style attribute contained any valid styles the re-write it; otherwise delete style attribute.
525								if (i > 0) {
526									return tag + ' style="' + n.join(';') + '"';
527								} else {
528									return tag;
529								}
530							}
531						]
532					]);
533				}
534			}
535
536			// Replace headers with <strong>
537			if (getParam(ed, "paste_convert_headers_to_strong")) {
538				process([
539					[/<h[1-6][^>]*>/gi, "<p><strong>"],
540					[/<\/h[1-6][^>]*>/gi, "</strong></p>"]
541				]);
542			}
543
544			process([
545				// Copy paste from Java like Open Office will produce this junk on FF
546				[/Version:[\d.]+\nStartHTML:\d+\nEndHTML:\d+\nStartFragment:\d+\nEndFragment:\d+/gi, '']
547			]);
548
549			// Class attribute options are: leave all as-is ("none"), remove all ("all"), or remove only those starting with mso ("mso").
550			// Note:-  paste_strip_class_attributes: "none", verify_css_classes: true is also a good variation.
551			stripClass = getParam(ed, "paste_strip_class_attributes");
552
553			if (stripClass !== "none") {
554				function removeClasses(match, g1) {
555						if (stripClass === "all")
556							return '';
557
558						var cls = grep(explode(g1.replace(/^(["'])(.*)\1$/, "$2"), " "),
559							function(v) {
560								return (/^(?!mso)/i.test(v));
561							}
562						);
563
564						return cls.length ? ' class="' + cls.join(" ") + '"' : '';
565				};
566
567				h = h.replace(/ class="([^"]+)"/gi, removeClasses);
568				h = h.replace(/ class=([\-\w]+)/gi, removeClasses);
569			}
570
571			// Remove spans option
572			if (getParam(ed, "paste_remove_spans")) {
573				h = h.replace(/<\/?span[^>]*>/gi, "");
574			}
575
576			//console.log('After preprocess:' + h);
577
578			o.content = h;
579		},
580
581		/**
582		 * Various post process items.
583		 */
584		_postProcess : function(pl, o) {
585			var t = this, ed = t.editor, dom = ed.dom, styleProps;
586
587			if (ed.settings.paste_enable_default_filters == false) {
588				return;
589			}
590			
591			if (o.wordContent) {
592				// Remove named anchors or TOC links
593				each(dom.select('a', o.node), function(a) {
594					if (!a.href || a.href.indexOf('#_Toc') != -1)
595						dom.remove(a, 1);
596				});
597
598				if (getParam(ed, "paste_convert_middot_lists")) {
599					t._convertLists(pl, o);
600				}
601
602				// Process styles
603				styleProps = getParam(ed, "paste_retain_style_properties"); // retained properties
604
605				// Process only if a string was specified and not equal to "all" or "*"
606				if ((tinymce.is(styleProps, "string")) && (styleProps !== "all") && (styleProps !== "*")) {
607					styleProps = tinymce.explode(styleProps.replace(/^none$/i, ""));
608
609					// Retains some style properties
610					each(dom.select('*', o.node), function(el) {
611						var newStyle = {}, npc = 0, i, sp, sv;
612
613						// Store a subset of the existing styles
614						if (styleProps) {
615							for (i = 0; i < styleProps.length; i++) {
616								sp = styleProps[i];
617								sv = dom.getStyle(el, sp);
618
619								if (sv) {
620									newStyle[sp] = sv;
621									npc++;
622								}
623							}
624						}
625
626						// Remove all of the existing styles
627						dom.setAttrib(el, 'style', '');
628
629						if (styleProps && npc > 0)
630							dom.setStyles(el, newStyle); // Add back the stored subset of styles
631						else // Remove empty span tags that do not have class attributes
632							if (el.nodeName == 'SPAN' && !el.className)
633								dom.remove(el, true);
634					});
635				}
636			}
637
638			// Remove all style information or only specifically on WebKit to avoid the style bug on that browser
639			if (getParam(ed, "paste_remove_styles") || (getParam(ed, "paste_remove_styles_if_webkit") && tinymce.isWebKit)) {
640				each(dom.select('*[style]', o.node), function(el) {
641					el.removeAttribute('style');
642					el.removeAttribute('data-mce-style');
643				});
644			} else {
645				if (tinymce.isWebKit) {
646					// 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 ..." />
647					// Removing the mce_style that contains the real value will force the Serializer engine to compress the styles
648					each(dom.select('*', o.node), function(el) {
649						el.removeAttribute('data-mce-style');
650					});
651				}
652			}
653		},
654
655		/**
656		 * Converts the most common bullet and number formats in Office into a real semantic UL/LI list.
657		 */
658		_convertLists : function(pl, o) {
659			var dom = pl.editor.dom, listElm, li, lastMargin = -1, margin, levels = [], lastType, html;
660
661			// Convert middot lists into real semantic lists
662			each(dom.select('p', o.node), function(p) {
663				var sib, val = '', type, html, idx, parents;
664
665				// Get text node value at beginning of paragraph
666				for (sib = p.firstChild; sib && sib.nodeType == 3; sib = sib.nextSibling)
667					val += sib.nodeValue;
668
669				val = p.innerHTML.replace(/<\/?\w+[^>]*>/gi, '').replace(/&nbsp;/g, '\u00a0');
670
671				// Detect unordered lists look for bullets
672				if (/^(__MCE_ITEM__)+[\u2022\u00b7\u00a7\u00d8o\u25CF]\s*\u00a0*/.test(val))
673					type = 'ul';
674
675				// Detect ordered lists 1., a. or ixv.
676				if (/^__MCE_ITEM__\s*\w+\.\s*\u00a0+/.test(val))
677					type = 'ol';
678
679				// Check if node value matches the list pattern: o&nbsp;&nbsp;
680				if (type) {
681					margin = parseFloat(p.style.marginLeft || 0);
682
683					if (margin > lastMargin)
684						levels.push(margin);
685
686					if (!listElm || type != lastType) {
687						listElm = dom.create(type);
688						dom.insertAfter(listElm, p);
689					} else {
690						// Nested list element
691						if (margin > lastMargin) {
692							listElm = li.appendChild(dom.create(type));
693						} else if (margin < lastMargin) {
694							// Find parent level based on margin value
695							idx = tinymce.inArray(levels, margin);
696							parents = dom.getParents(listElm.parentNode, type);
697							listElm = parents[parents.length - 1 - idx] || listElm;
698						}
699					}
700
701					// Remove middot or number spans if they exists
702					each(dom.select('span', p), function(span) {
703						var html = span.innerHTML.replace(/<\/?\w+[^>]*>/gi, '');
704
705						// Remove span with the middot or the number
706						if (type == 'ul' && /^__MCE_ITEM__[\u2022\u00b7\u00a7\u00d8o\u25CF]/.test(html))
707							dom.remove(span);
708						else if (/^__MCE_ITEM__[\s\S]*\w+\.(&nbsp;|\u00a0)*\s*/.test(html))
709							dom.remove(span);
710					});
711
712					html = p.innerHTML;
713
714					// Remove middot/list items
715					if (type == 'ul')
716						html = p.innerHTML.replace(/__MCE_ITEM__/g, '').replace(/^[\u2022\u00b7\u00a7\u00d8o\u25CF]\s*(&nbsp;|\u00a0)+\s*/, '');
717					else
718						html = p.innerHTML.replace(/__MCE_ITEM__/g, '').replace(/^\s*\w+\.(&nbsp;|\u00a0)+\s*/, '');
719
720					// Create li and add paragraph data into the new li
721					li = listElm.appendChild(dom.create('li', 0, html));
722					dom.remove(p);
723
724					lastMargin = margin;
725					lastType = type;
726				} else
727					listElm = lastMargin = 0; // End list element
728			});
729
730			// Remove any left over makers
731			html = o.node.innerHTML;
732			if (html.indexOf('__MCE_ITEM__') != -1)
733				o.node.innerHTML = html.replace(/__MCE_ITEM__/g, '');
734		},
735
736		/**
737		 * Inserts the specified contents at the caret position.
738		 */
739		_insert : function(h, skip_undo) {
740			var ed = this.editor, r = ed.selection.getRng();
741
742			// First delete the contents seems to work better on WebKit when the selection spans multiple list items or multiple table cells.
743			if (!ed.selection.isCollapsed() && r.startContainer != r.endContainer)
744				ed.getDoc().execCommand('Delete', false, null);
745
746			ed.execCommand('mceInsertContent', false, h, {skip_undo : skip_undo});
747		},
748
749		/**
750		 * Instead of the old plain text method which tried to re-create a paste operation, the
751		 * new approach adds a plain text mode toggle switch that changes the behavior of paste.
752		 * This function is passed the same input that the regular paste plugin produces.
753		 * It performs additional scrubbing and produces (and inserts) the plain text.
754		 * This approach leverages all of the great existing functionality in the paste
755		 * plugin, and requires minimal changes to add the new functionality.
756		 * Speednet - June 2009
757		 */
758		_insertPlainText : function(ed, dom, h) {
759			var i, len, pos, rpos, node, breakElms, before, after,
760				w = ed.getWin(),
761				d = ed.getDoc(),
762				sel = ed.selection,
763				is = tinymce.is,
764				inArray = tinymce.inArray,
765				linebr = getParam(ed, "paste_text_linebreaktype"),
766				rl = getParam(ed, "paste_text_replacements");
767
768			function process(items) {
769				each(items, function(v) {
770					if (v.constructor == RegExp)
771						h = h.replace(v, "");
772					else
773						h = h.replace(v[0], v[1]);
774				});
775			};
776
777			if ((typeof(h) === "string") && (h.length > 0)) {
778				// If HTML content with line-breaking tags, then remove all cr/lf chars because only tags will break a line
779				if (/<(?:p|br|h[1-6]|ul|ol|dl|table|t[rdh]|div|blockquote|fieldset|pre|address|center)[^>]*>/i.test(h)) {
780					process([
781						/[\n\r]+/g
782					]);
783				} else {
784					// Otherwise just get rid of carriage returns (only need linefeeds)
785					process([
786						/\r+/g
787					]);
788				}
789
790				process([
791					[/<\/(?: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
792					[/<br[^>]*>|<\/tr>/gi, "\n"],				// Single linebreak for <br /> tags and table rows
793					[/<\/t[dh]>\s*<t[dh][^>]*>/gi, "\t"],		// Table cells get tabs betweem them
794					/<[a-z!\/?][^>]*>/gi,						// Delete all remaining tags
795					[/&nbsp;/gi, " "],							// Convert non-break spaces to regular spaces (remember, *plain text*)
796					[/(?:(?!\n)\s)*(\n+)(?:(?!\n)\s)*/gi, "$1"],	// Cool little RegExp deletes whitespace around linebreak chars.
797					[/\n{3,}/g, "\n\n"],							// Max. 2 consecutive linebreaks
798					/^\s+|\s+$/g									// Trim the front & back
799				]);
800
801				h = dom.decode(tinymce.html.Entities.encodeRaw(h));
802
803				// Delete any highlighted text before pasting
804				if (!sel.isCollapsed()) {
805					d.execCommand("Delete", false, null);
806				}
807
808				// Perform default or custom replacements
809				if (is(rl, "array") || (is(rl, "array"))) {
810					process(rl);
811				}
812				else if (is(rl, "string")) {
813					process(new RegExp(rl, "gi"));
814				}
815
816				// Treat paragraphs as specified in the config
817				if (linebr == "none") {
818					process([
819						[/\n+/g, " "]
820					]);
821				}
822				else if (linebr == "br") {
823					process([
824						[/\n/g, "<br />"]
825					]);
826				}
827				else {
828					process([
829						/^\s+|\s+$/g,
830						[/\n\n/g, "</p><p>"],
831						[/\n/g, "<br />"]
832					]);
833				}
834
835				// This next piece of code handles the situation where we're pasting more than one paragraph of plain
836				// text, and we are pasting the content into the middle of a block node in the editor.  The block
837				// node gets split at the selection point into "Para A" and "Para B" (for the purposes of explaining).
838				// The first paragraph of the pasted text is appended to "Para A", and the last paragraph of the
839				// pasted text is prepended to "Para B".  Any other paragraphs of pasted text are placed between
840				// "Para A" and "Para B".  This code solves a host of problems with the original plain text plugin and
841				// now handles styles correctly.  (Pasting plain text into a styled paragraph is supposed to make the
842				// plain text take the same style as the existing paragraph.)
843				if ((pos = h.indexOf("</p><p>")) != -1) {
844					rpos = h.lastIndexOf("</p><p>");
845					node = sel.getNode(); 
846					breakElms = [];		// Get list of elements to break 
847
848					do {
849						if (node.nodeType == 1) {
850							// Don't break tables and break at body
851							if (node.nodeName == "TD" || node.nodeName == "BODY") {
852								break;
853							}
854
855							breakElms[breakElms.length] = node;
856						}
857					} while (node = node.parentNode);
858
859					// Are we in the middle of a block node?
860					if (breakElms.length > 0) {
861						before = h.substring(0, pos);
862						after = "";
863
864						for (i=0, len=breakElms.length; i<len; i++) {
865							before += "</" + breakElms[i].nodeName.toLowerCase() + ">";
866							after += "<" + breakElms[breakElms.length-i-1].nodeName.toLowerCase() + ">";
867						}
868
869						if (pos == rpos) {
870							h = before + after + h.substring(pos+7);
871						}
872						else {
873							h = before + h.substring(pos+4, rpos+4) + after + h.substring(rpos+7);
874						}
875					}
876				}
877
878				// Insert content at the caret, plus add a marker for repositioning the caret
879				ed.execCommand("mceInsertRawHTML", false, h + '<span id="_plain_text_marker">&nbsp;</span>');
880
881				// Reposition the caret to the marker, which was placed immediately after the inserted content.
882				// Needs to be done asynchronously (in window.setTimeout) or else it doesn't work in all browsers.
883				// The second part of the code scrolls the content up if the caret is positioned off-screen.
884				// This is only necessary for WebKit browsers, but it doesn't hurt to use for all.
885				window.setTimeout(function() {
886					var marker = dom.get('_plain_text_marker'),
887						elm, vp, y, elmHeight;
888
889					sel.select(marker, false);
890					d.execCommand("Delete", false, null);
891					marker = null;
892
893					// Get element, position and height
894					elm = sel.getStart();
895					vp = dom.getViewPort(w);
896					y = dom.getPos(elm).y;
897					elmHeight = elm.clientHeight;
898
899					// Is element within viewport if not then scroll it into view
900					if ((y < vp.y) || (y + elmHeight > vp.y + vp.h)) {
901						d.body.scrollTop = y < vp.y ? y : y - vp.h + 25;
902					}
903				}, 0);
904			}
905		},
906
907		/**
908		 * This method will open the old style paste dialogs. Some users might want the old behavior but still use the new cleanup engine.
909		 */
910		_legacySupport : function() {
911			var t = this, ed = t.editor;
912
913			// Register command(s) for backwards compatibility
914			ed.addCommand("mcePasteWord", function() {
915				ed.windowManager.open({
916					file: t.url + "/pasteword.htm",
917					width: parseInt(getParam(ed, "paste_dialog_width")),
918					height: parseInt(getParam(ed, "paste_dialog_height")),
919					inline: 1
920				});
921			});
922
923			if (getParam(ed, "paste_text_use_dialog")) {
924				ed.addCommand("mcePasteText", function() {
925					ed.windowManager.open({
926						file : t.url + "/pastetext.htm",
927						width: parseInt(getParam(ed, "paste_dialog_width")),
928						height: parseInt(getParam(ed, "paste_dialog_height")),
929						inline : 1
930					});
931				});
932			}
933
934			// Register button for backwards compatibility
935			ed.addButton("pasteword", {title : "paste.paste_word_desc", cmd : "mcePasteWord"});
936		}
937	});
938
939	// Register plugin
940	tinymce.PluginManager.add("paste", tinymce.plugins.PastePlugin);
941})();