2 * Compiled inline version. (Library mode)
5 /*jshint smarttabs:true, undef:true, latedef:true, curly:true, bitwise:true, camelcase:true */
8 (function(exports, undefined) {
13 function require(ids, callback) {
14 var module, defs = [];
16 for (var i = 0; i < ids.length; ++i) {
17 module = modules[ids[i]] || resolve(ids[i]);
19 throw 'module definition dependecy not found: ' + ids[i];
25 callback.apply(null, defs);
28 function define(id, dependencies, definition) {
29 if (typeof id !== 'string') {
30 throw 'invalid module definition, module id must be defined and be a string';
33 if (dependencies === undefined) {
34 throw 'invalid module definition, dependencies must be specified';
37 if (definition === undefined) {
38 throw 'invalid module definition, definition function must be specified';
41 require(dependencies, function() {
42 modules[id] = definition.apply(null, arguments);
46 function defined(id) {
50 function resolve(id) {
52 var fragments = id.split(/[.\/]/);
54 for (var fi = 0; fi < fragments.length; ++fi) {
55 if (!target[fragments[fi]]) {
59 target = target[fragments[fi]];
65 function expose(ids) {
66 for (var i = 0; i < ids.length; i++) {
69 var fragments = id.split(/[.\/]/);
71 for (var fi = 0; fi < fragments.length - 1; ++fi) {
72 if (target[fragments[fi]] === undefined) {
73 target[fragments[fi]] = {};
76 target = target[fragments[fi]];
79 target[fragments[fragments.length - 1]] = modules[id];
83 // Included from: js/tinymce/plugins/paste/classes/Utils.js
88 * Copyright, Moxiecode Systems AB
89 * Released under LGPL License.
91 * License: http://www.tinymce.com/license
92 * Contributing: http://www.tinymce.com/contributing
96 * This class contails various utility functions for the paste plugin.
98 * @class tinymce.pasteplugin.Clipboard
101 define("tinymce/pasteplugin/Utils", [
102 "tinymce/util/Tools",
103 "tinymce/html/DomParser",
104 "tinymce/html/Schema"
105 ], function(Tools, DomParser, Schema) {
106 function filter(content, items) {
107 Tools.each(items, function(v) {
108 if (v.constructor == RegExp) {
109 content = content.replace(v, '');
111 content = content.replace(v[0], v[1]);
119 * Gets the innerText of the specified element. It will handle edge cases
120 * and works better than textContent on Gecko.
122 * @param {String} html HTML string to get text from.
123 * @return {String} String of text with line feeds.
125 function innerText(html) {
126 var schema = new Schema(), domParser = new DomParser({}, schema), text = '';
127 var shortEndedElements = schema.getShortEndedElements();
128 var ignoreElements = Tools.makeMap('script noscript style textarea video audio iframe object', ' ');
129 var blockElements = schema.getBlockElements();
131 function walk(node) {
132 var name = node.name, currentNode = node;
140 if (shortEndedElements[name]) {
144 // Ingore script, video contents
145 if (ignoreElements[name]) {
150 if (node.type == 3) {
155 if (!node.shortEnded) {
156 if ((node = node.firstChild)) {
159 } while ((node = node.next));
163 // Add \n or \n\n for blocks or P
164 if (blockElements[name] && currentNode.next) {
173 html = filter(html, [
174 /<!\[[^\]]+\]>/g // Conditional comments
177 walk(domParser.parse(html));
183 * Trims the specified HTML by removing all WebKit fragments, all elements wrapping the body trailing BR elements etc.
185 * @param {String} html Html string to trim contents on.
186 * @return {String} Html contents that got trimmed.
188 function trimHtml(html) {
189 function trimSpaces(all, s1, s2) {
190 // WebKit meant to preserve multiple spaces but instead inserted around all inline tags,
191 // including the spans with inline styles created on paste
199 html = filter(html, [
200 /^[\s\S]*<body[^>]*>\s*|\s*<\/body[^>]*>[\s\S]*$/g, // Remove anything but the contents within the BODY element
201 /<!--StartFragment-->|<!--EndFragment-->/g, // Inner fragments (tables from excel on mac)
202 [/( ?)<span class="Apple-converted-space">\u00a0<\/span>( ?)/g, trimSpaces],
203 /<br>$/i // Trailing BR elements
211 innerText: innerText,
216 // Included from: js/tinymce/plugins/paste/classes/Clipboard.js
221 * Copyright, Moxiecode Systems AB
222 * Released under LGPL License.
224 * License: http://www.tinymce.com/license
225 * Contributing: http://www.tinymce.com/contributing
229 * This class contains logic for getting HTML contents out of the clipboard.
231 * We need to make a lot of ugly hacks to get the contents out of the clipboard since
232 * the W3C Clipboard API is broken in all browsers that have it: Gecko/WebKit/Blink.
233 * We might rewrite this the way those API:s stabilize. Browsers doesn't handle pasting
234 * from applications like Word the same way as it does when pasting into a contentEditable area
235 * so we need to do lots of extra work to try to get to this clipboard data.
237 * Current implementation steps:
238 * 1. On keydown with paste keys Ctrl+V or Shift+Insert create
239 * a paste bin element and move focus to that element.
240 * 2. Wait for the browser to fire a "paste" event and get the contents out of the paste bin.
241 * 3. Check if the paste was successful if true, process the HTML.
242 * (4). If the paste was unsuccessful use IE execCommand, Clipboard API, document.dataTransfer old WebKit API etc.
244 * @class tinymce.pasteplugin.Clipboard
247 define("tinymce/pasteplugin/Clipboard", [
250 "tinymce/pasteplugin/Utils"
251 ], function(Env, VK, Utils) {
252 return function(editor) {
253 var self = this, pasteBinElm, lastRng, keyboardPasteTimeStamp = 0, draggingInternally = false;
254 var pasteBinDefaultContent = '%MCEPASTEBIN%', keyboardPastePlainTextState;
257 * Pastes the specified HTML. This means that the HTML is filtered and then
258 * inserted at the current selection in the editor. It will also fire paste events
259 * for custom user filtering.
261 * @param {String} html HTML code to paste into the current selection.
263 function pasteHtml(html) {
264 var args, dom = editor.dom;
266 args = editor.fire('BeforePastePreProcess', {content: html}); // Internal event used by Quirks
267 args = editor.fire('PastePreProcess', args);
270 if (!args.isDefaultPrevented()) {
271 // User has bound PastePostProcess events then we need to pass it through a DOM node
272 // This is not ideal but we don't want to let the browser mess up the HTML for example
273 // some browsers add to P tags etc
274 if (editor.hasEventListeners('PastePostProcess') && !args.isDefaultPrevented()) {
275 // We need to attach the element to the DOM so Sizzle selectors work on the contents
276 var tempBody = dom.add(editor.getBody(), 'div', {style: 'display:none'}, html);
277 args = editor.fire('PastePostProcess', {node: tempBody});
278 dom.remove(tempBody);
279 html = args.node.innerHTML;
282 if (!args.isDefaultPrevented()) {
283 editor.insertContent(html, {merge: editor.settings.paste_merge_formats !== false});
289 * Pastes the specified text. This means that the plain text is processed
290 * and converted into BR and P elements. It will fire paste events for custom filtering.
292 * @param {String} text Text to paste as the current selection location.
294 function pasteText(text) {
295 text = editor.dom.encode(text).replace(/\r\n/g, '\n');
297 var startBlock = editor.dom.getParent(editor.selection.getStart(), editor.dom.isBlock);
299 // Create start block html for example <p attr="value">
300 var forcedRootBlockName = editor.settings.forced_root_block;
301 var forcedRootBlockStartHtml;
302 if (forcedRootBlockName) {
303 forcedRootBlockStartHtml = editor.dom.createHTML(forcedRootBlockName, editor.settings.forced_root_block_attrs);
304 forcedRootBlockStartHtml = forcedRootBlockStartHtml.substr(0, forcedRootBlockStartHtml.length - 3) + '>';
307 if ((startBlock && /^(PRE|DIV)$/.test(startBlock.nodeName)) || !forcedRootBlockName) {
308 text = Utils.filter(text, [
312 text = Utils.filter(text, [
313 [/\n\n/g, "</p>" + forcedRootBlockStartHtml],
314 [/^(.*<\/p>)(<p>)$/, forcedRootBlockStartHtml + '$1'],
318 if (text.indexOf('<p>') != -1) {
319 text = forcedRootBlockStartHtml + text;
327 * Creates a paste bin element as close as possible to the current caret location and places the focus inside that element
328 * so that when the real paste event occurs the contents gets inserted into this element
329 * instead of the current editor selection element.
331 function createPasteBin() {
332 var dom = editor.dom, body = editor.getBody();
333 var viewport = editor.dom.getViewPort(editor.getWin()), scrollTop = viewport.y, top = 20;
336 lastRng = editor.selection.getRng();
339 scrollContainer = editor.selection.getScrollContainer();
341 // Can't always rely on scrollTop returning a useful value.
342 // It returns 0 if the browser doesn't support scrollTop for the element or is non-scrollable
343 if (scrollContainer && scrollContainer.scrollTop > 0) {
344 scrollTop = scrollContainer.scrollTop;
349 * Returns the rect of the current caret if the caret is in an empty block before a
350 * BR we insert a temporary invisible character that we get the rect this way we always get a proper rect.
352 * TODO: This might be useful in core.
354 function getCaretRect(rng) {
355 var rects, textNode, node, container = rng.startContainer;
357 rects = rng.getClientRects();
362 if (!rng.collapsed || container.nodeType != 1) {
366 node = container.childNodes[lastRng.startOffset];
368 // Skip empty whitespace nodes
369 while (node && node.nodeType == 3 && !node.data.length) {
370 node = node.nextSibling;
377 // Check if the location is |<br>
378 // TODO: Might need to expand this to say |<table>
379 if (node.tagName == 'BR') {
380 textNode = dom.doc.createTextNode('\uFEFF');
381 node.parentNode.insertBefore(textNode, node);
383 rng = dom.createRng();
384 rng.setStartBefore(textNode);
385 rng.setEndAfter(textNode);
387 rects = rng.getClientRects();
388 dom.remove(textNode);
396 // Calculate top cordinate this is needed to avoid scrolling to top of document
397 // We want the paste bin to be as close to the caret as possible to avoid scrolling
398 if (lastRng.getClientRects) {
399 var rect = getCaretRect(lastRng);
402 // Client rects gets us closes to the actual
403 // caret location in for example a wrapped paragraph block
404 top = scrollTop + (rect.top - dom.getPos(body).y);
408 // Check if we can find a closer location by checking the range element
409 var container = lastRng.startContainer;
411 if (container.nodeType == 3 && container.parentNode != body) {
412 container = container.parentNode;
415 if (container.nodeType == 1) {
416 top = dom.getPos(container, scrollContainer || body).y;
423 pasteBinElm = dom.add(editor.getBody(), 'div', {
425 contentEditable: true,
426 "data-mce-bogus": "all",
427 style: 'position: absolute; top: ' + top + 'px;' +
428 'width: 10px; height: 10px; overflow: hidden; opacity: 0'
429 }, pasteBinDefaultContent);
431 // Move paste bin out of sight since the controlSelection rect gets displayed otherwise on IE and Gecko
432 if (Env.ie || Env.gecko) {
433 dom.setStyle(pasteBinElm, 'left', dom.getStyle(body, 'direction', true) == 'rtl' ? 0xFFFF : -0xFFFF);
436 // Prevent focus events from bubbeling fixed FocusManager issues
437 dom.bind(pasteBinElm, 'beforedeactivate focusin focusout', function(e) {
442 editor.selection.select(pasteBinElm, true);
446 * Removes the paste bin if it exists.
448 function removePasteBin() {
452 // WebKit/Blink might clone the div so
453 // lets make sure we remove all clones
454 // TODO: Man o man is this ugly. WebKit is the new IE! Remove this if they ever fix it!
455 while ((pasteBinClone = editor.dom.get('mcepastebin'))) {
456 editor.dom.remove(pasteBinClone);
457 editor.dom.unbind(pasteBinClone);
461 editor.selection.setRng(lastRng);
465 pasteBinElm = lastRng = null;
469 * Returns the contents of the paste bin as a HTML string.
471 * @return {String} Get the contents of the paste bin.
473 function getPasteBinHtml() {
474 var html = '', pasteBinClones, i, clone, cloneHtml;
476 // Since WebKit/Chrome might clone the paste bin when pasting
477 // for example: <img style="float: right"> we need to check if any of them contains some useful html.
478 // TODO: Man o man is this ugly. WebKit is the new IE! Remove this if they ever fix it!
479 pasteBinClones = editor.dom.select('div[id=mcepastebin]');
480 for (i = 0; i < pasteBinClones.length; i++) {
481 clone = pasteBinClones[i];
483 // Pasting plain text produces pastebins in pastebinds makes sence right!?
484 if (clone.firstChild && clone.firstChild.id == 'mcepastebin') {
485 clone = clone.firstChild;
488 cloneHtml = clone.innerHTML;
489 if (html != pasteBinDefaultContent) {
498 * Gets various content types out of a datatransfer object.
500 * @param {DataTransfer} dataTransfer Event fired on paste.
501 * @return {Object} Object with mime types and data for those mime types.
503 function getDataTransferItems(dataTransfer) {
507 // Use old WebKit/IE API
508 if (dataTransfer.getData) {
509 var legacyText = dataTransfer.getData('Text');
510 if (legacyText && legacyText.length > 0) {
511 data['text/plain'] = legacyText;
515 if (dataTransfer.types) {
516 for (var i = 0; i < dataTransfer.types.length; i++) {
517 var contentType = dataTransfer.types[i];
518 data[contentType] = dataTransfer.getData(contentType);
527 * Gets various content types out of the Clipboard API. It will also get the
528 * plain text using older IE and WebKit API:s.
530 * @param {ClipboardEvent} clipboardEvent Event fired on paste.
531 * @return {Object} Object with mime types and data for those mime types.
533 function getClipboardContent(clipboardEvent) {
534 return getDataTransferItems(clipboardEvent.clipboardData || editor.getDoc().dataTransfer);
538 * Checks if the clipboard contains image data if it does it will take that data
539 * and convert it into a data url image and paste that image at the caret location.
541 * @param {ClipboardEvent} e Paste/drop event object.
542 * @param {DOMRange} rng Optional rng object to move selection to.
543 * @return {Boolean} true/false if the image data was found or not.
545 function pasteImageData(e, rng) {
546 var dataTransfer = e.clipboardData || e.dataTransfer;
548 function processItems(items) {
551 function pasteImage() {
553 editor.selection.setRng(rng);
557 pasteHtml('<img src="' + reader.result + '">');
561 for (i = 0; i < items.length; i++) {
564 if (/^image\/(jpeg|png|gif)$/.test(item.type)) {
565 reader = new FileReader();
566 reader.onload = pasteImage;
567 reader.readAsDataURL(item.getAsFile ? item.getAsFile() : item);
576 if (editor.settings.paste_data_images && dataTransfer) {
577 return processItems(dataTransfer.items) || processItems(dataTransfer.files);
582 * Chrome on Android doesn't support proper clipboard access so we have no choice but to allow the browser default behavior.
584 * @param {Event} e Paste event object to check if it contains any data.
585 * @return {Boolean} true/false if the clipboard is empty or not.
587 function isBrokenAndroidClipboardEvent(e) {
588 var clipboardData = e.clipboardData;
590 return navigator.userAgent.indexOf('Android') != -1 && clipboardData && clipboardData.items && clipboardData.items.length === 0;
593 function getCaretRangeFromEvent(e) {
594 var doc = editor.getDoc(), rng, point;
596 if (doc.caretPositionFromPoint) {
597 point = doc.caretPositionFromPoint(e.clientX, e.clientY);
598 rng = doc.createRange();
599 rng.setStart(point.offsetNode, point.offset);
601 } else if (doc.caretRangeFromPoint) {
602 rng = doc.caretRangeFromPoint(e.clientX, e.clientY);
603 } else if (doc.body.createTextRange) {
604 rng = doc.body.createTextRange();
607 rng.moveToPoint(e.clientX, e.clientY);
610 // Append to top or bottom depending on drop location
611 rng.collapse(e.clientY < doc.body.clientHeight);
618 function hasContentType(clipboardContent, mimeType) {
619 return mimeType in clipboardContent && clipboardContent[mimeType].length > 0;
622 function isKeyboardPasteEvent(e) {
623 return (VK.metaKeyPressed(e) && e.keyCode == 86) || (e.shiftKey && e.keyCode == 45);
626 function registerEventHandlers() {
627 editor.on('keydown', function(e) {
628 function removePasteBinOnKeyUp(e) {
629 // Ctrl+V or Shift+Insert
630 if (isKeyboardPasteEvent(e) && !e.isDefaultPrevented()) {
635 // Ctrl+V or Shift+Insert
636 if (isKeyboardPasteEvent(e) && !e.isDefaultPrevented()) {
637 keyboardPastePlainTextState = e.shiftKey && e.keyCode == 86;
639 // Edge case on Safari on Mac where it doesn't handle Cmd+Shift+V correctly
640 // it fires the keydown but no paste or keyup so we are left with a paste bin
641 if (keyboardPastePlainTextState && Env.webkit && navigator.userAgent.indexOf('Version/') != -1) {
645 // Prevent undoManager keydown handler from making an undo level with the pastebin in it
646 e.stopImmediatePropagation();
648 keyboardPasteTimeStamp = new Date().getTime();
650 // IE doesn't support Ctrl+Shift+V and it doesn't even produce a paste event
651 // so lets fake a paste event and let IE use the execCommand/dataTransfer methods
652 if (Env.ie && keyboardPastePlainTextState) {
654 editor.fire('paste', {ieFake: true});
661 // Remove pastebin if we get a keyup and no paste event
662 // For example pasting a file in IE 11 will not produce a paste event
663 editor.once('keyup', removePasteBinOnKeyUp);
664 editor.once('paste', function() {
665 editor.off('keyup', removePasteBinOnKeyUp);
670 editor.on('paste', function(e) {
671 // Getting content from the Clipboard can take some time
672 var clipboardTimer = new Date().getTime();
673 var clipboardContent = getClipboardContent(e);
674 var clipboardDelay = new Date().getTime() - clipboardTimer;
676 var isKeyBoardPaste = (new Date().getTime() - keyboardPasteTimeStamp - clipboardDelay) < 1000;
677 var plainTextMode = self.pasteFormat == "text" || keyboardPastePlainTextState;
679 keyboardPastePlainTextState = false;
681 if (e.isDefaultPrevented() || isBrokenAndroidClipboardEvent(e)) {
686 if (pasteImageData(e)) {
691 // Not a keyboard paste prevent default paste and try to grab the clipboard contents using different APIs
692 if (!isKeyBoardPaste) {
696 // Try IE only method if paste isn't a keyboard paste
697 if (Env.ie && (!isKeyBoardPaste || e.ieFake)) {
700 editor.dom.bind(pasteBinElm, 'paste', function(e) {
704 editor.getDoc().execCommand('Paste', false, null);
705 clipboardContent["text/html"] = getPasteBinHtml();
708 setTimeout(function() {
711 // Grab HTML from Clipboard API or paste bin as a fallback
712 if (hasContentType(clipboardContent, 'text/html')) {
713 content = clipboardContent['text/html'];
715 content = getPasteBinHtml();
717 // If paste bin is empty try using plain text mode
718 // since that is better than nothing right
719 if (content == pasteBinDefaultContent) {
720 plainTextMode = true;
724 content = Utils.trimHtml(content);
726 // WebKit has a nice bug where it clones the paste bin if you paste from for example notepad
727 // so we need to force plain text mode in this case
728 if (pasteBinElm && pasteBinElm.firstChild && pasteBinElm.firstChild.id === 'mcepastebin') {
729 plainTextMode = true;
734 // If we got nothing from clipboard API and pastebin then we could try the last resort: plain/text
735 if (!content.length) {
736 plainTextMode = true;
739 // Grab plain text from Clipboard API or convert existing HTML to plain text
741 // Use plain text contents from Clipboard API unless the HTML contains paragraphs then
742 // we should convert the HTML to plain text since works better when pasting HTML/Word contents as plain text
743 if (hasContentType(clipboardContent, 'text/plain') && content.indexOf('</p>') == -1) {
744 content = clipboardContent['text/plain'];
746 content = Utils.innerText(content);
750 // If the content is the paste bin default HTML then it was
751 // impossible to get the cliboard data out.
752 if (content == pasteBinDefaultContent) {
753 if (!isKeyBoardPaste) {
754 editor.windowManager.alert('Please use Ctrl+V/Cmd+V keyboard shortcuts to paste contents.');
768 editor.on('dragstart dragend', function(e) {
769 draggingInternally = e.type == 'dragstart';
772 editor.on('drop', function(e) {
773 var rng = getCaretRangeFromEvent(e);
775 if (e.isDefaultPrevented() || draggingInternally) {
779 if (pasteImageData(e, rng)) {
783 if (rng && editor.settings.paste_filter_drop !== false) {
784 var dropContent = getDataTransferItems(e.dataTransfer);
785 var content = dropContent['mce-internal'] || dropContent['text/html'] || dropContent['text/plain'];
790 editor.undoManager.transact(function() {
791 if (dropContent['mce-internal']) {
792 editor.execCommand('Delete');
795 editor.selection.setRng(rng);
797 content = Utils.trimHtml(content);
799 if (!dropContent['text/html']) {
809 editor.on('dragover dragend', function(e) {
810 var i, dataTransfer = e.dataTransfer;
812 if (editor.settings.paste_data_images && dataTransfer) {
813 for (i = 0; i < dataTransfer.types.length; i++) {
814 // Prevent default if we have files dragged into the editor since the pasteImageData handles that
815 if (dataTransfer.types[i] == "Files") {
824 self.pasteHtml = pasteHtml;
825 self.pasteText = pasteText;
827 editor.on('preInit', function() {
828 registerEventHandlers();
830 // Remove all data images from paste for example from Gecko
831 // except internal images like video elements
832 editor.parser.addNodeFilter('img', function(nodes) {
833 if (!editor.settings.paste_data_images) {
834 var i = nodes.length;
837 var src = nodes[i].attributes.map.src;
839 // Some browsers automatically produce data uris on paste
840 // Safari on Mac produces webkit-fake-url see: https://bugs.webkit.org/show_bug.cgi?id=49141
841 if (src && /^(data:image|webkit\-fake\-url)/.test(src)) {
842 if (!nodes[i].attr('data-mce-object') && src !== Env.transparentSrc) {
853 // Included from: js/tinymce/plugins/paste/classes/WordFilter.js
858 * Copyright, Moxiecode Systems AB
859 * Released under LGPL License.
861 * License: http://www.tinymce.com/license
862 * Contributing: http://www.tinymce.com/contributing
866 * This class parses word HTML into proper TinyMCE markup.
868 * @class tinymce.pasteplugin.Quirks
871 define("tinymce/pasteplugin/WordFilter", [
872 "tinymce/util/Tools",
873 "tinymce/html/DomParser",
874 "tinymce/html/Schema",
875 "tinymce/html/Serializer",
877 "tinymce/pasteplugin/Utils"
878 ], function(Tools, DomParser, Schema, Serializer, Node, Utils) {
880 * Checks if the specified content is from any of the following sources: MS Word/Office 365/Google docs.
882 function isWordContent(content) {
884 (/<font face="Times New Roman"|class="?Mso|style="[^"]*\bmso-|style='[^'']*\bmso-|w:WordDocument/i).test(content) ||
885 (/class="OutlineElement/).test(content) ||
886 (/id="?docs\-internal\-guid\-/.test(content))
891 * Checks if the specified text starts with "1. " or "a. " etc.
893 function isNumericList(text) {
897 /^[IVXLMCD]{1,2}\.[ \u00a0]/, // Roman upper case
898 /^[ivxlmcd]{1,2}\.[ \u00a0]/, // Roman lower case
899 /^[a-z]{1,2}[\.\)][ \u00a0]/, // Alphabetical a-z
900 /^[A-Z]{1,2}[\.\)][ \u00a0]/, // Alphabetical A-Z
901 /^[0-9]+\.[ \u00a0]/, // Numeric lists
902 /^[\u3007\u4e00\u4e8c\u4e09\u56db\u4e94\u516d\u4e03\u516b\u4e5d]+\.[ \u00a0]/, // Japanese
903 /^[\u58f1\u5f10\u53c2\u56db\u4f0d\u516d\u4e03\u516b\u4e5d\u62fe]+\.[ \u00a0]/ // Chinese
906 text = text.replace(/^[\u00a0 ]+/, '');
908 Tools.each(patterns, function(pattern) {
909 if (pattern.test(text)) {
918 function isBulletList(text) {
919 return /^[\s\u00a0]*[\u2022\u00b7\u00a7\u00d8\u25CF]\s*/.test(text);
922 function WordFilter(editor) {
923 var settings = editor.settings;
925 editor.on('BeforePastePreProcess', function(e) {
926 var content = e.content, retainStyleProperties, validStyles;
928 retainStyleProperties = settings.paste_retain_style_properties;
929 if (retainStyleProperties) {
930 validStyles = Tools.makeMap(retainStyleProperties.split(/[, ]/));
934 * Converts fake bullet and numbered lists to real semantic OL/UL.
936 * @param {tinymce.html.Node} node Root node to convert children of.
938 function convertFakeListsToProperLists(node) {
939 var currentListNode, prevListNode, lastLevel = 1;
941 function getText(node) {
944 if (node.type === 3) {
948 if ((node = node.firstChild)) {
950 txt += getText(node);
951 } while ((node = node.next));
957 function trimListStart(node, regExp) {
958 if (node.type === 3) {
959 if (regExp.test(node.value)) {
960 node.value = node.value.replace(regExp, '');
965 if ((node = node.firstChild)) {
967 if (!trimListStart(node, regExp)) {
970 } while ((node = node.next));
976 function removeIgnoredNodes(node) {
977 if (node._listIgnore) {
982 if ((node = node.firstChild)) {
984 removeIgnoredNodes(node);
985 } while ((node = node.next));
989 function convertParagraphToLi(paragraphNode, listName, start) {
990 var level = paragraphNode._listLevel || lastLevel;
992 // Handle list nesting
993 if (level != lastLevel) {
994 if (level < lastLevel) {
995 // Move to parent list
996 if (currentListNode) {
997 currentListNode = currentListNode.parent.parent;
1001 prevListNode = currentListNode;
1002 currentListNode = null;
1006 if (!currentListNode || currentListNode.name != listName) {
1007 prevListNode = prevListNode || currentListNode;
1008 currentListNode = new Node(listName, 1);
1011 currentListNode.attr('start', '' + start);
1014 paragraphNode.wrap(currentListNode);
1016 currentListNode.append(paragraphNode);
1019 paragraphNode.name = 'li';
1021 // Append list to previous list if it exists
1022 if (level > lastLevel && prevListNode) {
1023 prevListNode.lastChild.append(currentListNode);
1028 // Remove start of list item "1. " or "· " etc
1029 removeIgnoredNodes(paragraphNode);
1030 trimListStart(paragraphNode, /^\u00a0+/);
1031 trimListStart(paragraphNode, /^\s*([\u2022\u00b7\u00a7\u00d8\u25CF]|\w+\.)/);
1032 trimListStart(paragraphNode, /^\u00a0+/);
1035 // Build a list of all root level elements before we start
1036 // altering them in the loop below.
1037 var elements = [], child = node.firstChild;
1038 while (typeof child !== 'undefined' && child !== null) {
1039 elements.push(child);
1041 child = child.walk();
1042 if (child !== null) {
1043 while (typeof child !== 'undefined' && child.parent !== node) {
1044 child = child.walk();
1049 for (var i = 0; i < elements.length; i++) {
1052 if (node.name == 'p' && node.firstChild) {
1053 // Find first text node in paragraph
1054 var nodeText = getText(node);
1056 // Detect unordered lists look for bullets
1057 if (isBulletList(nodeText)) {
1058 convertParagraphToLi(node, 'ul');
1062 // Detect ordered lists 1., a. or ixv.
1063 if (isNumericList(nodeText)) {
1064 // Parse OL start number
1065 var matches = /([0-9]+)\./.exec(nodeText);
1068 start = parseInt(matches[1], 10);
1071 convertParagraphToLi(node, 'ol', start);
1075 // Convert paragraphs marked as lists but doesn't look like anything
1076 if (node._listLevel) {
1077 convertParagraphToLi(node, 'ul', 1);
1081 currentListNode = null;
1083 // If the root level element isn't a p tag which can be
1084 // processed by convertParagraphToLi, it interrupts the
1085 // lists, causing a new list to start instead of having
1086 // elements from the next list inserted above this tag.
1087 prevListNode = currentListNode;
1088 currentListNode = null;
1093 function filterStyles(node, styleValue) {
1094 var outputStyles = {}, matches, styles = editor.dom.parseStyle(styleValue);
1096 Tools.each(styles, function(value, name) {
1097 // Convert various MS styles to W3C styles
1100 // Parse out list indent level for lists
1101 matches = /\w+ \w+([0-9]+)/i.exec(styleValue);
1103 node._listLevel = parseInt(matches[1], 10);
1106 // Remove these nodes <span style="mso-list:Ignore">o</span>
1107 // Since the span gets removed we mark the text node and the span
1108 if (/Ignore/i.test(value) && node.firstChild) {
1109 node._listIgnore = true;
1110 node.firstChild._listIgnore = true;
1116 name = "text-align";
1120 name = "vertical-align";
1124 case "mso-foreground":
1128 case "mso-background":
1129 case "mso-highlight":
1130 name = "background";
1135 if (value != "normal") {
1136 outputStyles[name] = value;
1141 // Remove track changes code
1142 if (/^(comment|comment-list)$/i.test(value)) {
1150 if (name.indexOf('mso-comment') === 0) {
1155 // Never allow mso- prefixed names
1156 if (name.indexOf('mso-') === 0) {
1160 // Output only valid styles
1161 if (retainStyleProperties == "all" || (validStyles && validStyles[name])) {
1162 outputStyles[name] = value;
1166 // Convert bold style to "b" element
1167 if (/(bold)/i.test(outputStyles["font-weight"])) {
1168 delete outputStyles["font-weight"];
1169 node.wrap(new Node("b", 1));
1172 // Convert italic style to "i" element
1173 if (/(italic)/i.test(outputStyles["font-style"])) {
1174 delete outputStyles["font-style"];
1175 node.wrap(new Node("i", 1));
1178 // Serialize the styles and see if there is something left to keep
1179 outputStyles = editor.dom.serializeStyle(outputStyles, node.name);
1181 return outputStyles;
1187 if (settings.paste_enable_default_filters === false) {
1191 // Detect is the contents is Word junk HTML
1192 if (isWordContent(e.content)) {
1193 e.wordContent = true; // Mark it for other processors
1195 // Remove basic Word junk
1196 content = Utils.filter(content, [
1197 // Word comments like conditional comments etc
1198 /<!--[\s\S]+?-->/gi,
1200 // Remove comments, scripts (e.g., msoShowComment), XML tag, VML content,
1201 // MS Office namespaced tags, and a few other tags
1202 /<(!|script[^>]*>.*?<\/script(?=[>\s])|\/?(\?xml(:\w+)?|img|meta|link|style|\w:\w+)(?=[\s\/>]))[^>]*>/gi,
1204 // Convert <s> into <strike> for line-though
1205 [/<(\/?)s>/gi, "<$1strike>"],
1207 // Replace nsbp entites to char since it's easier to handle
1208 [/ /gi, "\u00a0"],
1210 // Convert <span style="mso-spacerun:yes">___</span> to string of alternating
1211 // breaking/non-breaking spaces of same length
1212 [/<span\s+style\s*=\s*"\s*mso-spacerun\s*:\s*yes\s*;?\s*"\s*>([\s\u00a0]*)<\/span>/gi,
1213 function(str, spaces) {
1214 return (spaces.length > 0) ?
1215 spaces.replace(/./, " ").slice(Math.floor(spaces.length / 2)).split("").join("\u00a0") : "";
1220 var validElements = settings.paste_word_valid_elements;
1221 if (!validElements) {
1223 '-strong/b,-em/i,-u,-span,-p,-ol,-ul,-li,-h1,-h2,-h3,-h4,-h5,-h6,' +
1224 '-p/div,-a[href|name],sub,sup,strike,br,del,table[width],tr,' +
1225 'td[colspan|rowspan|width],th[colspan|rowspan|width],thead,tfoot,tbody'
1229 // Setup strict schema
1230 var schema = new Schema({
1231 valid_elements: validElements,
1232 valid_children: '-li[p]'
1235 // Add style/class attribute to all element rules since the user might have removed them from
1236 // paste_word_valid_elements config option and we need to check them for properties
1237 Tools.each(schema.elements, function(rule) {
1238 if (!rule.attributes["class"]) {
1239 rule.attributes["class"] = {};
1240 rule.attributesOrder.push("class");
1243 if (!rule.attributes.style) {
1244 rule.attributes.style = {};
1245 rule.attributesOrder.push("style");
1249 // Parse HTML into DOM structure
1250 var domParser = new DomParser({}, schema);
1252 // Filter styles to remove "mso" specific styles and convert some of them
1253 domParser.addAttributeFilter('style', function(nodes) {
1254 var i = nodes.length, node;
1258 node.attr('style', filterStyles(node, node.attr('style')));
1260 // Remove pointess spans
1261 if (node.name == 'span' && node.parent && !node.attributes.length) {
1267 // Check the class attribute for comments or del items and remove those
1268 domParser.addAttributeFilter('class', function(nodes) {
1269 var i = nodes.length, node, className;
1274 className = node.attr('class');
1275 if (/^(MsoCommentReference|MsoCommentText|msoDel|MsoCaption)$/i.test(className)) {
1279 node.attr('class', null);
1283 // Remove all del elements since we don't want the track changes code in the editor
1284 domParser.addNodeFilter('del', function(nodes) {
1285 var i = nodes.length;
1292 // Keep some of the links and anchors
1293 domParser.addNodeFilter('a', function(nodes) {
1294 var i = nodes.length, node, href, name;
1298 href = node.attr('href');
1299 name = node.attr('name');
1301 if (href && href.indexOf('#_msocom_') != -1) {
1306 if (href && href.indexOf('file://') === 0) {
1307 href = href.split('#')[1];
1313 if (!href && !name) {
1316 // Remove all named anchors that aren't specific to TOC, Footnotes or Endnotes
1317 if (name && !/^_?(?:toc|edn|ftn)/i.test(name)) {
1330 // Parse into DOM structure
1331 var rootNode = domParser.parse(content);
1334 if (settings.paste_convert_word_fake_lists !== false) {
1335 convertFakeListsToProperLists(rootNode);
1338 // Serialize DOM back to HTML
1339 e.content = new Serializer({}, schema).serialize(rootNode);
1344 WordFilter.isWordContent = isWordContent;
1349 // Included from: js/tinymce/plugins/paste/classes/Quirks.js
1354 * Copyright, Moxiecode Systems AB
1355 * Released under LGPL License.
1357 * License: http://www.tinymce.com/license
1358 * Contributing: http://www.tinymce.com/contributing
1362 * This class contains various fixes for browsers. These issues can not be feature
1363 * detected since we have no direct control over the clipboard. However we might be able
1364 * to remove some of these fixes once the browsers gets updated/fixed.
1366 * @class tinymce.pasteplugin.Quirks
1369 define("tinymce/pasteplugin/Quirks", [
1371 "tinymce/util/Tools",
1372 "tinymce/pasteplugin/WordFilter",
1373 "tinymce/pasteplugin/Utils"
1374 ], function(Env, Tools, WordFilter, Utils) {
1377 return function(editor) {
1378 function addPreProcessFilter(filterFunc) {
1379 editor.on('BeforePastePreProcess', function(e) {
1380 e.content = filterFunc(e.content);
1385 * Removes BR elements after block elements. IE9 has a nasty bug where it puts a BR element after each
1386 * block element when pasting from word. This removes those elements.
1389 * <p>a</p><br><p>b</p>
1394 function removeExplorerBrElementsAfterBlocks(html) {
1395 // Only filter word specific content
1396 if (!WordFilter.isWordContent(html)) {
1400 // Produce block regexp based on the block elements in schema
1401 var blockElements = [];
1403 Tools.each(editor.schema.getBlockElements(), function(block, blockName) {
1404 blockElements.push(blockName);
1407 var explorerBlocksRegExp = new RegExp(
1408 '(?:<br> [\\s\\r\\n]+|<br>)*(<\\/?(' + blockElements.join('|') + ')[^>]*>)(?:<br> [\\s\\r\\n]+|<br>)*',
1412 // Remove BR:s from: <BLOCK>X</BLOCK><BR>
1413 html = Utils.filter(html, [
1414 [explorerBlocksRegExp, '$1']
1417 // IE9 also adds an extra BR element for each soft-linefeed and it also adds a BR for each word wrap break
1418 html = Utils.filter(html, [
1419 [/<br><br>/g, '<BR><BR>'], // Replace multiple BR elements with uppercase BR to keep them intact
1420 [/<br>/g, ' '], // Replace single br elements with space since they are word wrap BR:s
1421 [/<BR><BR>/g, '<br>'] // Replace back the double brs but into a single BR
1428 * WebKit has a nasty bug where the all computed styles gets added to style attributes when copy/pasting contents.
1429 * This fix solves that by simply removing the whole style attribute.
1431 * The paste_webkit_styles option can be set to specify what to keep:
1432 * paste_webkit_styles: "none" // Keep no styles
1433 * paste_webkit_styles: "all", // Keep all of them
1434 * paste_webkit_styles: "font-weight color" // Keep specific ones
1436 * @param {String} content Content that needs to be processed.
1437 * @return {String} Processed contents.
1439 function removeWebKitStyles(content) {
1440 // Passthrough all styles from Word and let the WordFilter handle that junk
1441 if (WordFilter.isWordContent(content)) {
1445 // Filter away styles that isn't matching the target node
1446 var webKitStyles = editor.settings.paste_webkit_styles;
1448 if (editor.settings.paste_remove_styles_if_webkit === false || webKitStyles == "all") {
1453 webKitStyles = webKitStyles.split(/[, ]/);
1456 // Keep specific styles that doesn't match the current node computed style
1458 var dom = editor.dom, node = editor.selection.getNode();
1460 content = content.replace(/(<[^>]+) style="([^"]*)"([^>]*>)/gi, function(all, before, value, after) {
1461 var inputStyles = dom.parseStyle(value, 'span'), outputStyles = {};
1463 if (webKitStyles === "none") {
1464 return before + after;
1467 for (var i = 0; i < webKitStyles.length; i++) {
1468 var inputValue = inputStyles[webKitStyles[i]], currentValue = dom.getStyle(node, webKitStyles[i], true);
1470 if (/color/.test(webKitStyles[i])) {
1471 inputValue = dom.toHex(inputValue);
1472 currentValue = dom.toHex(currentValue);
1475 if (currentValue != inputValue) {
1476 outputStyles[webKitStyles[i]] = inputValue;
1480 outputStyles = dom.serializeStyle(outputStyles, 'span');
1482 return before + ' style="' + outputStyles + '"' + after;
1485 return before + after;
1488 // Remove all external styles
1489 content = content.replace(/(<[^>]+) style="([^"]*)"([^>]*>)/gi, '$1$3');
1492 // Keep internal styles
1493 content = content.replace(/(<[^>]+) data-mce-style="([^"]+)"([^>]*>)/gi, function(all, before, value, after) {
1494 return before + ' style="' + value + '"' + after;
1500 // Sniff browsers and apply fixes since we can't feature detect
1502 addPreProcessFilter(removeWebKitStyles);
1506 addPreProcessFilter(removeExplorerBrElementsAfterBlocks);
1511 // Included from: js/tinymce/plugins/paste/classes/Plugin.js
1516 * Copyright, Moxiecode Systems AB
1517 * Released under LGPL License.
1519 * License: http://www.tinymce.com/license
1520 * Contributing: http://www.tinymce.com/contributing
1524 * This class contains the tinymce plugin logic for the paste plugin.
1526 * @class tinymce.pasteplugin.Plugin
1529 define("tinymce/pasteplugin/Plugin", [
1530 "tinymce/PluginManager",
1531 "tinymce/pasteplugin/Clipboard",
1532 "tinymce/pasteplugin/WordFilter",
1533 "tinymce/pasteplugin/Quirks"
1534 ], function(PluginManager, Clipboard, WordFilter, Quirks) {
1537 PluginManager.add('paste', function(editor) {
1538 var self = this, clipboard, settings = editor.settings;
1540 function togglePlainTextPaste() {
1541 if (clipboard.pasteFormat == "text") {
1543 clipboard.pasteFormat = "html";
1545 clipboard.pasteFormat = "text";
1548 if (!userIsInformed) {
1549 editor.windowManager.alert(
1550 'Paste is now in plain text mode. Contents will now ' +
1551 'be pasted as plain text until you toggle this option off.'
1554 userIsInformed = true;
1559 self.clipboard = clipboard = new Clipboard(editor);
1560 self.quirks = new Quirks(editor);
1561 self.wordFilter = new WordFilter(editor);
1563 if (editor.settings.paste_as_text) {
1564 self.clipboard.pasteFormat = "text";
1567 if (settings.paste_preprocess) {
1568 editor.on('PastePreProcess', function(e) {
1569 settings.paste_preprocess.call(self, self, e);
1573 if (settings.paste_postprocess) {
1574 editor.on('PastePostProcess', function(e) {
1575 settings.paste_postprocess.call(self, self, e);
1579 editor.addCommand('mceInsertClipboardContent', function(ui, value) {
1580 if (value.content) {
1581 self.clipboard.pasteHtml(value.content);
1585 self.clipboard.pasteText(value.text);
1589 // Block all drag/drop events
1590 if (editor.paste_block_drop) {
1591 editor.on('dragend dragover draggesture dragdrop drop drag', function(e) {
1593 e.stopPropagation();
1597 // Prevent users from dropping data images on Gecko
1598 if (!editor.settings.paste_data_images) {
1599 editor.on('drop', function(e) {
1600 var dataTransfer = e.dataTransfer;
1602 if (dataTransfer && dataTransfer.files && dataTransfer.files.length > 0) {
1608 editor.addButton('pastetext', {
1610 tooltip: 'Paste as text',
1611 onclick: togglePlainTextPaste,
1612 active: self.clipboard.pasteFormat == "text"
1615 editor.addMenuItem('pastetext', {
1616 text: 'Paste as text',
1618 active: clipboard.pasteFormat,
1619 onclick: togglePlainTextPaste
1624 expose(["tinymce/pasteplugin/Utils","tinymce/pasteplugin/WordFilter"]);