d85b39bd31136b9007041c1491d3f7b2d768caa9
[atutor.git] / docs / jscripts / tiny_mce / plugins / paste / editor_plugin_src.js
1 /**\r
2  * editor_plugin_src.js\r
3  *\r
4  * Copyright 2009, Moxiecode Systems AB\r
5  * Released under LGPL License.\r
6  *\r
7  * License: http://tinymce.moxiecode.com/license\r
8  * Contributing: http://tinymce.moxiecode.com/contributing\r
9  */\r
10 \r
11 (function() {\r
12         var each = tinymce.each,\r
13                 entities = null,\r
14                 defs = {\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
31                                 [/\u2026/g, "..."],\r
32                                 [/[\x93\x94\u201c\u201d]/g, '"'],\r
33                                 [/[\x60\x91\x92\u2018\u2019]/g, "'"]\r
34                         ]\r
35                 };\r
36 \r
37         function getParam(ed, name) {\r
38                 return ed.getParam(name, defs[name]);\r
39         }\r
40 \r
41         tinymce.create('tinymce.plugins.PastePlugin', {\r
42                 init : function(ed, url) {\r
43                         var t = this;\r
44 \r
45                         t.editor = ed;\r
46                         t.url = url;\r
47 \r
48                         // Setup plugin events\r
49                         t.onPreProcess = new tinymce.util.Dispatcher(t);\r
50                         t.onPostProcess = new tinymce.util.Dispatcher(t);\r
51 \r
52                         // Register default handlers\r
53                         t.onPreProcess.add(t._preProcess);\r
54                         t.onPostProcess.add(t._postProcess);\r
55 \r
56                         // Register optional preprocess handler\r
57                         t.onPreProcess.add(function(pl, o) {\r
58                                 ed.execCallback('paste_preprocess', pl, o);\r
59                         });\r
60 \r
61                         // Register optional postprocess\r
62                         t.onPostProcess.add(function(pl, o) {\r
63                                 ed.execCallback('paste_postprocess', pl, o);\r
64                         });\r
65 \r
66                         // Initialize plain text flag\r
67                         ed.pasteAsPlainText = false;\r
68 \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
72                                 var dom = ed.dom;\r
73 \r
74                                 // Execute pre process handlers\r
75                                 t.onPreProcess.dispatch(t, o);\r
76 \r
77                                 // Create DOM structure\r
78                                 o.node = dom.create('div', 0, o.content);\r
79 \r
80                                 // Execute post process handlers\r
81                                 t.onPostProcess.dispatch(t, o);\r
82 \r
83                                 // Serialize content\r
84                                 o.content = ed.serializer.serialize(o.node, {getInner : 1});\r
85 \r
86                                 // Plain text option active?\r
87                                 if ((!force_rich) && (ed.pasteAsPlainText)) {\r
88                                         t._insertPlainText(ed, dom, o.content);\r
89 \r
90                                         if (!getParam(ed, "paste_text_sticky")) {\r
91                                                 ed.pasteAsPlainText = false;\r
92                                                 ed.controlManager.setActive("pastetext", false);\r
93                                         }\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
97                                 } else {\r
98                                         t._insert(o.content);\r
99                                 }\r
100                         }\r
101 \r
102                         // Add command for external usage\r
103                         ed.addCommand('mceInsertClipboardContent', function(u, o) {\r
104                                 process(o, true);\r
105                         });\r
106 \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
110 \r
111                                         ed.pasteAsPlainText = !ed.pasteAsPlainText;\r
112                                         ed.controlManager.setActive('pastetext', ed.pasteAsPlainText);\r
113 \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
117                                                 } else {\r
118                                                         ed.windowManager.alert("Paste is now in plain text mode. Click again to toggle back to regular paste mode.");\r
119                                                 }\r
120 \r
121                                                 if (!getParam(ed, "paste_text_notifyalways")) {\r
122                                                         cookie.set("tinymcePasteText", "1", new Date(new Date().getFullYear() + 1, 12, 31))\r
123                                                 }\r
124                                         }\r
125                                 });\r
126                         }\r
127 \r
128                         ed.addButton('pastetext', {title: 'paste.paste_text_desc', cmd: 'mcePasteText'});\r
129                         ed.addButton('selectall', {title: 'paste.selectall_desc', cmd: 'selectall'});\r
130 \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
136 \r
137                                 if (dom.get('_mcePaste'))\r
138                                         return;\r
139 \r
140                                 // Create container to paste into\r
141                                 n = dom.add(body, 'div', {id : '_mcePaste', 'class' : 'mcePaste'}, '\uFEFF');\r
142 \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
146                                 else\r
147                                         posY = body.scrollTop;\r
148 \r
149                                 // Styles needs to be applied after the element is added to the document since WebKit will otherwise remove all styles\r
150                                 dom.setStyles(n, {\r
151                                         position : 'absolute',\r
152                                         left : -10000,\r
153                                         top : posY,\r
154                                         width : 1,\r
155                                         height : 1,\r
156                                         overflow : 'hidden'\r
157                                 });\r
158 \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
164 \r
165                                         // Remove container\r
166                                         dom.remove(n);\r
167 \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
173                                                 return;\r
174                                         }\r
175 \r
176                                         // Process contents\r
177                                         process({content : n.innerHTML});\r
178 \r
179                                         // Block the real paste event\r
180                                         return tinymce.dom.Event.cancel(e);\r
181                                 } else {\r
182                                         function block(e) {\r
183                                                 e.preventDefault();\r
184                                         };\r
185 \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
189 \r
190                                         or = ed.selection.getRng();\r
191 \r
192                                         // Move caret into hidden div\r
193                                         n = n.firstChild;\r
194                                         rng = ed.getDoc().createRange();\r
195                                         rng.setStart(n, 0);\r
196                                         rng.setEnd(n, 1);\r
197                                         sel.setRng(rng);\r
198 \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
202 \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
207                                                                 dom.remove(n, 1);\r
208                                                         });\r
209 \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
212                                                 });\r
213 \r
214                                                 // Remove the nodes\r
215                                                 each(nl, function(n) {\r
216                                                         dom.remove(n);\r
217                                                 });\r
218 \r
219                                                 // Restore the old selection\r
220                                                 if (or)\r
221                                                         sel.setRng(or);\r
222 \r
223                                                 process({content : h});\r
224 \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
228                                         }, 0);\r
229                                 }\r
230                         }\r
231 \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
238                                                         grabContent(e);\r
239                                         });\r
240                                 } else {\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
244                                         });\r
245                                 }\r
246                         }\r
247 \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
254 \r
255                                                 return false;\r
256                                         });\r
257                                 });\r
258                         }\r
259 \r
260                         // Add legacy support\r
261                         t._legacySupport();\r
262                 },\r
263 \r
264                 getInfo : function() {\r
265                         return {\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
271                         };\r
272                 },\r
273 \r
274                 _preProcess : function(pl, o) {\r
275                         //console.log('Before preprocess:' + o.content);\r
276 \r
277                         var ed = this.editor,\r
278                                 h = o.content,\r
279                                 grep = tinymce.grep,\r
280                                 explode = tinymce.explode,\r
281                                 trim = tinymce.trim,\r
282                                 len, stripClass;\r
283 \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
289                                         else\r
290                                                 h = h.replace(v[0], v[1]);\r
291                                 });\r
292                         }\r
293 \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
298 \r
299                                 // Process away some basic content\r
300                                 process([\r
301                                         /^\s*(&nbsp;)+/gi,                              // &nbsp; entities at the start of contents\r
302                                         /(&nbsp;|<br[^>]*>)+\s*$/gi             // &nbsp; entities at the end of contents\r
303                                 ]);\r
304 \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
307                                 }\r
308 \r
309                                 if (getParam(ed, "paste_convert_middot_lists")) {\r
310                                         process([\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
313                                         ]);\r
314                                 }\r
315 \r
316                                 process([\r
317                                         // Word comments like conditional comments etc\r
318                                         /<!--[\s\S]+?-->/gi,\r
319 \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
322 \r
323                                         // Convert <s> into <strike> for line-though\r
324                                         [/<(\/?)s>/gi, "<$1strike>"],\r
325 \r
326                                         // Replace nsbp entites to char since it's easier to handle\r
327                                         [/&nbsp;/gi, "\u00a0"]\r
328                                 ]);\r
329 \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
332                                 do {\r
333                                         len = h.length;\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
336 \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
340                                 } else {\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
343 \r
344                                         process([\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
349                                                         }\r
350                                                 ],\r
351 \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
355                                                                 var n = [],\r
356                                                                         i = 0,\r
357                                                                         s = explode(trim(style).replace(/&quot;/gi, "'"), ";");\r
358 \r
359                                                                 // Examine each style definition within the tag's style attribute\r
360                                                                 each(s, function(v) {\r
361                                                                         var name, value,\r
362                                                                                 parts = explode(v, ":");\r
363 \r
364                                                                         function ensureUnits(v) {\r
365                                                                                 return v + ((v !== "0") && (/\d$/.test(v)))? "px" : "";\r
366                                                                         }\r
367 \r
368                                                                         if (parts.length == 2) {\r
369                                                                                 name = parts[0].toLowerCase();\r
370                                                                                 value = parts[1].toLowerCase();\r
371 \r
372                                                                                 // Translate certain MS Office styles into their CSS equivalents\r
373                                                                                 switch (name) {\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
385                                                                                         case "mso-height":\r
386                                                                                         case "mso-width":\r
387                                                                                         case "mso-vertical-align-alt":\r
388                                                                                                 n[i++] = name.replace(/^mso-|-alt$/g, "") + ":" + ensureUnits(value);\r
389                                                                                                 return;\r
390 \r
391                                                                                         case "horiz-align":\r
392                                                                                                 n[i++] = "text-align:" + value;\r
393                                                                                                 return;\r
394 \r
395                                                                                         case "vert-align":\r
396                                                                                                 n[i++] = "vertical-align:" + value;\r
397                                                                                                 return;\r
398 \r
399                                                                                         case "font-color":\r
400                                                                                         case "mso-foreground":\r
401                                                                                                 n[i++] = "color:" + value;\r
402                                                                                                 return;\r
403 \r
404                                                                                         case "mso-background":\r
405                                                                                         case "mso-highlight":\r
406                                                                                                 n[i++] = "background:" + value;\r
407                                                                                                 return;\r
408 \r
409                                                                                         case "mso-default-height":\r
410                                                                                                 n[i++] = "min-height:" + ensureUnits(value);\r
411                                                                                                 return;\r
412 \r
413                                                                                         case "mso-default-width":\r
414                                                                                                 n[i++] = "min-width:" + ensureUnits(value);\r
415                                                                                                 return;\r
416 \r
417                                                                                         case "mso-padding-between-alt":\r
418                                                                                                 n[i++] = "border-collapse:separate;border-spacing:" + ensureUnits(value);\r
419                                                                                                 return;\r
420 \r
421                                                                                         case "text-line-through":\r
422                                                                                                 if ((value == "single") || (value == "double")) {\r
423                                                                                                         n[i++] = "text-decoration:line-through";\r
424                                                                                                 }\r
425                                                                                                 return;\r
426 \r
427                                                                                         case "mso-zero-height":\r
428                                                                                                 if (value == "yes") {\r
429                                                                                                         n[i++] = "display:none";\r
430                                                                                                 }\r
431                                                                                                 return;\r
432                                                                                 }\r
433 \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
436                                                                                         return;\r
437                                                                                 }\r
438 \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
441                                                                         }\r
442                                                                 });\r
443 \r
444                                                                 // If style attribute contained any valid styles the re-write it; otherwise delete style attribute.\r
445                                                                 if (i > 0) {\r
446                                                                         return tag + ' style="' + n.join(';') + '"';\r
447                                                                 } else {\r
448                                                                         return tag;\r
449                                                                 }\r
450                                                         }\r
451                                                 ]\r
452                                         ]);\r
453                                 }\r
454                         }\r
455 \r
456                         // Replace headers with <strong>\r
457                         if (getParam(ed, "paste_convert_headers_to_strong")) {\r
458                                 process([\r
459                                         [/<h[1-6][^>]*>/gi, "<p><strong>"],\r
460                                         [/<\/h[1-6][^>]*>/gi, "</strong></p>"]\r
461                                 ]);\r
462                         }\r
463 \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
467 \r
468                         if (stripClass !== "none") {\r
469                                 function removeClasses(match, g1) {\r
470                                                 if (stripClass === "all")\r
471                                                         return '';\r
472 \r
473                                                 var cls = grep(explode(g1.replace(/^(["'])(.*)\1$/, "$2"), " "),\r
474                                                         function(v) {\r
475                                                                 return (/^(?!mso)/i.test(v));\r
476                                                         }\r
477                                                 );\r
478 \r
479                                                 return cls.length ? ' class="' + cls.join(" ") + '"' : '';\r
480                                 };\r
481 \r
482                                 h = h.replace(/ class="([^"]+)"/gi, removeClasses);\r
483                                 h = h.replace(/ class=(\w+)/gi, removeClasses);\r
484                         }\r
485 \r
486                         // Remove spans option\r
487                         if (getParam(ed, "paste_remove_spans")) {\r
488                                 h = h.replace(/<\/?span[^>]*>/gi, "");\r
489                         }\r
490 \r
491                         //console.log('After preprocess:' + h);\r
492 \r
493                         o.content = h;\r
494                 },\r
495 \r
496                 /**\r
497                  * Various post process items.\r
498                  */\r
499                 _postProcess : function(pl, o) {\r
500                         var t = this, ed = t.editor, dom = ed.dom, styleProps;\r
501 \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
506                                                 dom.remove(a, 1);\r
507                                 });\r
508 \r
509                                 if (getParam(ed, "paste_convert_middot_lists")) {\r
510                                         t._convertLists(pl, o);\r
511                                 }\r
512 \r
513                                 // Process styles\r
514                                 styleProps = getParam(ed, "paste_retain_style_properties"); // retained properties\r
515 \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
519 \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
523 \r
524                                                 // Store a subset of the existing styles\r
525                                                 if (styleProps) {\r
526                                                         for (i = 0; i < styleProps.length; i++) {\r
527                                                                 sp = styleProps[i];\r
528                                                                 sv = dom.getStyle(el, sp);\r
529 \r
530                                                                 if (sv) {\r
531                                                                         newStyle[sp] = sv;\r
532                                                                         npc++;\r
533                                                                 }\r
534                                                         }\r
535                                                 }\r
536 \r
537                                                 // Remove all of the existing styles\r
538                                                 dom.setAttrib(el, 'style', '');\r
539 \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
545                                         });\r
546                                 }\r
547                         }\r
548 \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
554                                 });\r
555                         } else {\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
561                                         });\r
562                                 }\r
563                         }\r
564                 },\r
565 \r
566                 /**\r
567                  * Converts the most common bullet and number formats in Office into a real semantic UL/LI list.\r
568                  */\r
569                 _convertLists : function(pl, o) {\r
570                         var dom = pl.editor.dom, listElm, li, lastMargin = -1, margin, levels = [], lastType, html;\r
571 \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
575 \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
579 \r
580                                 val = p.innerHTML.replace(/<\/?\w+[^>]*>/gi, '').replace(/&nbsp;/g, '\u00a0');\r
581 \r
582                                 // Detect unordered lists look for bullets\r
583                                 if (/^(__MCE_ITEM__)+[\u2022\u00b7\u00a7\u00d8o]\s*\u00a0*/.test(val))\r
584                                         type = 'ul';\r
585 \r
586                                 // Detect ordered lists 1., a. or ixv.\r
587                                 if (/^__MCE_ITEM__\s*\w+\.\s*\u00a0{2,}/.test(val))\r
588                                         type = 'ol';\r
589 \r
590                                 // Check if node value matches the list pattern: o&nbsp;&nbsp;\r
591                                 if (type) {\r
592                                         margin = parseFloat(p.style.marginLeft || 0);\r
593 \r
594                                         if (margin > lastMargin)\r
595                                                 levels.push(margin);\r
596 \r
597                                         if (!listElm || type != lastType) {\r
598                                                 listElm = dom.create(type);\r
599                                                 dom.insertAfter(listElm, p);\r
600                                         } else {\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
609                                                 }\r
610                                         }\r
611 \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
615 \r
616                                                 // Remove span with the middot or the number\r
617                                                 if (type == 'ul' && /^[\u2022\u00b7\u00a7\u00d8o]/.test(html))\r
618                                                         dom.remove(span);\r
619                                                 else if (/^[\s\S]*\w+\.(&nbsp;|\u00a0)*\s*/.test(html))\r
620                                                         dom.remove(span);\r
621                                         });\r
622 \r
623                                         html = p.innerHTML;\r
624 \r
625                                         // Remove middot/list items\r
626                                         if (type == 'ul')\r
627                                                 html = p.innerHTML.replace(/__MCE_ITEM__/g, '').replace(/^[\u2022\u00b7\u00a7\u00d8o]\s*(&nbsp;|\u00a0)+\s*/, '');\r
628                                         else\r
629                                                 html = p.innerHTML.replace(/__MCE_ITEM__/g, '').replace(/^\s*\w+\.(&nbsp;|\u00a0)+\s*/, '');\r
630 \r
631                                         // Create li and add paragraph data into the new li\r
632                                         li = listElm.appendChild(dom.create('li', 0, html));\r
633                                         dom.remove(p);\r
634 \r
635                                         lastMargin = margin;\r
636                                         lastType = type;\r
637                                 } else\r
638                                         listElm = lastMargin = 0; // End list element\r
639                         });\r
640 \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
645                 },\r
646 \r
647                 /**\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
650                  */\r
651                 _insertBlockContent : function(ed, dom, content) {\r
652                         var parentBlock, marker, sel = ed.selection, last, elm, vp, y, elmHeight, markerId = 'mce_marker';\r
653 \r
654                         function select(n) {\r
655                                 var r;\r
656 \r
657                                 if (tinymce.isIE) {\r
658                                         r = ed.getDoc().body.createTextRange();\r
659                                         r.moveToElementText(n);\r
660                                         r.collapse(false);\r
661                                         r.select();\r
662                                 } else {\r
663                                         sel.select(n, 1);\r
664                                         sel.collapse(false);\r
665                                 }\r
666                         }\r
667 \r
668                         // Insert a marker for the caret position\r
669                         this._insert('<span id="' + markerId + '">&nbsp;</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
672 \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
677 \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
681                                 });\r
682 \r
683                                 // Move caret after marker\r
684                                 select(last);\r
685                         } else {\r
686                                 dom.setOuterHTML(marker, content);\r
687                                 sel.select(ed.getBody(), 1);\r
688                                 sel.collapse(0);\r
689                         }\r
690 \r
691                         // Remove marker if it's left\r
692                         while (elm = dom.get(markerId))\r
693                                 dom.remove(elm);\r
694 \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
700 \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
704                 },\r
705 \r
706                 /**\r
707                  * Inserts the specified contents at the caret position.\r
708                  */\r
709                 _insert : function(h, skip_undo) {\r
710                         var ed = this.editor;\r
711 \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
715 \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
718                 },\r
719 \r
720                 /**\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
728                  */\r
729                 _insertPlainText : function(ed, dom, h) {\r
730                         var i, len, pos, rpos, node, breakElms, before, after,\r
731                                 w = ed.getWin(),\r
732                                 d = ed.getDoc(),\r
733                                 sel = ed.selection,\r
734                                 is = tinymce.is,\r
735                                 inArray = tinymce.inArray,\r
736                                 linebr = getParam(ed, "paste_text_linebreaktype"),\r
737                                 rl = getParam(ed, "paste_text_replacements");\r
738 \r
739                         function process(items) {\r
740                                 each(items, function(v) {\r
741                                         if (v.constructor == RegExp)\r
742                                                 h = h.replace(v, "");\r
743                                         else\r
744                                                 h = h.replace(v[0], v[1]);\r
745                                 });\r
746                         };\r
747 \r
748                         if ((typeof(h) === "string") && (h.length > 0)) {\r
749                                 if (!entities)\r
750                                         entities = ("34,quot,38,amp,39,apos,60,lt,62,gt," + ed.serializer.settings.entities).split(",");\r
751 \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
754                                         process([\r
755                                                 /[\n\r]+/g\r
756                                         ]);\r
757                                 } else {\r
758                                         // Otherwise just get rid of carriage returns (only need linefeeds)\r
759                                         process([\r
760                                                 /\r+/g\r
761                                         ]);\r
762                                 }\r
763 \r
764                                 process([\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                                         [/&nbsp;/gi, " "],                                                      // Convert non-break spaces to regular spaces (remember, *plain text*)\r
770                                         [\r
771                                                 // HTML entity\r
772                                                 /&(#\d+|[a-z0-9]{1,10});/gi,\r
773 \r
774                                                 // Replace with actual character\r
775                                                 function(e, s) {\r
776                                                         if (s.charAt(0) === "#") {\r
777                                                                 return String.fromCharCode(s.slice(1));\r
778                                                         }\r
779                                                         else {\r
780                                                                 return ((e = inArray(entities, s)) > 0)? String.fromCharCode(entities[e-1]) : " ";\r
781                                                         }\r
782                                                 }\r
783                                         ],\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
787                                 ]);\r
788 \r
789                                 h = dom.encode(h);\r
790 \r
791                                 // Delete any highlighted text before pasting\r
792                                 if (!sel.isCollapsed()) {\r
793                                         d.execCommand("Delete", false, null);\r
794                                 }\r
795 \r
796                                 // Perform default or custom replacements\r
797                                 if (is(rl, "array") || (is(rl, "array"))) {\r
798                                         process(rl);\r
799                                 }\r
800                                 else if (is(rl, "string")) {\r
801                                         process(new RegExp(rl, "gi"));\r
802                                 }\r
803 \r
804                                 // Treat paragraphs as specified in the config\r
805                                 if (linebr == "none") {\r
806                                         process([\r
807                                                 [/\n+/g, " "]\r
808                                         ]);\r
809                                 }\r
810                                 else if (linebr == "br") {\r
811                                         process([\r
812                                                 [/\n/g, "<br />"]\r
813                                         ]);\r
814                                 }\r
815                                 else {\r
816                                         process([\r
817                                                 /^\s+|\s+$/g,\r
818                                                 [/\n\n/g, "</p><p>"],\r
819                                                 [/\n/g, "<br />"]\r
820                                         ]);\r
821                                 }\r
822 \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
835 \r
836                                         do {\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
840                                                                 break;\r
841                                                         }\r
842 \r
843                                                         breakElms[breakElms.length] = node;\r
844                                                 }\r
845                                         } while (node = node.parentNode);\r
846 \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
850                                                 after = "";\r
851 \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
855                                                 }\r
856 \r
857                                                 if (pos == rpos) {\r
858                                                         h = before + after + h.substring(pos+7);\r
859                                                 }\r
860                                                 else {\r
861                                                         h = before + h.substring(pos+4, rpos+4) + after + h.substring(rpos+7);\r
862                                                 }\r
863                                         }\r
864                                 }\r
865 \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">&nbsp;</span>');\r
868 \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
876 \r
877                                         sel.select(marker, false);\r
878                                         d.execCommand("Delete", false, null);\r
879                                         marker = null;\r
880 \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
886 \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
890                                         }\r
891                                 }, 0);\r
892                         }\r
893                 },\r
894 \r
895                 /**\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
897                  */\r
898                 _legacySupport : function() {\r
899                         var t = this, ed = t.editor;\r
900 \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
907                                         inline: 1\r
908                                 });\r
909                         });\r
910 \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
917                                                 inline : 1\r
918                                         });\r
919                                 });\r
920                         }\r
921 \r
922                         // Register button for backwards compatibility\r
923                         ed.addButton("pasteword", {title : "paste.paste_word_desc", cmd : "mcePasteWord"});\r
924                 }\r
925         });\r
926 \r
927         // Register plugin\r
928         tinymce.PluginManager.add("paste", tinymce.plugins.PastePlugin);\r
929 })();\r