/**\r
- * $Id: editor_plugin_src.js 1104 2009-04-22 12:16:47Z spocke $\r
+ * editor_plugin_src.js\r
*\r
- * @author Moxiecode\r
- * @copyright Copyright © 2004-2008, Moxiecode Systems AB, All rights reserved.\r
+ * Copyright 2009, Moxiecode Systems AB\r
+ * Released under LGPL License.\r
+ *\r
+ * License: http://tinymce.moxiecode.com/license\r
+ * Contributing: http://tinymce.moxiecode.com/contributing\r
*/\r
\r
(function() {\r
- var each = tinymce.each;\r
+ var each = tinymce.each,\r
+ defs = {\r
+ paste_auto_cleanup_on_paste : true,\r
+ paste_enable_default_filters : true,\r
+ paste_block_drop : false,\r
+ paste_retain_style_properties : "none",\r
+ paste_strip_class_attributes : "mso",\r
+ paste_remove_spans : false,\r
+ paste_remove_styles : false,\r
+ paste_remove_styles_if_webkit : true,\r
+ paste_convert_middot_lists : true,\r
+ paste_convert_headers_to_strong : false,\r
+ paste_dialog_width : "450",\r
+ paste_dialog_height : "400",\r
+ paste_text_use_dialog : false,\r
+ paste_text_sticky : false,\r
+ paste_text_sticky_default : false,\r
+ paste_text_notifyalways : false,\r
+ paste_text_linebreaktype : "p",\r
+ paste_text_replacements : [\r
+ [/\u2026/g, "..."],\r
+ [/[\x93\x94\u201c\u201d]/g, '"'],\r
+ [/[\x60\x91\x92\u2018\u2019]/g, "'"]\r
+ ]\r
+ };\r
+\r
+ function getParam(ed, name) {\r
+ return ed.getParam(name, defs[name]);\r
+ }\r
\r
tinymce.create('tinymce.plugins.PastePlugin', {\r
init : function(ed, url) {\r
- var t = this, cb;\r
+ var t = this;\r
\r
t.editor = ed;\r
t.url = url;\r
ed.execCallback('paste_postprocess', pl, o);\r
});\r
\r
+ ed.onKeyDown.addToTop(function(ed, e) {\r
+ // Block ctrl+v from adding an undo level since the default logic in tinymce.Editor will add that\r
+ if (((tinymce.isMac ? e.metaKey : e.ctrlKey) && e.keyCode == 86) || (e.shiftKey && e.keyCode == 45))\r
+ return false; // Stop other listeners\r
+ });\r
+\r
+ // Initialize plain text flag\r
+ ed.pasteAsPlainText = getParam(ed, 'paste_text_sticky_default');\r
+\r
// This function executes the process handlers and inserts the contents\r
- function process(h) {\r
- var dom = ed.dom, o = {content : h};\r
+ // force_rich overrides plain text mode set by user, important for pasting with execCommand\r
+ function process(o, force_rich) {\r
+ var dom = ed.dom, rng, nodes;\r
\r
// Execute pre process handlers\r
t.onPreProcess.dispatch(t, o);\r
// Create DOM structure\r
o.node = dom.create('div', 0, o.content);\r
\r
+ // If pasting inside the same element and the contents is only one block\r
+ // remove the block and keep the text since Firefox will copy parts of pre and h1-h6 as a pre element\r
+ if (tinymce.isGecko) {\r
+ rng = ed.selection.getRng(true);\r
+ if (rng.startContainer == rng.endContainer && rng.startContainer.nodeType == 3) {\r
+ nodes = dom.select('p,h1,h2,h3,h4,h5,h6,pre', o.node);\r
+\r
+ // Is only one block node and it doesn't contain word stuff\r
+ if (nodes.length == 1 && o.content.indexOf('__MCE_ITEM__') === -1)\r
+ dom.remove(nodes.reverse(), true);\r
+ }\r
+ }\r
+\r
// Execute post process handlers\r
t.onPostProcess.dispatch(t, o);\r
\r
// Serialize content\r
o.content = ed.serializer.serialize(o.node, {getInner : 1});\r
\r
- // Insert cleaned content. We need to handle insertion of contents containing block elements separatly\r
- if (/<(p|h[1-6]|ul|ol)/.test(o.content))\r
- t._insertBlockContent(ed, dom, o.content);\r
- else\r
+ // Plain text option active?\r
+ if ((!force_rich) && (ed.pasteAsPlainText)) {\r
+ t._insertPlainText(ed, dom, o.content);\r
+\r
+ if (!getParam(ed, "paste_text_sticky")) {\r
+ ed.pasteAsPlainText = false;\r
+ ed.controlManager.setActive("pastetext", false);\r
+ }\r
+ } else {\r
t._insert(o.content);\r
- };\r
+ }\r
+ }\r
\r
// Add command for external usage\r
- ed.addCommand('mceInsertClipboardContent', function(u, v) {\r
- process(v);\r
+ ed.addCommand('mceInsertClipboardContent', function(u, o) {\r
+ process(o, true);\r
});\r
\r
+ if (!getParam(ed, "paste_text_use_dialog")) {\r
+ ed.addCommand('mcePasteText', function(u, v) {\r
+ var cookie = tinymce.util.Cookie;\r
+\r
+ ed.pasteAsPlainText = !ed.pasteAsPlainText;\r
+ ed.controlManager.setActive('pastetext', ed.pasteAsPlainText);\r
+\r
+ if ((ed.pasteAsPlainText) && (!cookie.get("tinymcePasteText"))) {\r
+ if (getParam(ed, "paste_text_sticky")) {\r
+ ed.windowManager.alert(ed.translate('paste.plaintext_mode_sticky'));\r
+ } else {\r
+ ed.windowManager.alert(ed.translate('paste.plaintext_mode_sticky'));\r
+ }\r
+\r
+ if (!getParam(ed, "paste_text_notifyalways")) {\r
+ cookie.set("tinymcePasteText", "1", new Date(new Date().getFullYear() + 1, 12, 31))\r
+ }\r
+ }\r
+ });\r
+ }\r
+\r
+ ed.addButton('pastetext', {title: 'paste.paste_text_desc', cmd: 'mcePasteText'});\r
+ ed.addButton('selectall', {title: 'paste.selectall_desc', cmd: 'selectall'});\r
+\r
// This function grabs the contents from the clipboard by adding a\r
// hidden div and placing the caret inside it and after the browser paste\r
// is done it grabs that contents and processes that\r
function grabContent(e) {\r
- var n, or, rng, sel = ed.selection, dom = ed.dom, body = ed.getBody(), posY;\r
+ var n, or, rng, oldRng, sel = ed.selection, dom = ed.dom, body = ed.getBody(), posY, textContent;\r
+\r
+ // Check if browser supports direct plaintext access\r
+ if (e.clipboardData || dom.doc.dataTransfer) {\r
+ textContent = (e.clipboardData || dom.doc.dataTransfer).getData('Text');\r
+\r
+ if (ed.pasteAsPlainText) {\r
+ e.preventDefault();\r
+ process({content : textContent.replace(/\r?\n/g, '<br />')});\r
+ return;\r
+ }\r
+ }\r
\r
if (dom.get('_mcePaste'))\r
return;\r
\r
// Create container to paste into\r
- n = dom.add(body, 'div', {id : '_mcePaste'}, ' ');\r
+ n = dom.add(body, 'div', {id : '_mcePaste', 'class' : 'mcePaste', 'data-mce-bogus' : '1'}, '\uFEFF\uFEFF');\r
\r
// If contentEditable mode we need to find out the position of the closest element\r
if (body != ed.getDoc().body)\r
posY = dom.getPos(ed.selection.getStart(), body).y;\r
else\r
- posY = body.scrollTop;\r
+ posY = body.scrollTop + dom.getViewPort().y;\r
\r
// Styles needs to be applied after the element is added to the document since WebKit will otherwise remove all styles\r
dom.setStyles(n, {\r
});\r
\r
if (tinymce.isIE) {\r
+ // Store away the old range\r
+ oldRng = sel.getRng();\r
+\r
// Select the container\r
rng = dom.doc.body.createTextRange();\r
rng.moveToElementText(n);\r
// Remove container\r
dom.remove(n);\r
\r
- // Process contents\r
- process(n.innerHTML);\r
+ // Check if the contents was changed, if it wasn't then clipboard extraction failed probably due\r
+ // to IE security settings so we pass the junk though better than nothing right\r
+ if (n.innerHTML === '\uFEFF\uFEFF') {\r
+ ed.execCommand('mcePasteWord');\r
+ e.preventDefault();\r
+ return;\r
+ }\r
+\r
+ // Restore the old range and clear the contents before pasting\r
+ sel.setRng(oldRng);\r
+ sel.setContent('');\r
+\r
+ // For some odd reason we need to detach the the mceInsertContent call from the paste event\r
+ // It's like IE has a reference to the parent element that you paste in and the selection gets messed up\r
+ // when it tries to restore the selection\r
+ setTimeout(function() {\r
+ // Process contents\r
+ process({content : n.innerHTML});\r
+ }, 0);\r
\r
+ // Block the real paste event\r
return tinymce.dom.Event.cancel(e);\r
} else {\r
+ function block(e) {\r
+ e.preventDefault();\r
+ };\r
+\r
+ // Block mousedown and click to prevent selection change\r
+ dom.bind(ed.getDoc(), 'mousedown', block);\r
+ dom.bind(ed.getDoc(), 'keydown', block);\r
+\r
or = ed.selection.getRng();\r
\r
- // Move caret into hidden div\r
+ // Move select contents inside DIV\r
n = n.firstChild;\r
rng = ed.getDoc().createRange();\r
rng.setStart(n, 0);\r
- rng.setEnd(n, 1);\r
+ rng.setEnd(n, 2);\r
sel.setRng(rng);\r
\r
// Wait a while and grab the pasted contents\r
window.setTimeout(function() {\r
- var n = dom.get('_mcePaste'), h;\r
-\r
- // Webkit clones the _mcePaste div for some odd reason so this will ensure that we get the real new div not the old empty one\r
- n.id = '_mceRemoved';\r
- dom.remove(n);\r
- n = dom.get('_mcePaste') || n;\r
-\r
- // Grab the HTML contents\r
- // We need to look for a apple style wrapper on webkit it also adds a div wrapper if you copy/paste the body of the editor\r
- // It's amazing how strange the contentEditable mode works in WebKit\r
- h = (dom.select('> span.Apple-style-span div', n)[0] || dom.select('> span.Apple-style-span', n)[0] || n).innerHTML;\r
+ var h = '', nl;\r
+\r
+ // Paste divs duplicated in paste divs seems to happen when you paste plain text so lets first look for that broken behavior in WebKit\r
+ if (!dom.select('div.mcePaste > div.mcePaste').length) {\r
+ nl = dom.select('div.mcePaste');\r
+\r
+ // 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
+ each(nl, function(n) {\r
+ var child = n.firstChild;\r
+\r
+ // WebKit inserts a DIV container with lots of odd styles\r
+ if (child && child.nodeName == 'DIV' && child.style.marginTop && child.style.backgroundColor) {\r
+ dom.remove(child, 1);\r
+ }\r
+\r
+ // Remove apply style spans\r
+ each(dom.select('span.Apple-style-span', n), function(n) {\r
+ dom.remove(n, 1);\r
+ });\r
+\r
+ // Remove bogus br elements\r
+ each(dom.select('br[data-mce-bogus]', n), function(n) {\r
+ dom.remove(n);\r
+ });\r
+\r
+ // WebKit will make a copy of the DIV for each line of plain text pasted and insert them into the DIV\r
+ if (n.parentNode.className != 'mcePaste')\r
+ h += n.innerHTML;\r
+ });\r
+ } else {\r
+ // Found WebKit weirdness so force the content into plain text mode\r
+ h = '<pre>' + dom.encode(textContent).replace(/\r?\n/g, '<br />') + '</pre>';\r
+ }\r
\r
- // Remove hidden div and restore selection\r
- dom.remove(n);\r
+ // Remove the nodes\r
+ each(dom.select('div.mcePaste'), function(n) {\r
+ dom.remove(n);\r
+ });\r
\r
// Restore the old selection\r
if (or)\r
sel.setRng(or);\r
\r
- process(h);\r
+ process({content : h});\r
+\r
+ // Unblock events ones we got the contents\r
+ dom.unbind(ed.getDoc(), 'mousedown', block);\r
+ dom.unbind(ed.getDoc(), 'keydown', block);\r
}, 0);\r
}\r
- };\r
+ }\r
\r
// Check if we should use the new auto process method \r
- if (ed.getParam('paste_auto_cleanup_on_paste', true)) {\r
+ if (getParam(ed, "paste_auto_cleanup_on_paste")) {\r
// Is it's Opera or older FF use key handler\r
if (tinymce.isOpera || /Firefox\/2/.test(navigator.userAgent)) {\r
- ed.onKeyDown.add(function(ed, e) {\r
+ ed.onKeyDown.addToTop(function(ed, e) {\r
if (((tinymce.isMac ? e.metaKey : e.ctrlKey) && e.keyCode == 86) || (e.shiftKey && e.keyCode == 45))\r
grabContent(e);\r
});\r
}\r
}\r
\r
+ ed.onInit.add(function() {\r
+ ed.controlManager.setActive("pastetext", ed.pasteAsPlainText);\r
+\r
+ // Block all drag/drop events\r
+ if (getParam(ed, "paste_block_drop")) {\r
+ ed.dom.bind(ed.getBody(), ['dragend', 'dragover', 'draggesture', 'dragdrop', 'drop', 'drag'], function(e) {\r
+ e.preventDefault();\r
+ e.stopPropagation();\r
+\r
+ return false;\r
+ });\r
+ }\r
+ });\r
+\r
// Add legacy support\r
t._legacySupport();\r
},\r
},\r
\r
_preProcess : function(pl, o) {\r
- var h = o.content, process;\r
+ var ed = this.editor,\r
+ h = o.content,\r
+ grep = tinymce.grep,\r
+ explode = tinymce.explode,\r
+ trim = tinymce.trim,\r
+ len, stripClass;\r
\r
//console.log('Before preprocess:' + o.content);\r
\r
else\r
h = h.replace(v[0], v[1]);\r
});\r
- };\r
+ }\r
+ \r
+ if (ed.settings.paste_enable_default_filters == false) {\r
+ return;\r
+ }\r
\r
- // Process away some basic content\r
- process([\r
- /^\s*( )+/g, // nbsp entities at the start of contents\r
- /( |<br[^>]*>)+\s*$/g // nbsp entities at the end of contents\r
- ]);\r
+ // IE9 adds BRs before/after block elements when contents is pasted from word or for example another browser\r
+ if (tinymce.isIE && document.documentMode >= 9)\r
+ process([[/(?:<br> [\s\r\n]+|<br>)*(<\/?(h[1-6r]|p|div|address|pre|form|table|tbody|thead|tfoot|th|tr|td|li|ol|ul|caption|blockquote|center|dl|dt|dd|dir|fieldset)[^>]*>)(?:<br> [\s\r\n]+|<br>)*/g, '$1']]);\r
\r
- // Detect Word content and process it more agressive\r
- if (/(class=\"?Mso|style=\"[^\"]*\bmso\-|w:WordDocument)/.test(h)) {\r
- o.wordContent = true; // Mark the pasted contents as word specific content\r
+ // Detect Word content and process it more aggressive\r
+ if (/class="?Mso|style="[^"]*\bmso-|w:WordDocument/i.test(h) || o.wordContent) {\r
+ o.wordContent = true; // Mark the pasted contents as word specific content\r
//console.log('Word contents detected.');\r
\r
+ // Process away some basic content\r
process([\r
- /<!--[\s\S]+?-->/gi, // Word comments\r
- /<\/?(img|font|meta|link|style|span|div|v:\w+)[^>]*>/gi, // Remove some tags including VML content\r
- /<\\?\?xml[^>]*>/gi, // XML namespace declarations\r
- /<\/?o:[^>]*>/gi, // MS namespaced elements <o:tag>\r
- / (id|name|class|language|type|on\w+|v:\w+)=\"([^\"]*)\"/gi, // on.., class, style and language attributes with quotes\r
- / (id|name|class|language|type|on\w+|v:\w+)=(\w+)/gi, // on.., class, style and language attributes without quotes (IE)\r
- [/<(\/?)s>/gi, '<$1strike>'], // Convert <s> into <strike> for line-though\r
- /<script[^>]+>[\s\S]*?<\/script>/gi, // All scripts elements for msoShowComment for example\r
- [/ /g, '\u00a0'] // Replace nsbp entites to char since it's easier to handle\r
+ /^\s*( )+/gi, // entities at the start of contents\r
+ /( |<br[^>]*>)+\s*$/gi // entities at the end of contents\r
+ ]);\r
+\r
+ if (getParam(ed, "paste_convert_headers_to_strong")) {\r
+ h = h.replace(/<p [^>]*class="?MsoHeading"?[^>]*>(.*?)<\/p>/gi, "<p><strong>$1</strong></p>");\r
+ }\r
+\r
+ if (getParam(ed, "paste_convert_middot_lists")) {\r
+ process([\r
+ [/<!--\[if !supportLists\]-->/gi, '$&__MCE_ITEM__'], // Convert supportLists to a list item marker\r
+ [/(<span[^>]+(?:mso-list:|:\s*symbol)[^>]+>)/gi, '$1__MCE_ITEM__'], // Convert mso-list and symbol spans to item markers\r
+ [/(<p[^>]+(?:MsoListParagraph)[^>]+>)/gi, '$1__MCE_ITEM__'] // Convert mso-list and symbol paragraphs to item markers (FF)\r
+ ]);\r
+ }\r
+\r
+ process([\r
+ // Word comments like conditional comments etc\r
+ /<!--[\s\S]+?-->/gi,\r
+\r
+ // Remove comments, scripts (e.g., msoShowComment), XML tag, VML content, MS Office namespaced tags, and a few other tags\r
+ /<(!|script[^>]*>.*?<\/script(?=[>\s])|\/?(\?xml(:\w+)?|img|meta|link|style|\w:\w+)(?=[\s\/>]))[^>]*>/gi,\r
+\r
+ // Convert <s> into <strike> for line-though\r
+ [/<(\/?)s>/gi, "<$1strike>"],\r
+\r
+ // Replace nsbp entites to char since it's easier to handle\r
+ [/ /gi, "\u00a0"]\r
+ ]);\r
+\r
+ // Remove bad attributes, with or without quotes, ensuring that attribute text is really inside a tag.\r
+ // 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
+ do {\r
+ len = h.length;\r
+ h = h.replace(/(<[a-z][^>]*\s)(?:id|name|language|type|on\w+|\w+:\w+)=(?:"[^"]*"|\w+)\s?/gi, "$1");\r
+ } while (len != h.length);\r
+\r
+ // Remove all spans if no styles is to be retained\r
+ if (getParam(ed, "paste_retain_style_properties").replace(/^none$/i, "").length == 0) {\r
+ h = h.replace(/<\/?span[^>]*>/gi, "");\r
+ } else {\r
+ // We're keeping styles, so at least clean them up.\r
+ // CSS Reference: http://msdn.microsoft.com/en-us/library/aa155477.aspx\r
+\r
+ process([\r
+ // Convert <span style="mso-spacerun:yes">___</span> to string of alternating breaking/non-breaking spaces of same length\r
+ [/<span\s+style\s*=\s*"\s*mso-spacerun\s*:\s*yes\s*;?\s*"\s*>([\s\u00a0]*)<\/span>/gi,\r
+ function(str, spaces) {\r
+ return (spaces.length > 0)? spaces.replace(/./, " ").slice(Math.floor(spaces.length/2)).split("").join("\u00a0") : "";\r
+ }\r
+ ],\r
+\r
+ // Examine all styles: delete junk, transform some, and keep the rest\r
+ [/(<[a-z][^>]*)\sstyle="([^"]*)"/gi,\r
+ function(str, tag, style) {\r
+ var n = [],\r
+ i = 0,\r
+ s = explode(trim(style).replace(/"/gi, "'"), ";");\r
+\r
+ // Examine each style definition within the tag's style attribute\r
+ each(s, function(v) {\r
+ var name, value,\r
+ parts = explode(v, ":");\r
+\r
+ function ensureUnits(v) {\r
+ return v + ((v !== "0") && (/\d$/.test(v)))? "px" : "";\r
+ }\r
+\r
+ if (parts.length == 2) {\r
+ name = parts[0].toLowerCase();\r
+ value = parts[1].toLowerCase();\r
+\r
+ // Translate certain MS Office styles into their CSS equivalents\r
+ switch (name) {\r
+ case "mso-padding-alt":\r
+ case "mso-padding-top-alt":\r
+ case "mso-padding-right-alt":\r
+ case "mso-padding-bottom-alt":\r
+ case "mso-padding-left-alt":\r
+ case "mso-margin-alt":\r
+ case "mso-margin-top-alt":\r
+ case "mso-margin-right-alt":\r
+ case "mso-margin-bottom-alt":\r
+ case "mso-margin-left-alt":\r
+ case "mso-table-layout-alt":\r
+ case "mso-height":\r
+ case "mso-width":\r
+ case "mso-vertical-align-alt":\r
+ n[i++] = name.replace(/^mso-|-alt$/g, "") + ":" + ensureUnits(value);\r
+ return;\r
+\r
+ case "horiz-align":\r
+ n[i++] = "text-align:" + value;\r
+ return;\r
+\r
+ case "vert-align":\r
+ n[i++] = "vertical-align:" + value;\r
+ return;\r
+\r
+ case "font-color":\r
+ case "mso-foreground":\r
+ n[i++] = "color:" + value;\r
+ return;\r
+\r
+ case "mso-background":\r
+ case "mso-highlight":\r
+ n[i++] = "background:" + value;\r
+ return;\r
+\r
+ case "mso-default-height":\r
+ n[i++] = "min-height:" + ensureUnits(value);\r
+ return;\r
+\r
+ case "mso-default-width":\r
+ n[i++] = "min-width:" + ensureUnits(value);\r
+ return;\r
+\r
+ case "mso-padding-between-alt":\r
+ n[i++] = "border-collapse:separate;border-spacing:" + ensureUnits(value);\r
+ return;\r
+\r
+ case "text-line-through":\r
+ if ((value == "single") || (value == "double")) {\r
+ n[i++] = "text-decoration:line-through";\r
+ }\r
+ return;\r
+\r
+ case "mso-zero-height":\r
+ if (value == "yes") {\r
+ n[i++] = "display:none";\r
+ }\r
+ return;\r
+ }\r
+\r
+ // Eliminate all MS Office style definitions that have no CSS equivalent by examining the first characters in the name\r
+ 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
+ return;\r
+ }\r
+\r
+ // If it reached this point, it must be a valid CSS style\r
+ n[i++] = name + ":" + parts[1]; // Lower-case name, but keep value case\r
+ }\r
+ });\r
+\r
+ // If style attribute contained any valid styles the re-write it; otherwise delete style attribute.\r
+ if (i > 0) {\r
+ return tag + ' style="' + n.join(';') + '"';\r
+ } else {\r
+ return tag;\r
+ }\r
+ }\r
+ ]\r
+ ]);\r
+ }\r
+ }\r
+\r
+ // Replace headers with <strong>\r
+ if (getParam(ed, "paste_convert_headers_to_strong")) {\r
+ process([\r
+ [/<h[1-6][^>]*>/gi, "<p><strong>"],\r
+ [/<\/h[1-6][^>]*>/gi, "</strong></p>"]\r
]);\r
}\r
\r
+ process([\r
+ // Copy paste from Java like Open Office will produce this junk on FF\r
+ [/Version:[\d.]+\nStartHTML:\d+\nEndHTML:\d+\nStartFragment:\d+\nEndFragment:\d+/gi, '']\r
+ ]);\r
+\r
+ // Class attribute options are: leave all as-is ("none"), remove all ("all"), or remove only those starting with mso ("mso").\r
+ // Note:- paste_strip_class_attributes: "none", verify_css_classes: true is also a good variation.\r
+ stripClass = getParam(ed, "paste_strip_class_attributes");\r
+\r
+ if (stripClass !== "none") {\r
+ function removeClasses(match, g1) {\r
+ if (stripClass === "all")\r
+ return '';\r
+\r
+ var cls = grep(explode(g1.replace(/^(["'])(.*)\1$/, "$2"), " "),\r
+ function(v) {\r
+ return (/^(?!mso)/i.test(v));\r
+ }\r
+ );\r
+\r
+ return cls.length ? ' class="' + cls.join(" ") + '"' : '';\r
+ };\r
+\r
+ h = h.replace(/ class="([^"]+)"/gi, removeClasses);\r
+ h = h.replace(/ class=([\-\w]+)/gi, removeClasses);\r
+ }\r
+\r
+ // Remove spans option\r
+ if (getParam(ed, "paste_remove_spans")) {\r
+ h = h.replace(/<\/?span[^>]*>/gi, "");\r
+ }\r
+\r
//console.log('After preprocess:' + h);\r
\r
o.content = h;\r
* Various post process items.\r
*/\r
_postProcess : function(pl, o) {\r
- var t = this, dom = t.editor.dom;\r
+ var t = this, ed = t.editor, dom = ed.dom, styleProps;\r
\r
+ if (ed.settings.paste_enable_default_filters == false) {\r
+ return;\r
+ }\r
+ \r
if (o.wordContent) {\r
// Remove named anchors or TOC links\r
each(dom.select('a', o.node), function(a) {\r
dom.remove(a, 1);\r
});\r
\r
- if (t.editor.getParam('paste_convert_middot_lists', true))\r
+ if (getParam(ed, "paste_convert_middot_lists")) {\r
t._convertLists(pl, o);\r
+ }\r
\r
- // Remove all styles\r
- each(dom.select('*', o.node), function(el) {\r
- dom.setAttrib(el, 'style', '');\r
- });\r
+ // Process styles\r
+ styleProps = getParam(ed, "paste_retain_style_properties"); // retained properties\r
+\r
+ // Process only if a string was specified and not equal to "all" or "*"\r
+ if ((tinymce.is(styleProps, "string")) && (styleProps !== "all") && (styleProps !== "*")) {\r
+ styleProps = tinymce.explode(styleProps.replace(/^none$/i, ""));\r
+\r
+ // Retains some style properties\r
+ each(dom.select('*', o.node), function(el) {\r
+ var newStyle = {}, npc = 0, i, sp, sv;\r
+\r
+ // Store a subset of the existing styles\r
+ if (styleProps) {\r
+ for (i = 0; i < styleProps.length; i++) {\r
+ sp = styleProps[i];\r
+ sv = dom.getStyle(el, sp);\r
+\r
+ if (sv) {\r
+ newStyle[sp] = sv;\r
+ npc++;\r
+ }\r
+ }\r
+ }\r
+\r
+ // Remove all of the existing styles\r
+ dom.setAttrib(el, 'style', '');\r
+\r
+ if (styleProps && npc > 0)\r
+ dom.setStyles(el, newStyle); // Add back the stored subset of styles\r
+ else // Remove empty span tags that do not have class attributes\r
+ if (el.nodeName == 'SPAN' && !el.className)\r
+ dom.remove(el, true);\r
+ });\r
+ }\r
}\r
\r
- if (tinymce.isWebKit) {\r
- // 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
- // Removing the mce_style that contains the real value will force the Serializer engine to compress the styles\r
- each(dom.select('*', o.node), function(el) {\r
- el.removeAttribute('mce_style');\r
+ // Remove all style information or only specifically on WebKit to avoid the style bug on that browser\r
+ if (getParam(ed, "paste_remove_styles") || (getParam(ed, "paste_remove_styles_if_webkit") && tinymce.isWebKit)) {\r
+ each(dom.select('*[style]', o.node), function(el) {\r
+ el.removeAttribute('style');\r
+ el.removeAttribute('data-mce-style');\r
});\r
+ } else {\r
+ if (tinymce.isWebKit) {\r
+ // 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
+ // Removing the mce_style that contains the real value will force the Serializer engine to compress the styles\r
+ each(dom.select('*', o.node), function(el) {\r
+ el.removeAttribute('data-mce-style');\r
+ });\r
+ }\r
}\r
},\r
\r
* Converts the most common bullet and number formats in Office into a real semantic UL/LI list.\r
*/\r
_convertLists : function(pl, o) {\r
- var dom = pl.editor.dom, listElm, li, lastMargin = -1, margin, levels = [], lastType;\r
+ var dom = pl.editor.dom, listElm, li, lastMargin = -1, margin, levels = [], lastType, html;\r
\r
- // Convert middot lists into real scemantic lists\r
+ // Convert middot lists into real semantic lists\r
each(dom.select('p', o.node), function(p) {\r
var sib, val = '', type, html, idx, parents;\r
\r
for (sib = p.firstChild; sib && sib.nodeType == 3; sib = sib.nextSibling)\r
val += sib.nodeValue;\r
\r
+ val = p.innerHTML.replace(/<\/?\w+[^>]*>/gi, '').replace(/ /g, '\u00a0');\r
+\r
// Detect unordered lists look for bullets\r
- if (/^[\u2022\u00b7\u00a7\u00d8o]\s*\u00a0\u00a0*/.test(val))\r
+ if (/^(__MCE_ITEM__)+[\u2022\u00b7\u00a7\u00d8o\u25CF]\s*\u00a0*/.test(val))\r
type = 'ul';\r
\r
// Detect ordered lists 1., a. or ixv.\r
- if (/^[\s\S]*\w+\.[\s\S]*\u00a0{2,}/.test(val))\r
+ if (/^__MCE_ITEM__\s*\w+\.\s*\u00a0+/.test(val))\r
type = 'ol';\r
\r
// Check if node value matches the list pattern: o \r
}\r
}\r
\r
+ // Remove middot or number spans if they exists\r
+ each(dom.select('span', p), function(span) {\r
+ var html = span.innerHTML.replace(/<\/?\w+[^>]*>/gi, '');\r
+\r
+ // Remove span with the middot or the number\r
+ if (type == 'ul' && /^__MCE_ITEM__[\u2022\u00b7\u00a7\u00d8o\u25CF]/.test(html))\r
+ dom.remove(span);\r
+ else if (/^__MCE_ITEM__[\s\S]*\w+\.( |\u00a0)*\s*/.test(html))\r
+ dom.remove(span);\r
+ });\r
+\r
+ html = p.innerHTML;\r
+\r
+ // Remove middot/list items\r
if (type == 'ul')\r
- html = p.innerHTML.replace(/^[\u2022\u00b7\u00a7\u00d8o]\s*( |\u00a0)+\s*/, '');\r
+ html = p.innerHTML.replace(/__MCE_ITEM__/g, '').replace(/^[\u2022\u00b7\u00a7\u00d8o\u25CF]\s*( |\u00a0)+\s*/, '');\r
else\r
- html = p.innerHTML.replace(/^[\s\S]*\w+\.( |\u00a0)+\s*/, '');\r
+ html = p.innerHTML.replace(/__MCE_ITEM__/g, '').replace(/^\s*\w+\.( |\u00a0)+\s*/, '');\r
\r
+ // Create li and add paragraph data into the new li\r
li = listElm.appendChild(dom.create('li', 0, html));\r
dom.remove(p);\r
\r
} else\r
listElm = lastMargin = 0; // End list element\r
});\r
+\r
+ // Remove any left over makers\r
+ html = o.node.innerHTML;\r
+ if (html.indexOf('__MCE_ITEM__') != -1)\r
+ o.node.innerHTML = html.replace(/__MCE_ITEM__/g, '');\r
},\r
\r
/**\r
- * This method will split the current block parent and insert the contents inside the split position.\r
- * This logic can be improved so text nodes at the start/end remain in the start/end block elements\r
+ * Inserts the specified contents at the caret position.\r
*/\r
- _insertBlockContent : function(ed, dom, content) {\r
- var parentBlock, marker, sel = ed.selection, last, elm, vp, y, elmHeight;\r
+ _insert : function(h, skip_undo) {\r
+ var ed = this.editor, r = ed.selection.getRng();\r
\r
- function select(n) {\r
- var r;\r
+ // First delete the contents seems to work better on WebKit when the selection spans multiple list items or multiple table cells.\r
+ if (!ed.selection.isCollapsed() && r.startContainer != r.endContainer)\r
+ ed.getDoc().execCommand('Delete', false, null);\r
\r
- if (tinymce.isIE) {\r
- r = ed.getDoc().body.createTextRange();\r
- r.moveToElementText(n);\r
- r.collapse(false);\r
- r.select();\r
+ ed.execCommand('mceInsertContent', false, h, {skip_undo : skip_undo});\r
+ },\r
+\r
+ /**\r
+ * Instead of the old plain text method which tried to re-create a paste operation, the\r
+ * new approach adds a plain text mode toggle switch that changes the behavior of paste.\r
+ * This function is passed the same input that the regular paste plugin produces.\r
+ * It performs additional scrubbing and produces (and inserts) the plain text.\r
+ * This approach leverages all of the great existing functionality in the paste\r
+ * plugin, and requires minimal changes to add the new functionality.\r
+ * Speednet - June 2009\r
+ */\r
+ _insertPlainText : function(ed, dom, h) {\r
+ var i, len, pos, rpos, node, breakElms, before, after,\r
+ w = ed.getWin(),\r
+ d = ed.getDoc(),\r
+ sel = ed.selection,\r
+ is = tinymce.is,\r
+ inArray = tinymce.inArray,\r
+ linebr = getParam(ed, "paste_text_linebreaktype"),\r
+ rl = getParam(ed, "paste_text_replacements");\r
+\r
+ function process(items) {\r
+ each(items, function(v) {\r
+ if (v.constructor == RegExp)\r
+ h = h.replace(v, "");\r
+ else\r
+ h = h.replace(v[0], v[1]);\r
+ });\r
+ };\r
+\r
+ if ((typeof(h) === "string") && (h.length > 0)) {\r
+ // If HTML content with line-breaking tags, then remove all cr/lf chars because only tags will break a line\r
+ if (/<(?:p|br|h[1-6]|ul|ol|dl|table|t[rdh]|div|blockquote|fieldset|pre|address|center)[^>]*>/i.test(h)) {\r
+ process([\r
+ /[\n\r]+/g\r
+ ]);\r
} else {\r
- sel.select(n, 1);\r
- sel.collapse(false);\r
+ // Otherwise just get rid of carriage returns (only need linefeeds)\r
+ process([\r
+ /\r+/g\r
+ ]);\r
}\r
- };\r
\r
- // Insert a marker for the caret position\r
- this._insert('<span id="_marker"> </span>', 1);\r
- marker = dom.get('_marker');\r
- parentBlock = dom.getParent(marker, 'p,h1,h2,h3,h4,h5,h6,ul,ol');\r
+ process([\r
+ [/<\/(?: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
+ [/<br[^>]*>|<\/tr>/gi, "\n"], // Single linebreak for <br /> tags and table rows\r
+ [/<\/t[dh]>\s*<t[dh][^>]*>/gi, "\t"], // Table cells get tabs betweem them\r
+ /<[a-z!\/?][^>]*>/gi, // Delete all remaining tags\r
+ [/ /gi, " "], // Convert non-break spaces to regular spaces (remember, *plain text*)\r
+ [/(?:(?!\n)\s)*(\n+)(?:(?!\n)\s)*/gi, "$1"], // Cool little RegExp deletes whitespace around linebreak chars.\r
+ [/\n{3,}/g, "\n\n"], // Max. 2 consecutive linebreaks\r
+ /^\s+|\s+$/g // Trim the front & back\r
+ ]);\r
\r
- if (parentBlock) {\r
- // Split parent block\r
- marker = dom.split(parentBlock, marker);\r
+ h = dom.decode(tinymce.html.Entities.encodeRaw(h));\r
\r
- // Insert nodes before the marker\r
- each(dom.create('div', 0, content).childNodes, function(n) {\r
- last = marker.parentNode.insertBefore(n.cloneNode(true), marker);\r
- });\r
+ // Delete any highlighted text before pasting\r
+ if (!sel.isCollapsed()) {\r
+ d.execCommand("Delete", false, null);\r
+ }\r
\r
- // Move caret after marker\r
- select(last);\r
- } else {\r
- dom.setOuterHTML(marker, content);\r
- sel.select(ed.getBody(), 1);\r
- sel.collapse(0);\r
- }\r
+ // Perform default or custom replacements\r
+ if (is(rl, "array") || (is(rl, "array"))) {\r
+ process(rl);\r
+ }\r
+ else if (is(rl, "string")) {\r
+ process(new RegExp(rl, "gi"));\r
+ }\r
\r
- dom.remove('_marker'); // Remove marker if it's left\r
+ // Treat paragraphs as specified in the config\r
+ if (linebr == "none") {\r
+ process([\r
+ [/\n+/g, " "]\r
+ ]);\r
+ }\r
+ else if (linebr == "br") {\r
+ process([\r
+ [/\n/g, "<br />"]\r
+ ]);\r
+ }\r
+ else {\r
+ process([\r
+ /^\s+|\s+$/g,\r
+ [/\n\n/g, "</p><p>"],\r
+ [/\n/g, "<br />"]\r
+ ]);\r
+ }\r
\r
- // Get element, position and height\r
- elm = sel.getStart();\r
- vp = dom.getViewPort(ed.getWin());\r
- y = ed.dom.getPos(elm).y;\r
- elmHeight = elm.clientHeight;\r
+ // This next piece of code handles the situation where we're pasting more than one paragraph of plain\r
+ // text, and we are pasting the content into the middle of a block node in the editor. The block\r
+ // node gets split at the selection point into "Para A" and "Para B" (for the purposes of explaining).\r
+ // The first paragraph of the pasted text is appended to "Para A", and the last paragraph of the\r
+ // pasted text is prepended to "Para B". Any other paragraphs of pasted text are placed between\r
+ // "Para A" and "Para B". This code solves a host of problems with the original plain text plugin and\r
+ // now handles styles correctly. (Pasting plain text into a styled paragraph is supposed to make the\r
+ // plain text take the same style as the existing paragraph.)\r
+ if ((pos = h.indexOf("</p><p>")) != -1) {\r
+ rpos = h.lastIndexOf("</p><p>");\r
+ node = sel.getNode(); \r
+ breakElms = []; // Get list of elements to break \r
+\r
+ do {\r
+ if (node.nodeType == 1) {\r
+ // Don't break tables and break at body\r
+ if (node.nodeName == "TD" || node.nodeName == "BODY") {\r
+ break;\r
+ }\r
+\r
+ breakElms[breakElms.length] = node;\r
+ }\r
+ } while (node = node.parentNode);\r
\r
- // Is element within viewport if not then scroll it into view\r
- if (y < vp.y || y + elmHeight > vp.y + vp.h)\r
- ed.getDoc().body.scrollTop = y < vp.y ? y : y - vp.h + 25;\r
- },\r
+ // Are we in the middle of a block node?\r
+ if (breakElms.length > 0) {\r
+ before = h.substring(0, pos);\r
+ after = "";\r
\r
- /**\r
- * Inserts the specified contents at the caret position.\r
- */\r
- _insert : function(h, skip_undo) {\r
- var ed = this.editor;\r
+ for (i=0, len=breakElms.length; i<len; i++) {\r
+ before += "</" + breakElms[i].nodeName.toLowerCase() + ">";\r
+ after += "<" + breakElms[breakElms.length-i-1].nodeName.toLowerCase() + ">";\r
+ }\r
\r
- // First delete the contents seems to work better on WebKit\r
- ed.execCommand('Delete');\r
+ if (pos == rpos) {\r
+ h = before + after + h.substring(pos+7);\r
+ }\r
+ else {\r
+ h = before + h.substring(pos+4, rpos+4) + after + h.substring(rpos+7);\r
+ }\r
+ }\r
+ }\r
\r
- // It's better to use the insertHTML method on Gecko since it will combine paragraphs correctly before inserting the contents\r
- ed.execCommand(tinymce.isGecko ? 'insertHTML' : 'mceInsertContent', false, h, {skip_undo : skip_undo});\r
+ // Insert content at the caret, plus add a marker for repositioning the caret\r
+ ed.execCommand("mceInsertRawHTML", false, h + '<span id="_plain_text_marker"> </span>');\r
+\r
+ // Reposition the caret to the marker, which was placed immediately after the inserted content.\r
+ // Needs to be done asynchronously (in window.setTimeout) or else it doesn't work in all browsers.\r
+ // The second part of the code scrolls the content up if the caret is positioned off-screen.\r
+ // This is only necessary for WebKit browsers, but it doesn't hurt to use for all.\r
+ window.setTimeout(function() {\r
+ var marker = dom.get('_plain_text_marker'),\r
+ elm, vp, y, elmHeight;\r
+\r
+ sel.select(marker, false);\r
+ d.execCommand("Delete", false, null);\r
+ marker = null;\r
+\r
+ // Get element, position and height\r
+ elm = sel.getStart();\r
+ vp = dom.getViewPort(w);\r
+ y = dom.getPos(elm).y;\r
+ elmHeight = elm.clientHeight;\r
+\r
+ // Is element within viewport if not then scroll it into view\r
+ if ((y < vp.y) || (y + elmHeight > vp.y + vp.h)) {\r
+ d.body.scrollTop = y < vp.y ? y : y - vp.h + 25;\r
+ }\r
+ }, 0);\r
+ }\r
},\r
\r
/**\r
_legacySupport : function() {\r
var t = this, ed = t.editor;\r
\r
- // Register commands for backwards compatibility\r
- each(['mcePasteText', 'mcePasteWord'], function(cmd) {\r
- ed.addCommand(cmd, function() {\r
+ // Register command(s) for backwards compatibility\r
+ ed.addCommand("mcePasteWord", function() {\r
+ ed.windowManager.open({\r
+ file: t.url + "/pasteword.htm",\r
+ width: parseInt(getParam(ed, "paste_dialog_width")),\r
+ height: parseInt(getParam(ed, "paste_dialog_height")),\r
+ inline: 1\r
+ });\r
+ });\r
+\r
+ if (getParam(ed, "paste_text_use_dialog")) {\r
+ ed.addCommand("mcePasteText", function() {\r
ed.windowManager.open({\r
- file : t.url + (cmd == 'mcePasteText' ? '/pastetext.htm' : '/pasteword.htm'),\r
- width : 450,\r
- height : 400,\r
+ file : t.url + "/pastetext.htm",\r
+ width: parseInt(getParam(ed, "paste_dialog_width")),\r
+ height: parseInt(getParam(ed, "paste_dialog_height")),\r
inline : 1\r
});\r
});\r
- });\r
+ }\r
\r
- // Register buttons for backwards compatibility\r
- ed.addButton('pastetext', {title : 'paste.paste_text_desc', cmd : 'mcePasteText'});\r
- ed.addButton('pasteword', {title : 'paste.paste_word_desc', cmd : 'mcePasteWord'});\r
- ed.addButton('selectall', {title : 'paste.selectall_desc', cmd : 'selectall'});\r
+ // Register button for backwards compatibility\r
+ ed.addButton("pasteword", {title : "paste.paste_word_desc", cmd : "mcePasteWord"});\r
}\r
});\r
\r
// Register plugin\r
- tinymce.PluginManager.add('paste', tinymce.plugins.PastePlugin);\r
-})();
\ No newline at end of file
+ tinymce.PluginManager.add("paste", tinymce.plugins.PastePlugin);\r
+})();\r