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 var i, target, id, fragments, privateModules;
68 for (i = 0; i < ids.length; i++) {
71 fragments = id.split(/[.\/]/);
73 for (var fi = 0; fi < fragments.length - 1; ++fi) {
74 if (target[fragments[fi]] === undefined) {
75 target[fragments[fi]] = {};
78 target = target[fragments[fi]];
81 target[fragments[fragments.length - 1]] = modules[id];
84 // Expose private modules for unit tests
85 if (exports.AMDLC_TESTS) {
86 privateModules = exports.privateModules || {};
89 privateModules[id] = modules[id];
92 for (i = 0; i < ids.length; i++) {
93 delete privateModules[ids[i]];
96 exports.privateModules = privateModules;
100 // Included from: js/tinymce/plugins/paste/classes/Utils.js
105 * Released under LGPL License.
106 * Copyright (c) 1999-2015 Ephox Corp. All rights reserved
108 * License: http://www.tinymce.com/license
109 * Contributing: http://www.tinymce.com/contributing
113 * This class contails various utility functions for the paste plugin.
115 * @class tinymce.pasteplugin.Utils
117 define("tinymce/pasteplugin/Utils", [
118 "tinymce/util/Tools",
119 "tinymce/html/DomParser",
120 "tinymce/html/Schema"
121 ], function(Tools, DomParser, Schema) {
122 function filter(content, items) {
123 Tools.each(items, function(v) {
124 if (v.constructor == RegExp) {
125 content = content.replace(v, '');
127 content = content.replace(v[0], v[1]);
135 * Gets the innerText of the specified element. It will handle edge cases
136 * and works better than textContent on Gecko.
138 * @param {String} html HTML string to get text from.
139 * @return {String} String of text with line feeds.
141 function innerText(html) {
142 var schema = new Schema(), domParser = new DomParser({}, schema), text = '';
143 var shortEndedElements = schema.getShortEndedElements();
144 var ignoreElements = Tools.makeMap('script noscript style textarea video audio iframe object', ' ');
145 var blockElements = schema.getBlockElements();
147 function walk(node) {
148 var name = node.name, currentNode = node;
156 if (shortEndedElements[name]) {
160 // Ingore script, video contents
161 if (ignoreElements[name]) {
166 if (node.type == 3) {
171 if (!node.shortEnded) {
172 if ((node = node.firstChild)) {
175 } while ((node = node.next));
179 // Add \n or \n\n for blocks or P
180 if (blockElements[name] && currentNode.next) {
189 html = filter(html, [
190 /<!\[[^\]]+\]>/g // Conditional comments
193 walk(domParser.parse(html));
199 * Trims the specified HTML by removing all WebKit fragments, all elements wrapping the body trailing BR elements etc.
201 * @param {String} html Html string to trim contents on.
202 * @return {String} Html contents that got trimmed.
204 function trimHtml(html) {
205 function trimSpaces(all, s1, s2) {
206 // WebKit meant to preserve multiple spaces but instead inserted around all inline tags,
207 // including the spans with inline styles created on paste
215 html = filter(html, [
216 /^[\s\S]*<body[^>]*>\s*|\s*<\/body[^>]*>[\s\S]*$/g, // Remove anything but the contents within the BODY element
217 /<!--StartFragment-->|<!--EndFragment-->/g, // Inner fragments (tables from excel on mac)
218 [/( ?)<span class="Apple-converted-space">\u00a0<\/span>( ?)/g, trimSpaces],
219 /<br class="Apple-interchange-newline">/g,
220 /<br>$/i // Trailing BR elements
226 // TODO: Should be in some global class
227 function createIdGenerator(prefix) {
231 return prefix + (count++);
237 innerText: innerText,
239 createIdGenerator: createIdGenerator
243 // Included from: js/tinymce/plugins/paste/classes/SmartPaste.js
248 * Released under LGPL License.
249 * Copyright (c) 1999-2016 Ephox Corp. All rights reserved
251 * License: http://www.tinymce.com/license
252 * Contributing: http://www.tinymce.com/contributing
256 * Tries to be smart depending on what the user pastes if it looks like an url
257 * it will make a link out of the current selection. If it's an image url that looks
258 * like an image it will check if it's an image and insert it as an image.
260 * @class tinymce.pasteplugin.SmartPaste
263 define("tinymce/pasteplugin/SmartPaste", [
265 ], function (Tools) {
266 var isAbsoluteUrl = function (url) {
267 return /^https?:\/\/[\w\?\-\/+=.&%@~#]+$/i.test(url);
270 var isImageUrl = function (url) {
271 return isAbsoluteUrl(url) && /.(gif|jpe?g|png)$/.test(url);
274 var createImage = function (editor, url, pasteHtml) {
275 editor.undoManager.extra(function () {
276 pasteHtml(editor, url);
278 editor.insertContent('<img src="' + url + '">');
284 var createLink = function (editor, url, pasteHtml) {
285 editor.undoManager.extra(function () {
286 pasteHtml(editor, url);
288 editor.execCommand('mceInsertLink', false, url);
294 var linkSelection = function (editor, html, pasteHtml) {
295 return editor.selection.isCollapsed() === false && isAbsoluteUrl(html) ? createLink(editor, html, pasteHtml) : false;
298 var insertImage = function (editor, html, pasteHtml) {
299 return isImageUrl(html) ? createImage(editor, html, pasteHtml) : false;
302 var pasteHtml = function (editor, html) {
303 editor.insertContent(html, {
304 merge: editor.settings.paste_merge_formats !== false,
311 var smartInsertContent = function (editor, html) {
316 ], function (action) {
317 return action(editor, html, pasteHtml) !== true;
321 var insertContent = function (editor, html) {
322 if (editor.settings.smart_paste === false) {
323 pasteHtml(editor, html);
325 smartInsertContent(editor, html);
330 isImageUrl: isImageUrl,
331 isAbsoluteUrl: isAbsoluteUrl,
332 insertContent: insertContent
336 // Included from: js/tinymce/plugins/paste/classes/Clipboard.js
341 * Released under LGPL License.
342 * Copyright (c) 1999-2015 Ephox Corp. All rights reserved
344 * License: http://www.tinymce.com/license
345 * Contributing: http://www.tinymce.com/contributing
349 * This class contains logic for getting HTML contents out of the clipboard.
351 * We need to make a lot of ugly hacks to get the contents out of the clipboard since
352 * the W3C Clipboard API is broken in all browsers that have it: Gecko/WebKit/Blink.
353 * We might rewrite this the way those API:s stabilize. Browsers doesn't handle pasting
354 * from applications like Word the same way as it does when pasting into a contentEditable area
355 * so we need to do lots of extra work to try to get to this clipboard data.
357 * Current implementation steps:
358 * 1. On keydown with paste keys Ctrl+V or Shift+Insert create
359 * a paste bin element and move focus to that element.
360 * 2. Wait for the browser to fire a "paste" event and get the contents out of the paste bin.
361 * 3. Check if the paste was successful if true, process the HTML.
362 * (4). If the paste was unsuccessful use IE execCommand, Clipboard API, document.dataTransfer old WebKit API etc.
364 * @class tinymce.pasteplugin.Clipboard
367 define("tinymce/pasteplugin/Clipboard", [
369 "tinymce/dom/RangeUtils",
371 "tinymce/pasteplugin/Utils",
372 "tinymce/pasteplugin/SmartPaste",
374 ], function(Env, RangeUtils, VK, Utils, SmartPaste, Delay) {
375 return function(editor) {
376 var self = this, pasteBinElm, lastRng, keyboardPasteTimeStamp = 0, draggingInternally = false;
377 var pasteBinDefaultContent = '%MCEPASTEBIN%', keyboardPastePlainTextState;
378 var mceInternalUrlPrefix = 'data:text/mce-internal,';
379 var uniqueId = Utils.createIdGenerator("mceclip");
382 * Pastes the specified HTML. This means that the HTML is filtered and then
383 * inserted at the current selection in the editor. It will also fire paste events
384 * for custom user filtering.
386 * @param {String} html HTML code to paste into the current selection.
388 function pasteHtml(html) {
389 var args, dom = editor.dom;
391 args = editor.fire('BeforePastePreProcess', {content: html}); // Internal event used by Quirks
392 args = editor.fire('PastePreProcess', args);
395 if (!args.isDefaultPrevented()) {
396 // User has bound PastePostProcess events then we need to pass it through a DOM node
397 // This is not ideal but we don't want to let the browser mess up the HTML for example
398 // some browsers add to P tags etc
399 if (editor.hasEventListeners('PastePostProcess') && !args.isDefaultPrevented()) {
400 // We need to attach the element to the DOM so Sizzle selectors work on the contents
401 var tempBody = dom.add(editor.getBody(), 'div', {style: 'display:none'}, html);
402 args = editor.fire('PastePostProcess', {node: tempBody});
403 dom.remove(tempBody);
404 html = args.node.innerHTML;
407 if (!args.isDefaultPrevented()) {
408 SmartPaste.insertContent(editor, html);
414 * Pastes the specified text. This means that the plain text is processed
415 * and converted into BR and P elements. It will fire paste events for custom filtering.
417 * @param {String} text Text to paste as the current selection location.
419 function pasteText(text) {
420 text = editor.dom.encode(text).replace(/\r\n/g, '\n');
422 var startBlock = editor.dom.getParent(editor.selection.getStart(), editor.dom.isBlock);
424 // Create start block html for example <p attr="value">
425 var forcedRootBlockName = editor.settings.forced_root_block;
426 var forcedRootBlockStartHtml;
427 if (forcedRootBlockName) {
428 forcedRootBlockStartHtml = editor.dom.createHTML(forcedRootBlockName, editor.settings.forced_root_block_attrs);
429 forcedRootBlockStartHtml = forcedRootBlockStartHtml.substr(0, forcedRootBlockStartHtml.length - 3) + '>';
432 if ((startBlock && /^(PRE|DIV)$/.test(startBlock.nodeName)) || !forcedRootBlockName) {
433 text = Utils.filter(text, [
437 text = Utils.filter(text, [
438 [/\n\n/g, "</p>" + forcedRootBlockStartHtml],
439 [/^(.*<\/p>)(<p>)$/, forcedRootBlockStartHtml + '$1'],
443 if (text.indexOf('<p>') != -1) {
444 text = forcedRootBlockStartHtml + text;
452 * Creates a paste bin element as close as possible to the current caret location and places the focus inside that element
453 * so that when the real paste event occurs the contents gets inserted into this element
454 * instead of the current editor selection element.
456 function createPasteBin() {
457 var dom = editor.dom, body = editor.getBody();
458 var viewport = editor.dom.getViewPort(editor.getWin()), scrollTop = viewport.y, top = 20;
461 lastRng = editor.selection.getRng();
464 scrollContainer = editor.selection.getScrollContainer();
466 // Can't always rely on scrollTop returning a useful value.
467 // It returns 0 if the browser doesn't support scrollTop for the element or is non-scrollable
468 if (scrollContainer && scrollContainer.scrollTop > 0) {
469 scrollTop = scrollContainer.scrollTop;
474 * Returns the rect of the current caret if the caret is in an empty block before a
475 * BR we insert a temporary invisible character that we get the rect this way we always get a proper rect.
477 * TODO: This might be useful in core.
479 function getCaretRect(rng) {
480 var rects, textNode, node, container = rng.startContainer;
482 rects = rng.getClientRects();
487 if (!rng.collapsed || container.nodeType != 1) {
491 node = container.childNodes[lastRng.startOffset];
493 // Skip empty whitespace nodes
494 while (node && node.nodeType == 3 && !node.data.length) {
495 node = node.nextSibling;
502 // Check if the location is |<br>
503 // TODO: Might need to expand this to say |<table>
504 if (node.tagName == 'BR') {
505 textNode = dom.doc.createTextNode('\uFEFF');
506 node.parentNode.insertBefore(textNode, node);
508 rng = dom.createRng();
509 rng.setStartBefore(textNode);
510 rng.setEndAfter(textNode);
512 rects = rng.getClientRects();
513 dom.remove(textNode);
521 // Calculate top cordinate this is needed to avoid scrolling to top of document
522 // We want the paste bin to be as close to the caret as possible to avoid scrolling
523 if (lastRng.getClientRects) {
524 var rect = getCaretRect(lastRng);
527 // Client rects gets us closes to the actual
528 // caret location in for example a wrapped paragraph block
529 top = scrollTop + (rect.top - dom.getPos(body).y);
533 // Check if we can find a closer location by checking the range element
534 var container = lastRng.startContainer;
536 if (container.nodeType == 3 && container.parentNode != body) {
537 container = container.parentNode;
540 if (container.nodeType == 1) {
541 top = dom.getPos(container, scrollContainer || body).y;
548 pasteBinElm = dom.add(editor.getBody(), 'div', {
550 contentEditable: true,
551 "data-mce-bogus": "all",
552 style: 'position: absolute; top: ' + top + 'px;' +
553 'width: 10px; height: 10px; overflow: hidden; opacity: 0'
554 }, pasteBinDefaultContent);
556 // Move paste bin out of sight since the controlSelection rect gets displayed otherwise on IE and Gecko
557 if (Env.ie || Env.gecko) {
558 dom.setStyle(pasteBinElm, 'left', dom.getStyle(body, 'direction', true) == 'rtl' ? 0xFFFF : -0xFFFF);
561 // Prevent focus events from bubbeling fixed FocusManager issues
562 dom.bind(pasteBinElm, 'beforedeactivate focusin focusout', function(e) {
567 editor.selection.select(pasteBinElm, true);
571 * Removes the paste bin if it exists.
573 function removePasteBin() {
577 // WebKit/Blink might clone the div so
578 // lets make sure we remove all clones
579 // TODO: Man o man is this ugly. WebKit is the new IE! Remove this if they ever fix it!
580 while ((pasteBinClone = editor.dom.get('mcepastebin'))) {
581 editor.dom.remove(pasteBinClone);
582 editor.dom.unbind(pasteBinClone);
586 editor.selection.setRng(lastRng);
590 pasteBinElm = lastRng = null;
594 * Returns the contents of the paste bin as a HTML string.
596 * @return {String} Get the contents of the paste bin.
598 function getPasteBinHtml() {
599 var html = '', pasteBinClones, i, clone, cloneHtml;
601 // Since WebKit/Chrome might clone the paste bin when pasting
602 // for example: <img style="float: right"> we need to check if any of them contains some useful html.
603 // TODO: Man o man is this ugly. WebKit is the new IE! Remove this if they ever fix it!
604 pasteBinClones = editor.dom.select('div[id=mcepastebin]');
605 for (i = 0; i < pasteBinClones.length; i++) {
606 clone = pasteBinClones[i];
608 // Pasting plain text produces pastebins in pastebinds makes sence right!?
609 if (clone.firstChild && clone.firstChild.id == 'mcepastebin') {
610 clone = clone.firstChild;
613 cloneHtml = clone.innerHTML;
614 if (html != pasteBinDefaultContent) {
623 * Gets various content types out of a datatransfer object.
625 * @param {DataTransfer} dataTransfer Event fired on paste.
626 * @return {Object} Object with mime types and data for those mime types.
628 function getDataTransferItems(dataTransfer) {
632 // Use old WebKit/IE API
633 if (dataTransfer.getData) {
634 var legacyText = dataTransfer.getData('Text');
635 if (legacyText && legacyText.length > 0) {
636 if (legacyText.indexOf(mceInternalUrlPrefix) == -1) {
637 items['text/plain'] = legacyText;
642 if (dataTransfer.types) {
643 for (var i = 0; i < dataTransfer.types.length; i++) {
644 var contentType = dataTransfer.types[i];
645 items[contentType] = dataTransfer.getData(contentType);
654 * Gets various content types out of the Clipboard API. It will also get the
655 * plain text using older IE and WebKit API:s.
657 * @param {ClipboardEvent} clipboardEvent Event fired on paste.
658 * @return {Object} Object with mime types and data for those mime types.
660 function getClipboardContent(clipboardEvent) {
661 return getDataTransferItems(clipboardEvent.clipboardData || editor.getDoc().dataTransfer);
664 function hasHtmlOrText(content) {
665 return hasContentType(content, 'text/html') || hasContentType(content, 'text/plain');
668 function getBase64FromUri(uri) {
671 idx = uri.indexOf(',');
673 return uri.substr(idx + 1);
679 function isValidDataUriImage(settings, imgElm) {
680 return settings.images_dataimg_filter ? settings.images_dataimg_filter(imgElm) : true;
683 function pasteImage(rng, reader, blob) {
685 editor.selection.setRng(rng);
689 var dataUri = reader.result;
690 var base64 = getBase64FromUri(dataUri);
692 var img = new Image();
695 // TODO: Move the bulk of the cache logic to EditorUpload
696 if (isValidDataUriImage(editor.settings, img)) {
697 var blobCache = editor.editorUpload.blobCache;
698 var blobInfo, existingBlobInfo;
700 existingBlobInfo = blobCache.findFirst(function(cachedBlobInfo) {
701 return cachedBlobInfo.base64() === base64;
704 if (!existingBlobInfo) {
705 blobInfo = blobCache.create(uniqueId(), blob, base64);
706 blobCache.add(blobInfo);
708 blobInfo = existingBlobInfo;
711 pasteHtml('<img src="' + blobInfo.blobUri() + '">');
713 pasteHtml('<img src="' + dataUri + '">');
718 * Checks if the clipboard contains image data if it does it will take that data
719 * and convert it into a data url image and paste that image at the caret location.
721 * @param {ClipboardEvent} e Paste/drop event object.
722 * @param {DOMRange} rng Rng object to move selection to.
723 * @return {Boolean} true/false if the image data was found or not.
725 function pasteImageData(e, rng) {
726 var dataTransfer = e.clipboardData || e.dataTransfer;
728 function processItems(items) {
729 var i, item, reader, hadImage = false;
732 for (i = 0; i < items.length; i++) {
735 if (/^image\/(jpeg|png|gif|bmp)$/.test(item.type)) {
736 var blob = item.getAsFile ? item.getAsFile() : item;
738 reader = new FileReader();
739 reader.onload = pasteImage.bind(null, rng, reader, blob);
740 reader.readAsDataURL(blob);
751 if (editor.settings.paste_data_images && dataTransfer) {
752 return processItems(dataTransfer.items) || processItems(dataTransfer.files);
757 * Chrome on Android doesn't support proper clipboard access so we have no choice but to allow the browser default behavior.
759 * @param {Event} e Paste event object to check if it contains any data.
760 * @return {Boolean} true/false if the clipboard is empty or not.
762 function isBrokenAndroidClipboardEvent(e) {
763 var clipboardData = e.clipboardData;
765 return navigator.userAgent.indexOf('Android') != -1 && clipboardData && clipboardData.items && clipboardData.items.length === 0;
768 function getCaretRangeFromEvent(e) {
769 return RangeUtils.getCaretRangeFromPoint(e.clientX, e.clientY, editor.getDoc());
772 function hasContentType(clipboardContent, mimeType) {
773 return mimeType in clipboardContent && clipboardContent[mimeType].length > 0;
776 function isKeyboardPasteEvent(e) {
777 return (VK.metaKeyPressed(e) && e.keyCode == 86) || (e.shiftKey && e.keyCode == 45);
780 function registerEventHandlers() {
781 editor.on('keydown', function(e) {
782 function removePasteBinOnKeyUp(e) {
783 // Ctrl+V or Shift+Insert
784 if (isKeyboardPasteEvent(e) && !e.isDefaultPrevented()) {
789 // Ctrl+V or Shift+Insert
790 if (isKeyboardPasteEvent(e) && !e.isDefaultPrevented()) {
791 keyboardPastePlainTextState = e.shiftKey && e.keyCode == 86;
793 // Edge case on Safari on Mac where it doesn't handle Cmd+Shift+V correctly
794 // it fires the keydown but no paste or keyup so we are left with a paste bin
795 if (keyboardPastePlainTextState && Env.webkit && navigator.userAgent.indexOf('Version/') != -1) {
799 // Prevent undoManager keydown handler from making an undo level with the pastebin in it
800 e.stopImmediatePropagation();
802 keyboardPasteTimeStamp = new Date().getTime();
804 // IE doesn't support Ctrl+Shift+V and it doesn't even produce a paste event
805 // so lets fake a paste event and let IE use the execCommand/dataTransfer methods
806 if (Env.ie && keyboardPastePlainTextState) {
808 editor.fire('paste', {ieFake: true});
815 // Remove pastebin if we get a keyup and no paste event
816 // For example pasting a file in IE 11 will not produce a paste event
817 editor.once('keyup', removePasteBinOnKeyUp);
818 editor.once('paste', function() {
819 editor.off('keyup', removePasteBinOnKeyUp);
824 function insertClipboardContent(clipboardContent, isKeyBoardPaste, plainTextMode) {
827 // Grab HTML from Clipboard API or paste bin as a fallback
828 if (hasContentType(clipboardContent, 'text/html')) {
829 content = clipboardContent['text/html'];
831 content = getPasteBinHtml();
833 // If paste bin is empty try using plain text mode
834 // since that is better than nothing right
835 if (content == pasteBinDefaultContent) {
836 plainTextMode = true;
840 content = Utils.trimHtml(content);
842 // WebKit has a nice bug where it clones the paste bin if you paste from for example notepad
843 // so we need to force plain text mode in this case
844 if (pasteBinElm && pasteBinElm.firstChild && pasteBinElm.firstChild.id === 'mcepastebin') {
845 plainTextMode = true;
850 // If we got nothing from clipboard API and pastebin then we could try the last resort: plain/text
851 if (!content.length) {
852 plainTextMode = true;
855 // Grab plain text from Clipboard API or convert existing HTML to plain text
857 // Use plain text contents from Clipboard API unless the HTML contains paragraphs then
858 // we should convert the HTML to plain text since works better when pasting HTML/Word contents as plain text
859 if (hasContentType(clipboardContent, 'text/plain') && content.indexOf('</p>') == -1) {
860 content = clipboardContent['text/plain'];
862 content = Utils.innerText(content);
866 // If the content is the paste bin default HTML then it was
867 // impossible to get the cliboard data out.
868 if (content == pasteBinDefaultContent) {
869 if (!isKeyBoardPaste) {
870 editor.windowManager.alert('Please use Ctrl+V/Cmd+V keyboard shortcuts to paste contents.');
883 var getLastRng = function() {
884 return lastRng || editor.selection.getRng();
887 editor.on('paste', function(e) {
888 // Getting content from the Clipboard can take some time
889 var clipboardTimer = new Date().getTime();
890 var clipboardContent = getClipboardContent(e);
891 var clipboardDelay = new Date().getTime() - clipboardTimer;
893 var isKeyBoardPaste = (new Date().getTime() - keyboardPasteTimeStamp - clipboardDelay) < 1000;
894 var plainTextMode = self.pasteFormat == "text" || keyboardPastePlainTextState;
896 keyboardPastePlainTextState = false;
898 if (e.isDefaultPrevented() || isBrokenAndroidClipboardEvent(e)) {
903 if (!hasHtmlOrText(clipboardContent) && pasteImageData(e, getLastRng())) {
908 // Not a keyboard paste prevent default paste and try to grab the clipboard contents using different APIs
909 if (!isKeyBoardPaste) {
913 // Try IE only method if paste isn't a keyboard paste
914 if (Env.ie && (!isKeyBoardPaste || e.ieFake)) {
917 editor.dom.bind(pasteBinElm, 'paste', function(e) {
921 editor.getDoc().execCommand('Paste', false, null);
922 clipboardContent["text/html"] = getPasteBinHtml();
925 // If clipboard API has HTML then use that directly
926 if (hasContentType(clipboardContent, 'text/html')) {
928 insertClipboardContent(clipboardContent, isKeyBoardPaste, plainTextMode);
930 Delay.setEditorTimeout(editor, function() {
931 insertClipboardContent(clipboardContent, isKeyBoardPaste, plainTextMode);
936 editor.on('dragstart dragend', function(e) {
937 draggingInternally = e.type == 'dragstart';
940 function isPlainTextFileUrl(content) {
941 return content['text/plain'].indexOf('file://') === 0;
944 editor.on('drop', function(e) {
945 var dropContent, rng;
947 rng = getCaretRangeFromEvent(e);
949 if (e.isDefaultPrevented() || draggingInternally) {
953 dropContent = getDataTransferItems(e.dataTransfer);
955 if ((!hasHtmlOrText(dropContent) || isPlainTextFileUrl(dropContent)) && pasteImageData(e, rng)) {
959 if (rng && editor.settings.paste_filter_drop !== false) {
960 var content = dropContent['mce-internal'] || dropContent['text/html'] || dropContent['text/plain'];
965 // FF 45 doesn't paint a caret when dragging in text in due to focus call by execCommand
966 Delay.setEditorTimeout(editor, function() {
967 editor.undoManager.transact(function() {
968 if (dropContent['mce-internal']) {
969 editor.execCommand('Delete');
972 editor.selection.setRng(rng);
974 content = Utils.trimHtml(content);
976 if (!dropContent['text/html']) {
987 editor.on('dragover dragend', function(e) {
988 if (editor.settings.paste_data_images) {
994 self.pasteHtml = pasteHtml;
995 self.pasteText = pasteText;
996 self.pasteImageData = pasteImageData;
998 editor.on('preInit', function() {
999 registerEventHandlers();
1001 // Remove all data images from paste for example from Gecko
1002 // except internal images like video elements
1003 editor.parser.addNodeFilter('img', function(nodes, name, args) {
1004 function isPasteInsert(args) {
1005 return args.data && args.data.paste === true;
1008 function remove(node) {
1009 if (!node.attr('data-mce-object') && src !== Env.transparentSrc) {
1014 function isWebKitFakeUrl(src) {
1015 return src.indexOf("webkit-fake-url") === 0;
1018 function isDataUri(src) {
1019 return src.indexOf("data:") === 0;
1022 if (!editor.settings.paste_data_images && isPasteInsert(args)) {
1023 var i = nodes.length;
1026 var src = nodes[i].attributes.map.src;
1032 // Safari on Mac produces webkit-fake-url see: https://bugs.webkit.org/show_bug.cgi?id=49141
1033 if (isWebKitFakeUrl(src)) {
1035 } else if (!editor.settings.allow_html_data_urls && isDataUri(src)) {
1045 // Included from: js/tinymce/plugins/paste/classes/WordFilter.js
1050 * Released under LGPL License.
1051 * Copyright (c) 1999-2015 Ephox Corp. All rights reserved
1053 * License: http://www.tinymce.com/license
1054 * Contributing: http://www.tinymce.com/contributing
1058 * This class parses word HTML into proper TinyMCE markup.
1060 * @class tinymce.pasteplugin.WordFilter
1063 define("tinymce/pasteplugin/WordFilter", [
1064 "tinymce/util/Tools",
1065 "tinymce/html/DomParser",
1066 "tinymce/html/Schema",
1067 "tinymce/html/Serializer",
1068 "tinymce/html/Node",
1069 "tinymce/pasteplugin/Utils"
1070 ], function(Tools, DomParser, Schema, Serializer, Node, Utils) {
1072 * Checks if the specified content is from any of the following sources: MS Word/Office 365/Google docs.
1074 function isWordContent(content) {
1076 (/<font face="Times New Roman"|class="?Mso|style="[^"]*\bmso-|style='[^'']*\bmso-|w:WordDocument/i).test(content) ||
1077 (/class="OutlineElement/).test(content) ||
1078 (/id="?docs\-internal\-guid\-/.test(content))
1083 * Checks if the specified text starts with "1. " or "a. " etc.
1085 function isNumericList(text) {
1086 var found, patterns;
1089 /^[IVXLMCD]{1,2}\.[ \u00a0]/, // Roman upper case
1090 /^[ivxlmcd]{1,2}\.[ \u00a0]/, // Roman lower case
1091 /^[a-z]{1,2}[\.\)][ \u00a0]/, // Alphabetical a-z
1092 /^[A-Z]{1,2}[\.\)][ \u00a0]/, // Alphabetical A-Z
1093 /^[0-9]+\.[ \u00a0]/, // Numeric lists
1094 /^[\u3007\u4e00\u4e8c\u4e09\u56db\u4e94\u516d\u4e03\u516b\u4e5d]+\.[ \u00a0]/, // Japanese
1095 /^[\u58f1\u5f10\u53c2\u56db\u4f0d\u516d\u4e03\u516b\u4e5d\u62fe]+\.[ \u00a0]/ // Chinese
1098 text = text.replace(/^[\u00a0 ]+/, '');
1100 Tools.each(patterns, function(pattern) {
1101 if (pattern.test(text)) {
1110 function isBulletList(text) {
1111 return /^[\s\u00a0]*[\u2022\u00b7\u00a7\u25CF]\s*/.test(text);
1114 function WordFilter(editor) {
1115 var settings = editor.settings;
1117 editor.on('BeforePastePreProcess', function(e) {
1118 var content = e.content, retainStyleProperties, validStyles;
1120 // Remove google docs internal guid markers
1121 content = content.replace(/<b[^>]+id="?docs-internal-[^>]*>/gi, '');
1122 content = content.replace(/<br class="?Apple-interchange-newline"?>/gi, '');
1124 retainStyleProperties = settings.paste_retain_style_properties;
1125 if (retainStyleProperties) {
1126 validStyles = Tools.makeMap(retainStyleProperties.split(/[, ]/));
1130 * Converts fake bullet and numbered lists to real semantic OL/UL.
1132 * @param {tinymce.html.Node} node Root node to convert children of.
1134 function convertFakeListsToProperLists(node) {
1135 var currentListNode, prevListNode, lastLevel = 1;
1137 function getText(node) {
1140 if (node.type === 3) {
1144 if ((node = node.firstChild)) {
1146 txt += getText(node);
1147 } while ((node = node.next));
1153 function trimListStart(node, regExp) {
1154 if (node.type === 3) {
1155 if (regExp.test(node.value)) {
1156 node.value = node.value.replace(regExp, '');
1161 if ((node = node.firstChild)) {
1163 if (!trimListStart(node, regExp)) {
1166 } while ((node = node.next));
1172 function removeIgnoredNodes(node) {
1173 if (node._listIgnore) {
1178 if ((node = node.firstChild)) {
1180 removeIgnoredNodes(node);
1181 } while ((node = node.next));
1185 function convertParagraphToLi(paragraphNode, listName, start) {
1186 var level = paragraphNode._listLevel || lastLevel;
1188 // Handle list nesting
1189 if (level != lastLevel) {
1190 if (level < lastLevel) {
1191 // Move to parent list
1192 if (currentListNode) {
1193 currentListNode = currentListNode.parent.parent;
1197 prevListNode = currentListNode;
1198 currentListNode = null;
1202 if (!currentListNode || currentListNode.name != listName) {
1203 prevListNode = prevListNode || currentListNode;
1204 currentListNode = new Node(listName, 1);
1207 currentListNode.attr('start', '' + start);
1210 paragraphNode.wrap(currentListNode);
1212 currentListNode.append(paragraphNode);
1215 paragraphNode.name = 'li';
1217 // Append list to previous list if it exists
1218 if (level > lastLevel && prevListNode) {
1219 prevListNode.lastChild.append(currentListNode);
1224 // Remove start of list item "1. " or "· " etc
1225 removeIgnoredNodes(paragraphNode);
1226 trimListStart(paragraphNode, /^\u00a0+/);
1227 trimListStart(paragraphNode, /^\s*([\u2022\u00b7\u00a7\u25CF]|\w+\.)/);
1228 trimListStart(paragraphNode, /^\u00a0+/);
1231 // Build a list of all root level elements before we start
1232 // altering them in the loop below.
1233 var elements = [], child = node.firstChild;
1234 while (typeof child !== 'undefined' && child !== null) {
1235 elements.push(child);
1237 child = child.walk();
1238 if (child !== null) {
1239 while (typeof child !== 'undefined' && child.parent !== node) {
1240 child = child.walk();
1245 for (var i = 0; i < elements.length; i++) {
1248 if (node.name == 'p' && node.firstChild) {
1249 // Find first text node in paragraph
1250 var nodeText = getText(node);
1252 // Detect unordered lists look for bullets
1253 if (isBulletList(nodeText)) {
1254 convertParagraphToLi(node, 'ul');
1258 // Detect ordered lists 1., a. or ixv.
1259 if (isNumericList(nodeText)) {
1260 // Parse OL start number
1261 var matches = /([0-9]+)\./.exec(nodeText);
1264 start = parseInt(matches[1], 10);
1267 convertParagraphToLi(node, 'ol', start);
1271 // Convert paragraphs marked as lists but doesn't look like anything
1272 if (node._listLevel) {
1273 convertParagraphToLi(node, 'ul', 1);
1277 currentListNode = null;
1279 // If the root level element isn't a p tag which can be
1280 // processed by convertParagraphToLi, it interrupts the
1281 // lists, causing a new list to start instead of having
1282 // elements from the next list inserted above this tag.
1283 prevListNode = currentListNode;
1284 currentListNode = null;
1289 function filterStyles(node, styleValue) {
1290 var outputStyles = {}, matches, styles = editor.dom.parseStyle(styleValue);
1292 Tools.each(styles, function(value, name) {
1293 // Convert various MS styles to W3C styles
1296 // Parse out list indent level for lists
1297 matches = /\w+ \w+([0-9]+)/i.exec(styleValue);
1299 node._listLevel = parseInt(matches[1], 10);
1302 // Remove these nodes <span style="mso-list:Ignore">o</span>
1303 // Since the span gets removed we mark the text node and the span
1304 if (/Ignore/i.test(value) && node.firstChild) {
1305 node._listIgnore = true;
1306 node.firstChild._listIgnore = true;
1312 name = "text-align";
1316 name = "vertical-align";
1320 case "mso-foreground":
1324 case "mso-background":
1325 case "mso-highlight":
1326 name = "background";
1331 if (value != "normal") {
1332 outputStyles[name] = value;
1337 // Remove track changes code
1338 if (/^(comment|comment-list)$/i.test(value)) {
1346 if (name.indexOf('mso-comment') === 0) {
1351 // Never allow mso- prefixed names
1352 if (name.indexOf('mso-') === 0) {
1356 // Output only valid styles
1357 if (retainStyleProperties == "all" || (validStyles && validStyles[name])) {
1358 outputStyles[name] = value;
1362 // Convert bold style to "b" element
1363 if (/(bold)/i.test(outputStyles["font-weight"])) {
1364 delete outputStyles["font-weight"];
1365 node.wrap(new Node("b", 1));
1368 // Convert italic style to "i" element
1369 if (/(italic)/i.test(outputStyles["font-style"])) {
1370 delete outputStyles["font-style"];
1371 node.wrap(new Node("i", 1));
1374 // Serialize the styles and see if there is something left to keep
1375 outputStyles = editor.dom.serializeStyle(outputStyles, node.name);
1377 return outputStyles;
1383 if (settings.paste_enable_default_filters === false) {
1387 // Detect is the contents is Word junk HTML
1388 if (isWordContent(e.content)) {
1389 e.wordContent = true; // Mark it for other processors
1391 // Remove basic Word junk
1392 content = Utils.filter(content, [
1393 // Word comments like conditional comments etc
1394 /<!--[\s\S]+?-->/gi,
1396 // Remove comments, scripts (e.g., msoShowComment), XML tag, VML content,
1397 // MS Office namespaced tags, and a few other tags
1398 /<(!|script[^>]*>.*?<\/script(?=[>\s])|\/?(\?xml(:\w+)?|img|meta|link|style|\w:\w+)(?=[\s\/>]))[^>]*>/gi,
1400 // Convert <s> into <strike> for line-though
1401 [/<(\/?)s>/gi, "<$1strike>"],
1403 // Replace nsbp entites to char since it's easier to handle
1404 [/ /gi, "\u00a0"],
1406 // Convert <span style="mso-spacerun:yes">___</span> to string of alternating
1407 // breaking/non-breaking spaces of same length
1408 [/<span\s+style\s*=\s*"\s*mso-spacerun\s*:\s*yes\s*;?\s*"\s*>([\s\u00a0]*)<\/span>/gi,
1409 function(str, spaces) {
1410 return (spaces.length > 0) ?
1411 spaces.replace(/./, " ").slice(Math.floor(spaces.length / 2)).split("").join("\u00a0") : "";
1416 var validElements = settings.paste_word_valid_elements;
1417 if (!validElements) {
1419 '-strong/b,-em/i,-u,-span,-p,-ol,-ul,-li,-h1,-h2,-h3,-h4,-h5,-h6,' +
1420 '-p/div,-a[href|name],sub,sup,strike,br,del,table[width],tr,' +
1421 'td[colspan|rowspan|width],th[colspan|rowspan|width],thead,tfoot,tbody'
1425 // Setup strict schema
1426 var schema = new Schema({
1427 valid_elements: validElements,
1428 valid_children: '-li[p]'
1431 // Add style/class attribute to all element rules since the user might have removed them from
1432 // paste_word_valid_elements config option and we need to check them for properties
1433 Tools.each(schema.elements, function(rule) {
1434 /*eslint dot-notation:0*/
1435 if (!rule.attributes["class"]) {
1436 rule.attributes["class"] = {};
1437 rule.attributesOrder.push("class");
1440 if (!rule.attributes.style) {
1441 rule.attributes.style = {};
1442 rule.attributesOrder.push("style");
1446 // Parse HTML into DOM structure
1447 var domParser = new DomParser({}, schema);
1449 // Filter styles to remove "mso" specific styles and convert some of them
1450 domParser.addAttributeFilter('style', function(nodes) {
1451 var i = nodes.length, node;
1455 node.attr('style', filterStyles(node, node.attr('style')));
1457 // Remove pointess spans
1458 if (node.name == 'span' && node.parent && !node.attributes.length) {
1464 // Check the class attribute for comments or del items and remove those
1465 domParser.addAttributeFilter('class', function(nodes) {
1466 var i = nodes.length, node, className;
1471 className = node.attr('class');
1472 if (/^(MsoCommentReference|MsoCommentText|msoDel)$/i.test(className)) {
1476 node.attr('class', null);
1480 // Remove all del elements since we don't want the track changes code in the editor
1481 domParser.addNodeFilter('del', function(nodes) {
1482 var i = nodes.length;
1489 // Keep some of the links and anchors
1490 domParser.addNodeFilter('a', function(nodes) {
1491 var i = nodes.length, node, href, name;
1495 href = node.attr('href');
1496 name = node.attr('name');
1498 if (href && href.indexOf('#_msocom_') != -1) {
1503 if (href && href.indexOf('file://') === 0) {
1504 href = href.split('#')[1];
1510 if (!href && !name) {
1513 // Remove all named anchors that aren't specific to TOC, Footnotes or Endnotes
1514 if (name && !/^_?(?:toc|edn|ftn)/i.test(name)) {
1527 // Parse into DOM structure
1528 var rootNode = domParser.parse(content);
1531 if (settings.paste_convert_word_fake_lists !== false) {
1532 convertFakeListsToProperLists(rootNode);
1535 // Serialize DOM back to HTML
1536 e.content = new Serializer({
1537 validate: settings.validate
1538 }, schema).serialize(rootNode);
1543 WordFilter.isWordContent = isWordContent;
1548 // Included from: js/tinymce/plugins/paste/classes/Quirks.js
1553 * Released under LGPL License.
1554 * Copyright (c) 1999-2015 Ephox Corp. All rights reserved
1556 * License: http://www.tinymce.com/license
1557 * Contributing: http://www.tinymce.com/contributing
1561 * This class contains various fixes for browsers. These issues can not be feature
1562 * detected since we have no direct control over the clipboard. However we might be able
1563 * to remove some of these fixes once the browsers gets updated/fixed.
1565 * @class tinymce.pasteplugin.Quirks
1568 define("tinymce/pasteplugin/Quirks", [
1570 "tinymce/util/Tools",
1571 "tinymce/pasteplugin/WordFilter",
1572 "tinymce/pasteplugin/Utils"
1573 ], function(Env, Tools, WordFilter, Utils) {
1576 return function(editor) {
1577 function addPreProcessFilter(filterFunc) {
1578 editor.on('BeforePastePreProcess', function(e) {
1579 e.content = filterFunc(e.content);
1584 * Removes BR elements after block elements. IE9 has a nasty bug where it puts a BR element after each
1585 * block element when pasting from word. This removes those elements.
1588 * <p>a</p><br><p>b</p>
1593 function removeExplorerBrElementsAfterBlocks(html) {
1594 // Only filter word specific content
1595 if (!WordFilter.isWordContent(html)) {
1599 // Produce block regexp based on the block elements in schema
1600 var blockElements = [];
1602 Tools.each(editor.schema.getBlockElements(), function(block, blockName) {
1603 blockElements.push(blockName);
1606 var explorerBlocksRegExp = new RegExp(
1607 '(?:<br> [\\s\\r\\n]+|<br>)*(<\\/?(' + blockElements.join('|') + ')[^>]*>)(?:<br> [\\s\\r\\n]+|<br>)*',
1611 // Remove BR:s from: <BLOCK>X</BLOCK><BR>
1612 html = Utils.filter(html, [
1613 [explorerBlocksRegExp, '$1']
1616 // IE9 also adds an extra BR element for each soft-linefeed and it also adds a BR for each word wrap break
1617 html = Utils.filter(html, [
1618 [/<br><br>/g, '<BR><BR>'], // Replace multiple BR elements with uppercase BR to keep them intact
1619 [/<br>/g, ' '], // Replace single br elements with space since they are word wrap BR:s
1620 [/<BR><BR>/g, '<br>'] // Replace back the double brs but into a single BR
1627 * WebKit has a nasty bug where the all computed styles gets added to style attributes when copy/pasting contents.
1628 * This fix solves that by simply removing the whole style attribute.
1630 * The paste_webkit_styles option can be set to specify what to keep:
1631 * paste_webkit_styles: "none" // Keep no styles
1632 * paste_webkit_styles: "all", // Keep all of them
1633 * paste_webkit_styles: "font-weight color" // Keep specific ones
1635 * @param {String} content Content that needs to be processed.
1636 * @return {String} Processed contents.
1638 function removeWebKitStyles(content) {
1639 // Passthrough all styles from Word and let the WordFilter handle that junk
1640 if (WordFilter.isWordContent(content)) {
1644 // Filter away styles that isn't matching the target node
1645 var webKitStyles = editor.settings.paste_webkit_styles;
1647 if (editor.settings.paste_remove_styles_if_webkit === false || webKitStyles == "all") {
1652 webKitStyles = webKitStyles.split(/[, ]/);
1655 // Keep specific styles that doesn't match the current node computed style
1657 var dom = editor.dom, node = editor.selection.getNode();
1659 content = content.replace(/(<[^>]+) style="([^"]*)"([^>]*>)/gi, function(all, before, value, after) {
1660 var inputStyles = dom.parseStyle(value, 'span'), outputStyles = {};
1662 if (webKitStyles === "none") {
1663 return before + after;
1666 for (var i = 0; i < webKitStyles.length; i++) {
1667 var inputValue = inputStyles[webKitStyles[i]], currentValue = dom.getStyle(node, webKitStyles[i], true);
1669 if (/color/.test(webKitStyles[i])) {
1670 inputValue = dom.toHex(inputValue);
1671 currentValue = dom.toHex(currentValue);
1674 if (currentValue != inputValue) {
1675 outputStyles[webKitStyles[i]] = inputValue;
1679 outputStyles = dom.serializeStyle(outputStyles, 'span');
1681 return before + ' style="' + outputStyles + '"' + after;
1684 return before + after;
1687 // Remove all external styles
1688 content = content.replace(/(<[^>]+) style="([^"]*)"([^>]*>)/gi, '$1$3');
1691 // Keep internal styles
1692 content = content.replace(/(<[^>]+) data-mce-style="([^"]+)"([^>]*>)/gi, function(all, before, value, after) {
1693 return before + ' style="' + value + '"' + after;
1699 // Sniff browsers and apply fixes since we can't feature detect
1701 addPreProcessFilter(removeWebKitStyles);
1705 addPreProcessFilter(removeExplorerBrElementsAfterBlocks);
1710 // Included from: js/tinymce/plugins/paste/classes/Plugin.js
1715 * Released under LGPL License.
1716 * Copyright (c) 1999-2015 Ephox Corp. All rights reserved
1718 * License: http://www.tinymce.com/license
1719 * Contributing: http://www.tinymce.com/contributing
1723 * This class contains the tinymce plugin logic for the paste plugin.
1725 * @class tinymce.pasteplugin.Plugin
1728 define("tinymce/pasteplugin/Plugin", [
1729 "tinymce/PluginManager",
1730 "tinymce/pasteplugin/Clipboard",
1731 "tinymce/pasteplugin/WordFilter",
1732 "tinymce/pasteplugin/Quirks"
1733 ], function(PluginManager, Clipboard, WordFilter, Quirks) {
1736 PluginManager.add('paste', function(editor) {
1737 var self = this, clipboard, settings = editor.settings;
1739 function isUserInformedAboutPlainText() {
1740 return userIsInformed || editor.settings.paste_plaintext_inform === false;
1743 function togglePlainTextPaste() {
1744 if (clipboard.pasteFormat == "text") {
1746 clipboard.pasteFormat = "html";
1747 editor.fire('PastePlainTextToggle', {state: false});
1749 clipboard.pasteFormat = "text";
1752 if (!isUserInformedAboutPlainText()) {
1753 var message = editor.translate('Paste is now in plain text mode. Contents will now ' +
1754 'be pasted as plain text until you toggle this option off.');
1756 editor.notificationManager.open({
1761 userIsInformed = true;
1762 editor.fire('PastePlainTextToggle', {state: true});
1769 // draw back if power version is requested and registered
1770 if (/(^|[ ,])powerpaste([, ]|$)/.test(settings.plugins) && PluginManager.get('powerpaste')) {
1771 /*eslint no-console:0 */
1772 if (typeof console !== "undefined" && console.log) {
1773 console.log("PowerPaste is incompatible with Paste plugin! Remove 'paste' from the 'plugins' option.");
1778 self.clipboard = clipboard = new Clipboard(editor);
1779 self.quirks = new Quirks(editor);
1780 self.wordFilter = new WordFilter(editor);
1782 if (editor.settings.paste_as_text) {
1783 self.clipboard.pasteFormat = "text";
1786 if (settings.paste_preprocess) {
1787 editor.on('PastePreProcess', function(e) {
1788 settings.paste_preprocess.call(self, self, e);
1792 if (settings.paste_postprocess) {
1793 editor.on('PastePostProcess', function(e) {
1794 settings.paste_postprocess.call(self, self, e);
1798 editor.addCommand('mceInsertClipboardContent', function(ui, value) {
1799 if (value.content) {
1800 self.clipboard.pasteHtml(value.content);
1804 self.clipboard.pasteText(value.text);
1808 // Block all drag/drop events
1809 if (editor.settings.paste_block_drop) {
1810 editor.on('dragend dragover draggesture dragdrop drop drag', function(e) {
1812 e.stopPropagation();
1816 // Prevent users from dropping data images on Gecko
1817 if (!editor.settings.paste_data_images) {
1818 editor.on('drop', function(e) {
1819 var dataTransfer = e.dataTransfer;
1821 if (dataTransfer && dataTransfer.files && dataTransfer.files.length > 0) {
1827 editor.addButton('pastetext', {
1829 tooltip: 'Paste as text',
1830 onclick: togglePlainTextPaste,
1831 active: self.clipboard.pasteFormat == "text"
1834 editor.addMenuItem('pastetext', {
1835 text: 'Paste as text',
1837 active: clipboard.pasteFormat,
1838 onclick: togglePlainTextPaste
1843 expose(["tinymce/pasteplugin/Utils"]);