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/Clipboard.js
248 * Released under LGPL License.
249 * Copyright (c) 1999-2015 Ephox Corp. All rights reserved
251 * License: http://www.tinymce.com/license
252 * Contributing: http://www.tinymce.com/contributing
256 * This class contains logic for getting HTML contents out of the clipboard.
258 * We need to make a lot of ugly hacks to get the contents out of the clipboard since
259 * the W3C Clipboard API is broken in all browsers that have it: Gecko/WebKit/Blink.
260 * We might rewrite this the way those API:s stabilize. Browsers doesn't handle pasting
261 * from applications like Word the same way as it does when pasting into a contentEditable area
262 * so we need to do lots of extra work to try to get to this clipboard data.
264 * Current implementation steps:
265 * 1. On keydown with paste keys Ctrl+V or Shift+Insert create
266 * a paste bin element and move focus to that element.
267 * 2. Wait for the browser to fire a "paste" event and get the contents out of the paste bin.
268 * 3. Check if the paste was successful if true, process the HTML.
269 * (4). If the paste was unsuccessful use IE execCommand, Clipboard API, document.dataTransfer old WebKit API etc.
271 * @class tinymce.pasteplugin.Clipboard
274 define("tinymce/pasteplugin/Clipboard", [
276 "tinymce/dom/RangeUtils",
278 "tinymce/pasteplugin/Utils",
280 ], function(Env, RangeUtils, VK, Utils, Delay) {
281 return function(editor) {
282 var self = this, pasteBinElm, lastRng, keyboardPasteTimeStamp = 0, draggingInternally = false;
283 var pasteBinDefaultContent = '%MCEPASTEBIN%', keyboardPastePlainTextState;
284 var mceInternalUrlPrefix = 'data:text/mce-internal,';
285 var uniqueId = Utils.createIdGenerator("mceclip");
288 * Pastes the specified HTML. This means that the HTML is filtered and then
289 * inserted at the current selection in the editor. It will also fire paste events
290 * for custom user filtering.
292 * @param {String} html HTML code to paste into the current selection.
294 function pasteHtml(html) {
295 var args, dom = editor.dom;
297 args = editor.fire('BeforePastePreProcess', {content: html}); // Internal event used by Quirks
298 args = editor.fire('PastePreProcess', args);
301 if (!args.isDefaultPrevented()) {
302 // User has bound PastePostProcess events then we need to pass it through a DOM node
303 // This is not ideal but we don't want to let the browser mess up the HTML for example
304 // some browsers add to P tags etc
305 if (editor.hasEventListeners('PastePostProcess') && !args.isDefaultPrevented()) {
306 // We need to attach the element to the DOM so Sizzle selectors work on the contents
307 var tempBody = dom.add(editor.getBody(), 'div', {style: 'display:none'}, html);
308 args = editor.fire('PastePostProcess', {node: tempBody});
309 dom.remove(tempBody);
310 html = args.node.innerHTML;
313 if (!args.isDefaultPrevented()) {
314 editor.insertContent(html, {merge: editor.settings.paste_merge_formats !== false, data: {paste: true}});
320 * Pastes the specified text. This means that the plain text is processed
321 * and converted into BR and P elements. It will fire paste events for custom filtering.
323 * @param {String} text Text to paste as the current selection location.
325 function pasteText(text) {
326 text = editor.dom.encode(text).replace(/\r\n/g, '\n');
328 var startBlock = editor.dom.getParent(editor.selection.getStart(), editor.dom.isBlock);
330 // Create start block html for example <p attr="value">
331 var forcedRootBlockName = editor.settings.forced_root_block;
332 var forcedRootBlockStartHtml;
333 if (forcedRootBlockName) {
334 forcedRootBlockStartHtml = editor.dom.createHTML(forcedRootBlockName, editor.settings.forced_root_block_attrs);
335 forcedRootBlockStartHtml = forcedRootBlockStartHtml.substr(0, forcedRootBlockStartHtml.length - 3) + '>';
338 if ((startBlock && /^(PRE|DIV)$/.test(startBlock.nodeName)) || !forcedRootBlockName) {
339 text = Utils.filter(text, [
343 text = Utils.filter(text, [
344 [/\n\n/g, "</p>" + forcedRootBlockStartHtml],
345 [/^(.*<\/p>)(<p>)$/, forcedRootBlockStartHtml + '$1'],
349 if (text.indexOf('<p>') != -1) {
350 text = forcedRootBlockStartHtml + text;
358 * Creates a paste bin element as close as possible to the current caret location and places the focus inside that element
359 * so that when the real paste event occurs the contents gets inserted into this element
360 * instead of the current editor selection element.
362 function createPasteBin() {
363 var dom = editor.dom, body = editor.getBody();
364 var viewport = editor.dom.getViewPort(editor.getWin()), scrollTop = viewport.y, top = 20;
367 lastRng = editor.selection.getRng();
370 scrollContainer = editor.selection.getScrollContainer();
372 // Can't always rely on scrollTop returning a useful value.
373 // It returns 0 if the browser doesn't support scrollTop for the element or is non-scrollable
374 if (scrollContainer && scrollContainer.scrollTop > 0) {
375 scrollTop = scrollContainer.scrollTop;
380 * Returns the rect of the current caret if the caret is in an empty block before a
381 * BR we insert a temporary invisible character that we get the rect this way we always get a proper rect.
383 * TODO: This might be useful in core.
385 function getCaretRect(rng) {
386 var rects, textNode, node, container = rng.startContainer;
388 rects = rng.getClientRects();
393 if (!rng.collapsed || container.nodeType != 1) {
397 node = container.childNodes[lastRng.startOffset];
399 // Skip empty whitespace nodes
400 while (node && node.nodeType == 3 && !node.data.length) {
401 node = node.nextSibling;
408 // Check if the location is |<br>
409 // TODO: Might need to expand this to say |<table>
410 if (node.tagName == 'BR') {
411 textNode = dom.doc.createTextNode('\uFEFF');
412 node.parentNode.insertBefore(textNode, node);
414 rng = dom.createRng();
415 rng.setStartBefore(textNode);
416 rng.setEndAfter(textNode);
418 rects = rng.getClientRects();
419 dom.remove(textNode);
427 // Calculate top cordinate this is needed to avoid scrolling to top of document
428 // We want the paste bin to be as close to the caret as possible to avoid scrolling
429 if (lastRng.getClientRects) {
430 var rect = getCaretRect(lastRng);
433 // Client rects gets us closes to the actual
434 // caret location in for example a wrapped paragraph block
435 top = scrollTop + (rect.top - dom.getPos(body).y);
439 // Check if we can find a closer location by checking the range element
440 var container = lastRng.startContainer;
442 if (container.nodeType == 3 && container.parentNode != body) {
443 container = container.parentNode;
446 if (container.nodeType == 1) {
447 top = dom.getPos(container, scrollContainer || body).y;
454 pasteBinElm = dom.add(editor.getBody(), 'div', {
456 contentEditable: true,
457 "data-mce-bogus": "all",
458 style: 'position: absolute; top: ' + top + 'px;' +
459 'width: 10px; height: 10px; overflow: hidden; opacity: 0'
460 }, pasteBinDefaultContent);
462 // Move paste bin out of sight since the controlSelection rect gets displayed otherwise on IE and Gecko
463 if (Env.ie || Env.gecko) {
464 dom.setStyle(pasteBinElm, 'left', dom.getStyle(body, 'direction', true) == 'rtl' ? 0xFFFF : -0xFFFF);
467 // Prevent focus events from bubbeling fixed FocusManager issues
468 dom.bind(pasteBinElm, 'beforedeactivate focusin focusout', function(e) {
473 editor.selection.select(pasteBinElm, true);
477 * Removes the paste bin if it exists.
479 function removePasteBin() {
483 // WebKit/Blink might clone the div so
484 // lets make sure we remove all clones
485 // TODO: Man o man is this ugly. WebKit is the new IE! Remove this if they ever fix it!
486 while ((pasteBinClone = editor.dom.get('mcepastebin'))) {
487 editor.dom.remove(pasteBinClone);
488 editor.dom.unbind(pasteBinClone);
492 editor.selection.setRng(lastRng);
496 pasteBinElm = lastRng = null;
500 * Returns the contents of the paste bin as a HTML string.
502 * @return {String} Get the contents of the paste bin.
504 function getPasteBinHtml() {
505 var html = '', pasteBinClones, i, clone, cloneHtml;
507 // Since WebKit/Chrome might clone the paste bin when pasting
508 // for example: <img style="float: right"> we need to check if any of them contains some useful html.
509 // TODO: Man o man is this ugly. WebKit is the new IE! Remove this if they ever fix it!
510 pasteBinClones = editor.dom.select('div[id=mcepastebin]');
511 for (i = 0; i < pasteBinClones.length; i++) {
512 clone = pasteBinClones[i];
514 // Pasting plain text produces pastebins in pastebinds makes sence right!?
515 if (clone.firstChild && clone.firstChild.id == 'mcepastebin') {
516 clone = clone.firstChild;
519 cloneHtml = clone.innerHTML;
520 if (html != pasteBinDefaultContent) {
529 * Gets various content types out of a datatransfer object.
531 * @param {DataTransfer} dataTransfer Event fired on paste.
532 * @return {Object} Object with mime types and data for those mime types.
534 function getDataTransferItems(dataTransfer) {
538 // Use old WebKit/IE API
539 if (dataTransfer.getData) {
540 var legacyText = dataTransfer.getData('Text');
541 if (legacyText && legacyText.length > 0) {
542 if (legacyText.indexOf(mceInternalUrlPrefix) == -1) {
543 items['text/plain'] = legacyText;
548 if (dataTransfer.types) {
549 for (var i = 0; i < dataTransfer.types.length; i++) {
550 var contentType = dataTransfer.types[i];
551 items[contentType] = dataTransfer.getData(contentType);
560 * Gets various content types out of the Clipboard API. It will also get the
561 * plain text using older IE and WebKit API:s.
563 * @param {ClipboardEvent} clipboardEvent Event fired on paste.
564 * @return {Object} Object with mime types and data for those mime types.
566 function getClipboardContent(clipboardEvent) {
567 return getDataTransferItems(clipboardEvent.clipboardData || editor.getDoc().dataTransfer);
570 function hasHtmlOrText(content) {
571 return hasContentType(content, 'text/html') || hasContentType(content, 'text/plain');
575 * Checks if the clipboard contains image data if it does it will take that data
576 * and convert it into a data url image and paste that image at the caret location.
578 * @param {ClipboardEvent} e Paste/drop event object.
579 * @param {DOMRange} rng Rng object to move selection to.
580 * @return {Boolean} true/false if the image data was found or not.
582 function pasteImageData(e, rng) {
583 var dataTransfer = e.clipboardData || e.dataTransfer;
585 function getBase64FromUri(uri) {
588 idx = uri.indexOf(',');
590 return uri.substr(idx + 1);
596 function processItems(items) {
597 var i, item, reader, hadImage = false;
599 function pasteImage(reader, blob) {
601 editor.selection.setRng(rng);
605 var blobCache = editor.editorUpload.blobCache;
606 var blobInfo = blobCache.create(uniqueId(), blob, getBase64FromUri(reader.result));
607 blobCache.add(blobInfo);
609 pasteHtml('<img src="' + blobInfo.blobUri() + '">');
613 for (i = 0; i < items.length; i++) {
616 if (/^image\/(jpeg|png|gif|bmp)$/.test(item.type)) {
617 var blob = item.getAsFile ? item.getAsFile() : item;
619 reader = new FileReader();
620 reader.onload = pasteImage.bind(null, reader, blob);
621 reader.readAsDataURL(blob);
632 if (editor.settings.paste_data_images && dataTransfer) {
633 return processItems(dataTransfer.items) || processItems(dataTransfer.files);
638 * Chrome on Android doesn't support proper clipboard access so we have no choice but to allow the browser default behavior.
640 * @param {Event} e Paste event object to check if it contains any data.
641 * @return {Boolean} true/false if the clipboard is empty or not.
643 function isBrokenAndroidClipboardEvent(e) {
644 var clipboardData = e.clipboardData;
646 return navigator.userAgent.indexOf('Android') != -1 && clipboardData && clipboardData.items && clipboardData.items.length === 0;
649 function getCaretRangeFromEvent(e) {
650 return RangeUtils.getCaretRangeFromPoint(e.clientX, e.clientY, editor.getDoc());
653 function hasContentType(clipboardContent, mimeType) {
654 return mimeType in clipboardContent && clipboardContent[mimeType].length > 0;
657 function isKeyboardPasteEvent(e) {
658 return (VK.metaKeyPressed(e) && e.keyCode == 86) || (e.shiftKey && e.keyCode == 45);
661 function registerEventHandlers() {
662 editor.on('keydown', function(e) {
663 function removePasteBinOnKeyUp(e) {
664 // Ctrl+V or Shift+Insert
665 if (isKeyboardPasteEvent(e) && !e.isDefaultPrevented()) {
670 // Ctrl+V or Shift+Insert
671 if (isKeyboardPasteEvent(e) && !e.isDefaultPrevented()) {
672 keyboardPastePlainTextState = e.shiftKey && e.keyCode == 86;
674 // Edge case on Safari on Mac where it doesn't handle Cmd+Shift+V correctly
675 // it fires the keydown but no paste or keyup so we are left with a paste bin
676 if (keyboardPastePlainTextState && Env.webkit && navigator.userAgent.indexOf('Version/') != -1) {
680 // Prevent undoManager keydown handler from making an undo level with the pastebin in it
681 e.stopImmediatePropagation();
683 keyboardPasteTimeStamp = new Date().getTime();
685 // IE doesn't support Ctrl+Shift+V and it doesn't even produce a paste event
686 // so lets fake a paste event and let IE use the execCommand/dataTransfer methods
687 if (Env.ie && keyboardPastePlainTextState) {
689 editor.fire('paste', {ieFake: true});
696 // Remove pastebin if we get a keyup and no paste event
697 // For example pasting a file in IE 11 will not produce a paste event
698 editor.once('keyup', removePasteBinOnKeyUp);
699 editor.once('paste', function() {
700 editor.off('keyup', removePasteBinOnKeyUp);
705 function insertClipboardContent(clipboardContent, isKeyBoardPaste, plainTextMode) {
708 // Grab HTML from Clipboard API or paste bin as a fallback
709 if (hasContentType(clipboardContent, 'text/html')) {
710 content = clipboardContent['text/html'];
712 content = getPasteBinHtml();
714 // If paste bin is empty try using plain text mode
715 // since that is better than nothing right
716 if (content == pasteBinDefaultContent) {
717 plainTextMode = true;
721 content = Utils.trimHtml(content);
723 // WebKit has a nice bug where it clones the paste bin if you paste from for example notepad
724 // so we need to force plain text mode in this case
725 if (pasteBinElm && pasteBinElm.firstChild && pasteBinElm.firstChild.id === 'mcepastebin') {
726 plainTextMode = true;
731 // If we got nothing from clipboard API and pastebin then we could try the last resort: plain/text
732 if (!content.length) {
733 plainTextMode = true;
736 // Grab plain text from Clipboard API or convert existing HTML to plain text
738 // Use plain text contents from Clipboard API unless the HTML contains paragraphs then
739 // we should convert the HTML to plain text since works better when pasting HTML/Word contents as plain text
740 if (hasContentType(clipboardContent, 'text/plain') && content.indexOf('</p>') == -1) {
741 content = clipboardContent['text/plain'];
743 content = Utils.innerText(content);
747 // If the content is the paste bin default HTML then it was
748 // impossible to get the cliboard data out.
749 if (content == pasteBinDefaultContent) {
750 if (!isKeyBoardPaste) {
751 editor.windowManager.alert('Please use Ctrl+V/Cmd+V keyboard shortcuts to paste contents.');
764 var getLastRng = function() {
765 return lastRng || editor.selection.getRng();
768 editor.on('paste', function(e) {
769 // Getting content from the Clipboard can take some time
770 var clipboardTimer = new Date().getTime();
771 var clipboardContent = getClipboardContent(e);
772 var clipboardDelay = new Date().getTime() - clipboardTimer;
774 var isKeyBoardPaste = (new Date().getTime() - keyboardPasteTimeStamp - clipboardDelay) < 1000;
775 var plainTextMode = self.pasteFormat == "text" || keyboardPastePlainTextState;
777 keyboardPastePlainTextState = false;
779 if (e.isDefaultPrevented() || isBrokenAndroidClipboardEvent(e)) {
784 if (!hasHtmlOrText(clipboardContent) && pasteImageData(e, getLastRng())) {
789 // Not a keyboard paste prevent default paste and try to grab the clipboard contents using different APIs
790 if (!isKeyBoardPaste) {
794 // Try IE only method if paste isn't a keyboard paste
795 if (Env.ie && (!isKeyBoardPaste || e.ieFake)) {
798 editor.dom.bind(pasteBinElm, 'paste', function(e) {
802 editor.getDoc().execCommand('Paste', false, null);
803 clipboardContent["text/html"] = getPasteBinHtml();
806 // If clipboard API has HTML then use that directly
807 if (hasContentType(clipboardContent, 'text/html')) {
809 insertClipboardContent(clipboardContent, isKeyBoardPaste, plainTextMode);
811 Delay.setEditorTimeout(editor, function() {
812 insertClipboardContent(clipboardContent, isKeyBoardPaste, plainTextMode);
817 editor.on('dragstart dragend', function(e) {
818 draggingInternally = e.type == 'dragstart';
821 function isPlainTextFileUrl(content) {
822 return content['text/plain'].indexOf('file://') === 0;
825 editor.on('drop', function(e) {
826 var dropContent, rng;
828 rng = getCaretRangeFromEvent(e);
830 if (e.isDefaultPrevented() || draggingInternally) {
834 dropContent = getDataTransferItems(e.dataTransfer);
836 if ((!hasHtmlOrText(dropContent) || isPlainTextFileUrl(dropContent)) && pasteImageData(e, rng)) {
840 if (rng && editor.settings.paste_filter_drop !== false) {
841 var content = dropContent['mce-internal'] || dropContent['text/html'] || dropContent['text/plain'];
846 // FF 45 doesn't paint a caret when dragging in text in due to focus call by execCommand
847 Delay.setEditorTimeout(editor, function() {
848 editor.undoManager.transact(function() {
849 if (dropContent['mce-internal']) {
850 editor.execCommand('Delete');
853 editor.selection.setRng(rng);
855 content = Utils.trimHtml(content);
857 if (!dropContent['text/html']) {
868 editor.on('dragover dragend', function(e) {
869 if (editor.settings.paste_data_images) {
875 self.pasteHtml = pasteHtml;
876 self.pasteText = pasteText;
878 editor.on('preInit', function() {
879 registerEventHandlers();
881 // Remove all data images from paste for example from Gecko
882 // except internal images like video elements
883 editor.parser.addNodeFilter('img', function(nodes, name, args) {
884 function isPasteInsert(args) {
885 return args.data && args.data.paste === true;
888 function remove(node) {
889 if (!node.attr('data-mce-object') && src !== Env.transparentSrc) {
894 function isWebKitFakeUrl(src) {
895 return src.indexOf("webkit-fake-url") === 0;
898 function isDataUri(src) {
899 return src.indexOf("data:") === 0;
902 if (!editor.settings.paste_data_images && isPasteInsert(args)) {
903 var i = nodes.length;
906 var src = nodes[i].attributes.map.src;
912 // Safari on Mac produces webkit-fake-url see: https://bugs.webkit.org/show_bug.cgi?id=49141
913 if (isWebKitFakeUrl(src)) {
915 } else if (!editor.settings.allow_html_data_urls && isDataUri(src)) {
925 // Included from: js/tinymce/plugins/paste/classes/WordFilter.js
930 * Released under LGPL License.
931 * Copyright (c) 1999-2015 Ephox Corp. All rights reserved
933 * License: http://www.tinymce.com/license
934 * Contributing: http://www.tinymce.com/contributing
938 * This class parses word HTML into proper TinyMCE markup.
940 * @class tinymce.pasteplugin.WordFilter
943 define("tinymce/pasteplugin/WordFilter", [
944 "tinymce/util/Tools",
945 "tinymce/html/DomParser",
946 "tinymce/html/Schema",
947 "tinymce/html/Serializer",
949 "tinymce/pasteplugin/Utils"
950 ], function(Tools, DomParser, Schema, Serializer, Node, Utils) {
952 * Checks if the specified content is from any of the following sources: MS Word/Office 365/Google docs.
954 function isWordContent(content) {
956 (/<font face="Times New Roman"|class="?Mso|style="[^"]*\bmso-|style='[^'']*\bmso-|w:WordDocument/i).test(content) ||
957 (/class="OutlineElement/).test(content) ||
958 (/id="?docs\-internal\-guid\-/.test(content))
963 * Checks if the specified text starts with "1. " or "a. " etc.
965 function isNumericList(text) {
969 /^[IVXLMCD]{1,2}\.[ \u00a0]/, // Roman upper case
970 /^[ivxlmcd]{1,2}\.[ \u00a0]/, // Roman lower case
971 /^[a-z]{1,2}[\.\)][ \u00a0]/, // Alphabetical a-z
972 /^[A-Z]{1,2}[\.\)][ \u00a0]/, // Alphabetical A-Z
973 /^[0-9]+\.[ \u00a0]/, // Numeric lists
974 /^[\u3007\u4e00\u4e8c\u4e09\u56db\u4e94\u516d\u4e03\u516b\u4e5d]+\.[ \u00a0]/, // Japanese
975 /^[\u58f1\u5f10\u53c2\u56db\u4f0d\u516d\u4e03\u516b\u4e5d\u62fe]+\.[ \u00a0]/ // Chinese
978 text = text.replace(/^[\u00a0 ]+/, '');
980 Tools.each(patterns, function(pattern) {
981 if (pattern.test(text)) {
990 function isBulletList(text) {
991 return /^[\s\u00a0]*[\u2022\u00b7\u00a7\u25CF]\s*/.test(text);
994 function WordFilter(editor) {
995 var settings = editor.settings;
997 editor.on('BeforePastePreProcess', function(e) {
998 var content = e.content, retainStyleProperties, validStyles;
1000 // Remove google docs internal guid markers
1001 content = content.replace(/<b[^>]+id="?docs-internal-[^>]*>/gi, '');
1002 content = content.replace(/<br class="?Apple-interchange-newline"?>/gi, '');
1004 retainStyleProperties = settings.paste_retain_style_properties;
1005 if (retainStyleProperties) {
1006 validStyles = Tools.makeMap(retainStyleProperties.split(/[, ]/));
1010 * Converts fake bullet and numbered lists to real semantic OL/UL.
1012 * @param {tinymce.html.Node} node Root node to convert children of.
1014 function convertFakeListsToProperLists(node) {
1015 var currentListNode, prevListNode, lastLevel = 1;
1017 function getText(node) {
1020 if (node.type === 3) {
1024 if ((node = node.firstChild)) {
1026 txt += getText(node);
1027 } while ((node = node.next));
1033 function trimListStart(node, regExp) {
1034 if (node.type === 3) {
1035 if (regExp.test(node.value)) {
1036 node.value = node.value.replace(regExp, '');
1041 if ((node = node.firstChild)) {
1043 if (!trimListStart(node, regExp)) {
1046 } while ((node = node.next));
1052 function removeIgnoredNodes(node) {
1053 if (node._listIgnore) {
1058 if ((node = node.firstChild)) {
1060 removeIgnoredNodes(node);
1061 } while ((node = node.next));
1065 function convertParagraphToLi(paragraphNode, listName, start) {
1066 var level = paragraphNode._listLevel || lastLevel;
1068 // Handle list nesting
1069 if (level != lastLevel) {
1070 if (level < lastLevel) {
1071 // Move to parent list
1072 if (currentListNode) {
1073 currentListNode = currentListNode.parent.parent;
1077 prevListNode = currentListNode;
1078 currentListNode = null;
1082 if (!currentListNode || currentListNode.name != listName) {
1083 prevListNode = prevListNode || currentListNode;
1084 currentListNode = new Node(listName, 1);
1087 currentListNode.attr('start', '' + start);
1090 paragraphNode.wrap(currentListNode);
1092 currentListNode.append(paragraphNode);
1095 paragraphNode.name = 'li';
1097 // Append list to previous list if it exists
1098 if (level > lastLevel && prevListNode) {
1099 prevListNode.lastChild.append(currentListNode);
1104 // Remove start of list item "1. " or "· " etc
1105 removeIgnoredNodes(paragraphNode);
1106 trimListStart(paragraphNode, /^\u00a0+/);
1107 trimListStart(paragraphNode, /^\s*([\u2022\u00b7\u00a7\u25CF]|\w+\.)/);
1108 trimListStart(paragraphNode, /^\u00a0+/);
1111 // Build a list of all root level elements before we start
1112 // altering them in the loop below.
1113 var elements = [], child = node.firstChild;
1114 while (typeof child !== 'undefined' && child !== null) {
1115 elements.push(child);
1117 child = child.walk();
1118 if (child !== null) {
1119 while (typeof child !== 'undefined' && child.parent !== node) {
1120 child = child.walk();
1125 for (var i = 0; i < elements.length; i++) {
1128 if (node.name == 'p' && node.firstChild) {
1129 // Find first text node in paragraph
1130 var nodeText = getText(node);
1132 // Detect unordered lists look for bullets
1133 if (isBulletList(nodeText)) {
1134 convertParagraphToLi(node, 'ul');
1138 // Detect ordered lists 1., a. or ixv.
1139 if (isNumericList(nodeText)) {
1140 // Parse OL start number
1141 var matches = /([0-9]+)\./.exec(nodeText);
1144 start = parseInt(matches[1], 10);
1147 convertParagraphToLi(node, 'ol', start);
1151 // Convert paragraphs marked as lists but doesn't look like anything
1152 if (node._listLevel) {
1153 convertParagraphToLi(node, 'ul', 1);
1157 currentListNode = null;
1159 // If the root level element isn't a p tag which can be
1160 // processed by convertParagraphToLi, it interrupts the
1161 // lists, causing a new list to start instead of having
1162 // elements from the next list inserted above this tag.
1163 prevListNode = currentListNode;
1164 currentListNode = null;
1169 function filterStyles(node, styleValue) {
1170 var outputStyles = {}, matches, styles = editor.dom.parseStyle(styleValue);
1172 Tools.each(styles, function(value, name) {
1173 // Convert various MS styles to W3C styles
1176 // Parse out list indent level for lists
1177 matches = /\w+ \w+([0-9]+)/i.exec(styleValue);
1179 node._listLevel = parseInt(matches[1], 10);
1182 // Remove these nodes <span style="mso-list:Ignore">o</span>
1183 // Since the span gets removed we mark the text node and the span
1184 if (/Ignore/i.test(value) && node.firstChild) {
1185 node._listIgnore = true;
1186 node.firstChild._listIgnore = true;
1192 name = "text-align";
1196 name = "vertical-align";
1200 case "mso-foreground":
1204 case "mso-background":
1205 case "mso-highlight":
1206 name = "background";
1211 if (value != "normal") {
1212 outputStyles[name] = value;
1217 // Remove track changes code
1218 if (/^(comment|comment-list)$/i.test(value)) {
1226 if (name.indexOf('mso-comment') === 0) {
1231 // Never allow mso- prefixed names
1232 if (name.indexOf('mso-') === 0) {
1236 // Output only valid styles
1237 if (retainStyleProperties == "all" || (validStyles && validStyles[name])) {
1238 outputStyles[name] = value;
1242 // Convert bold style to "b" element
1243 if (/(bold)/i.test(outputStyles["font-weight"])) {
1244 delete outputStyles["font-weight"];
1245 node.wrap(new Node("b", 1));
1248 // Convert italic style to "i" element
1249 if (/(italic)/i.test(outputStyles["font-style"])) {
1250 delete outputStyles["font-style"];
1251 node.wrap(new Node("i", 1));
1254 // Serialize the styles and see if there is something left to keep
1255 outputStyles = editor.dom.serializeStyle(outputStyles, node.name);
1257 return outputStyles;
1263 if (settings.paste_enable_default_filters === false) {
1267 // Detect is the contents is Word junk HTML
1268 if (isWordContent(e.content)) {
1269 e.wordContent = true; // Mark it for other processors
1271 // Remove basic Word junk
1272 content = Utils.filter(content, [
1273 // Word comments like conditional comments etc
1274 /<!--[\s\S]+?-->/gi,
1276 // Remove comments, scripts (e.g., msoShowComment), XML tag, VML content,
1277 // MS Office namespaced tags, and a few other tags
1278 /<(!|script[^>]*>.*?<\/script(?=[>\s])|\/?(\?xml(:\w+)?|img|meta|link|style|\w:\w+)(?=[\s\/>]))[^>]*>/gi,
1280 // Convert <s> into <strike> for line-though
1281 [/<(\/?)s>/gi, "<$1strike>"],
1283 // Replace nsbp entites to char since it's easier to handle
1284 [/ /gi, "\u00a0"],
1286 // Convert <span style="mso-spacerun:yes">___</span> to string of alternating
1287 // breaking/non-breaking spaces of same length
1288 [/<span\s+style\s*=\s*"\s*mso-spacerun\s*:\s*yes\s*;?\s*"\s*>([\s\u00a0]*)<\/span>/gi,
1289 function(str, spaces) {
1290 return (spaces.length > 0) ?
1291 spaces.replace(/./, " ").slice(Math.floor(spaces.length / 2)).split("").join("\u00a0") : "";
1296 var validElements = settings.paste_word_valid_elements;
1297 if (!validElements) {
1299 '-strong/b,-em/i,-u,-span,-p,-ol,-ul,-li,-h1,-h2,-h3,-h4,-h5,-h6,' +
1300 '-p/div,-a[href|name],sub,sup,strike,br,del,table[width],tr,' +
1301 'td[colspan|rowspan|width],th[colspan|rowspan|width],thead,tfoot,tbody'
1305 // Setup strict schema
1306 var schema = new Schema({
1307 valid_elements: validElements,
1308 valid_children: '-li[p]'
1311 // Add style/class attribute to all element rules since the user might have removed them from
1312 // paste_word_valid_elements config option and we need to check them for properties
1313 Tools.each(schema.elements, function(rule) {
1314 /*eslint dot-notation:0*/
1315 if (!rule.attributes["class"]) {
1316 rule.attributes["class"] = {};
1317 rule.attributesOrder.push("class");
1320 if (!rule.attributes.style) {
1321 rule.attributes.style = {};
1322 rule.attributesOrder.push("style");
1326 // Parse HTML into DOM structure
1327 var domParser = new DomParser({}, schema);
1329 // Filter styles to remove "mso" specific styles and convert some of them
1330 domParser.addAttributeFilter('style', function(nodes) {
1331 var i = nodes.length, node;
1335 node.attr('style', filterStyles(node, node.attr('style')));
1337 // Remove pointess spans
1338 if (node.name == 'span' && node.parent && !node.attributes.length) {
1344 // Check the class attribute for comments or del items and remove those
1345 domParser.addAttributeFilter('class', function(nodes) {
1346 var i = nodes.length, node, className;
1351 className = node.attr('class');
1352 if (/^(MsoCommentReference|MsoCommentText|msoDel)$/i.test(className)) {
1356 node.attr('class', null);
1360 // Remove all del elements since we don't want the track changes code in the editor
1361 domParser.addNodeFilter('del', function(nodes) {
1362 var i = nodes.length;
1369 // Keep some of the links and anchors
1370 domParser.addNodeFilter('a', function(nodes) {
1371 var i = nodes.length, node, href, name;
1375 href = node.attr('href');
1376 name = node.attr('name');
1378 if (href && href.indexOf('#_msocom_') != -1) {
1383 if (href && href.indexOf('file://') === 0) {
1384 href = href.split('#')[1];
1390 if (!href && !name) {
1393 // Remove all named anchors that aren't specific to TOC, Footnotes or Endnotes
1394 if (name && !/^_?(?:toc|edn|ftn)/i.test(name)) {
1407 // Parse into DOM structure
1408 var rootNode = domParser.parse(content);
1411 if (settings.paste_convert_word_fake_lists !== false) {
1412 convertFakeListsToProperLists(rootNode);
1415 // Serialize DOM back to HTML
1416 e.content = new Serializer({
1417 validate: settings.validate
1418 }, schema).serialize(rootNode);
1423 WordFilter.isWordContent = isWordContent;
1428 // Included from: js/tinymce/plugins/paste/classes/Quirks.js
1433 * Released under LGPL License.
1434 * Copyright (c) 1999-2015 Ephox Corp. All rights reserved
1436 * License: http://www.tinymce.com/license
1437 * Contributing: http://www.tinymce.com/contributing
1441 * This class contains various fixes for browsers. These issues can not be feature
1442 * detected since we have no direct control over the clipboard. However we might be able
1443 * to remove some of these fixes once the browsers gets updated/fixed.
1445 * @class tinymce.pasteplugin.Quirks
1448 define("tinymce/pasteplugin/Quirks", [
1450 "tinymce/util/Tools",
1451 "tinymce/pasteplugin/WordFilter",
1452 "tinymce/pasteplugin/Utils"
1453 ], function(Env, Tools, WordFilter, Utils) {
1456 return function(editor) {
1457 function addPreProcessFilter(filterFunc) {
1458 editor.on('BeforePastePreProcess', function(e) {
1459 e.content = filterFunc(e.content);
1464 * Removes BR elements after block elements. IE9 has a nasty bug where it puts a BR element after each
1465 * block element when pasting from word. This removes those elements.
1468 * <p>a</p><br><p>b</p>
1473 function removeExplorerBrElementsAfterBlocks(html) {
1474 // Only filter word specific content
1475 if (!WordFilter.isWordContent(html)) {
1479 // Produce block regexp based on the block elements in schema
1480 var blockElements = [];
1482 Tools.each(editor.schema.getBlockElements(), function(block, blockName) {
1483 blockElements.push(blockName);
1486 var explorerBlocksRegExp = new RegExp(
1487 '(?:<br> [\\s\\r\\n]+|<br>)*(<\\/?(' + blockElements.join('|') + ')[^>]*>)(?:<br> [\\s\\r\\n]+|<br>)*',
1491 // Remove BR:s from: <BLOCK>X</BLOCK><BR>
1492 html = Utils.filter(html, [
1493 [explorerBlocksRegExp, '$1']
1496 // IE9 also adds an extra BR element for each soft-linefeed and it also adds a BR for each word wrap break
1497 html = Utils.filter(html, [
1498 [/<br><br>/g, '<BR><BR>'], // Replace multiple BR elements with uppercase BR to keep them intact
1499 [/<br>/g, ' '], // Replace single br elements with space since they are word wrap BR:s
1500 [/<BR><BR>/g, '<br>'] // Replace back the double brs but into a single BR
1507 * WebKit has a nasty bug where the all computed styles gets added to style attributes when copy/pasting contents.
1508 * This fix solves that by simply removing the whole style attribute.
1510 * The paste_webkit_styles option can be set to specify what to keep:
1511 * paste_webkit_styles: "none" // Keep no styles
1512 * paste_webkit_styles: "all", // Keep all of them
1513 * paste_webkit_styles: "font-weight color" // Keep specific ones
1515 * @param {String} content Content that needs to be processed.
1516 * @return {String} Processed contents.
1518 function removeWebKitStyles(content) {
1519 // Passthrough all styles from Word and let the WordFilter handle that junk
1520 if (WordFilter.isWordContent(content)) {
1524 // Filter away styles that isn't matching the target node
1525 var webKitStyles = editor.settings.paste_webkit_styles;
1527 if (editor.settings.paste_remove_styles_if_webkit === false || webKitStyles == "all") {
1532 webKitStyles = webKitStyles.split(/[, ]/);
1535 // Keep specific styles that doesn't match the current node computed style
1537 var dom = editor.dom, node = editor.selection.getNode();
1539 content = content.replace(/(<[^>]+) style="([^"]*)"([^>]*>)/gi, function(all, before, value, after) {
1540 var inputStyles = dom.parseStyle(value, 'span'), outputStyles = {};
1542 if (webKitStyles === "none") {
1543 return before + after;
1546 for (var i = 0; i < webKitStyles.length; i++) {
1547 var inputValue = inputStyles[webKitStyles[i]], currentValue = dom.getStyle(node, webKitStyles[i], true);
1549 if (/color/.test(webKitStyles[i])) {
1550 inputValue = dom.toHex(inputValue);
1551 currentValue = dom.toHex(currentValue);
1554 if (currentValue != inputValue) {
1555 outputStyles[webKitStyles[i]] = inputValue;
1559 outputStyles = dom.serializeStyle(outputStyles, 'span');
1561 return before + ' style="' + outputStyles + '"' + after;
1564 return before + after;
1567 // Remove all external styles
1568 content = content.replace(/(<[^>]+) style="([^"]*)"([^>]*>)/gi, '$1$3');
1571 // Keep internal styles
1572 content = content.replace(/(<[^>]+) data-mce-style="([^"]+)"([^>]*>)/gi, function(all, before, value, after) {
1573 return before + ' style="' + value + '"' + after;
1579 // Sniff browsers and apply fixes since we can't feature detect
1581 addPreProcessFilter(removeWebKitStyles);
1585 addPreProcessFilter(removeExplorerBrElementsAfterBlocks);
1590 // Included from: js/tinymce/plugins/paste/classes/Plugin.js
1595 * Released under LGPL License.
1596 * Copyright (c) 1999-2015 Ephox Corp. All rights reserved
1598 * License: http://www.tinymce.com/license
1599 * Contributing: http://www.tinymce.com/contributing
1603 * This class contains the tinymce plugin logic for the paste plugin.
1605 * @class tinymce.pasteplugin.Plugin
1608 define("tinymce/pasteplugin/Plugin", [
1609 "tinymce/PluginManager",
1610 "tinymce/pasteplugin/Clipboard",
1611 "tinymce/pasteplugin/WordFilter",
1612 "tinymce/pasteplugin/Quirks"
1613 ], function(PluginManager, Clipboard, WordFilter, Quirks) {
1616 PluginManager.add('paste', function(editor) {
1617 var self = this, clipboard, settings = editor.settings;
1619 function isUserInformedAboutPlainText() {
1620 return userIsInformed || editor.settings.paste_plaintext_inform === false;
1623 function togglePlainTextPaste() {
1624 if (clipboard.pasteFormat == "text") {
1626 clipboard.pasteFormat = "html";
1627 editor.fire('PastePlainTextToggle', {state: false});
1629 clipboard.pasteFormat = "text";
1632 if (!isUserInformedAboutPlainText()) {
1633 var message = editor.translate('Paste is now in plain text mode. Contents will now ' +
1634 'be pasted as plain text until you toggle this option off.');
1636 editor.notificationManager.open({
1641 userIsInformed = true;
1642 editor.fire('PastePlainTextToggle', {state: true});
1649 self.clipboard = clipboard = new Clipboard(editor);
1650 self.quirks = new Quirks(editor);
1651 self.wordFilter = new WordFilter(editor);
1653 if (editor.settings.paste_as_text) {
1654 self.clipboard.pasteFormat = "text";
1657 if (settings.paste_preprocess) {
1658 editor.on('PastePreProcess', function(e) {
1659 settings.paste_preprocess.call(self, self, e);
1663 if (settings.paste_postprocess) {
1664 editor.on('PastePostProcess', function(e) {
1665 settings.paste_postprocess.call(self, self, e);
1669 editor.addCommand('mceInsertClipboardContent', function(ui, value) {
1670 if (value.content) {
1671 self.clipboard.pasteHtml(value.content);
1675 self.clipboard.pasteText(value.text);
1679 // Block all drag/drop events
1680 if (editor.settings.paste_block_drop) {
1681 editor.on('dragend dragover draggesture dragdrop drop drag', function(e) {
1683 e.stopPropagation();
1687 // Prevent users from dropping data images on Gecko
1688 if (!editor.settings.paste_data_images) {
1689 editor.on('drop', function(e) {
1690 var dataTransfer = e.dataTransfer;
1692 if (dataTransfer && dataTransfer.files && dataTransfer.files.length > 0) {
1698 editor.addButton('pastetext', {
1700 tooltip: 'Paste as text',
1701 onclick: togglePlainTextPaste,
1702 active: self.clipboard.pasteFormat == "text"
1705 editor.addMenuItem('pastetext', {
1706 text: 'Paste as text',
1708 active: clipboard.pasteFormat,
1709 onclick: togglePlainTextPaste
1714 expose(["tinymce/pasteplugin/Utils"]);