/modules/mod_base/lib/js/modules/tinymce3.4.3.2/plugins/paste/editor_plugin_src.js

https://code.google.com/p/zotonic/ · JavaScript · 942 lines · 758 code · 88 blank · 96 comment · 106 complexity · 65e17bcbe468725a287ba306dcc361ff MD5 · raw file

  1. /**
  2. * editor_plugin_src.js
  3. *
  4. * Copyright 2009, Moxiecode Systems AB
  5. * Released under LGPL License.
  6. *
  7. * License: http://tinymce.moxiecode.com/license
  8. * Contributing: http://tinymce.moxiecode.com/contributing
  9. */
  10. (function() {
  11. var each = tinymce.each,
  12. defs = {
  13. paste_auto_cleanup_on_paste : true,
  14. paste_enable_default_filters : true,
  15. paste_block_drop : false,
  16. paste_retain_style_properties : "none",
  17. paste_strip_class_attributes : "mso",
  18. paste_remove_spans : false,
  19. paste_remove_styles : false,
  20. paste_remove_styles_if_webkit : true,
  21. paste_convert_middot_lists : true,
  22. paste_convert_headers_to_strong : false,
  23. paste_dialog_width : "450",
  24. paste_dialog_height : "400",
  25. paste_text_use_dialog : false,
  26. paste_text_sticky : false,
  27. paste_text_sticky_default : false,
  28. paste_text_notifyalways : false,
  29. paste_text_linebreaktype : "p",
  30. paste_text_replacements : [
  31. [/\u2026/g, "..."],
  32. [/[\x93\x94\u201c\u201d]/g, '"'],
  33. [/[\x60\x91\x92\u2018\u2019]/g, "'"]
  34. ]
  35. };
  36. function getParam(ed, name) {
  37. return ed.getParam(name, defs[name]);
  38. }
  39. tinymce.create('tinymce.plugins.PastePlugin', {
  40. init : function(ed, url) {
  41. var t = this;
  42. t.editor = ed;
  43. t.url = url;
  44. // Setup plugin events
  45. t.onPreProcess = new tinymce.util.Dispatcher(t);
  46. t.onPostProcess = new tinymce.util.Dispatcher(t);
  47. // Register default handlers
  48. t.onPreProcess.add(t._preProcess);
  49. t.onPostProcess.add(t._postProcess);
  50. // Register optional preprocess handler
  51. t.onPreProcess.add(function(pl, o) {
  52. ed.execCallback('paste_preprocess', pl, o);
  53. });
  54. // Register optional postprocess
  55. t.onPostProcess.add(function(pl, o) {
  56. ed.execCallback('paste_postprocess', pl, o);
  57. });
  58. ed.onKeyDown.addToTop(function(ed, e) {
  59. // Block ctrl+v from adding an undo level since the default logic in tinymce.Editor will add that
  60. if (((tinymce.isMac ? e.metaKey : e.ctrlKey) && e.keyCode == 86) || (e.shiftKey && e.keyCode == 45))
  61. return false; // Stop other listeners
  62. });
  63. // Initialize plain text flag
  64. ed.pasteAsPlainText = getParam(ed, 'paste_text_sticky_default');
  65. // This function executes the process handlers and inserts the contents
  66. // force_rich overrides plain text mode set by user, important for pasting with execCommand
  67. function process(o, force_rich) {
  68. var dom = ed.dom, rng;
  69. // Execute pre process handlers
  70. t.onPreProcess.dispatch(t, o);
  71. // Create DOM structure
  72. o.node = dom.create('div', 0, o.content);
  73. // If pasting inside the same element and the contents is only one block
  74. // remove the block and keep the text since Firefox will copy parts of pre and h1-h6 as a pre element
  75. if (tinymce.isGecko) {
  76. rng = ed.selection.getRng(true);
  77. if (rng.startContainer == rng.endContainer && rng.startContainer.nodeType == 3) {
  78. // Is only one block node and it doesn't contain word stuff
  79. if (o.node.childNodes.length === 1 && /^(p|h[1-6]|pre)$/i.test(o.node.firstChild.nodeName) && o.content.indexOf('__MCE_ITEM__') === -1)
  80. dom.remove(o.node.firstChild, true);
  81. }
  82. }
  83. // Execute post process handlers
  84. t.onPostProcess.dispatch(t, o);
  85. // Serialize content
  86. o.content = ed.serializer.serialize(o.node, {getInner : 1, forced_root_block : ''});
  87. // Plain text option active?
  88. if ((!force_rich) && (ed.pasteAsPlainText)) {
  89. t._insertPlainText(ed, dom, o.content);
  90. if (!getParam(ed, "paste_text_sticky")) {
  91. ed.pasteAsPlainText = false;
  92. ed.controlManager.setActive("pastetext", false);
  93. }
  94. } else {
  95. t._insert(o.content);
  96. }
  97. }
  98. // Add command for external usage
  99. ed.addCommand('mceInsertClipboardContent', function(u, o) {
  100. process(o, true);
  101. });
  102. if (!getParam(ed, "paste_text_use_dialog")) {
  103. ed.addCommand('mcePasteText', function(u, v) {
  104. var cookie = tinymce.util.Cookie;
  105. ed.pasteAsPlainText = !ed.pasteAsPlainText;
  106. ed.controlManager.setActive('pastetext', ed.pasteAsPlainText);
  107. if ((ed.pasteAsPlainText) && (!cookie.get("tinymcePasteText"))) {
  108. if (getParam(ed, "paste_text_sticky")) {
  109. ed.windowManager.alert(ed.translate('paste.plaintext_mode_sticky'));
  110. } else {
  111. ed.windowManager.alert(ed.translate('paste.plaintext_mode_sticky'));
  112. }
  113. if (!getParam(ed, "paste_text_notifyalways")) {
  114. cookie.set("tinymcePasteText", "1", new Date(new Date().getFullYear() + 1, 12, 31))
  115. }
  116. }
  117. });
  118. }
  119. ed.addButton('pastetext', {title: 'paste.paste_text_desc', cmd: 'mcePasteText'});
  120. ed.addButton('selectall', {title: 'paste.selectall_desc', cmd: 'selectall'});
  121. // This function grabs the contents from the clipboard by adding a
  122. // hidden div and placing the caret inside it and after the browser paste
  123. // is done it grabs that contents and processes that
  124. function grabContent(e) {
  125. var n, or, rng, oldRng, sel = ed.selection, dom = ed.dom, body = ed.getBody(), posY, textContent;
  126. // Check if browser supports direct plaintext access
  127. if (e.clipboardData || dom.doc.dataTransfer) {
  128. textContent = (e.clipboardData || dom.doc.dataTransfer).getData('Text');
  129. if (ed.pasteAsPlainText) {
  130. e.preventDefault();
  131. process({content : textContent.replace(/\r?\n/g, '<br />')});
  132. return;
  133. }
  134. }
  135. if (dom.get('_mcePaste'))
  136. return;
  137. // Create container to paste into
  138. n = dom.add(body, 'div', {id : '_mcePaste', 'class' : 'mcePaste', 'data-mce-bogus' : '1'}, '\uFEFF\uFEFF');
  139. // If contentEditable mode we need to find out the position of the closest element
  140. if (body != ed.getDoc().body)
  141. posY = dom.getPos(ed.selection.getStart(), body).y;
  142. else
  143. posY = body.scrollTop + dom.getViewPort(ed.getWin()).y;
  144. // Styles needs to be applied after the element is added to the document since WebKit will otherwise remove all styles
  145. // If also needs to be in view on IE or the paste would fail
  146. dom.setStyles(n, {
  147. position : 'absolute',
  148. left : tinymce.isGecko ? -40 : 0, // Need to move it out of site on Gecko since it will othewise display a ghost resize rect for the div
  149. top : posY - 25,
  150. width : 1,
  151. height : 1,
  152. overflow : 'hidden'
  153. });
  154. if (tinymce.isIE) {
  155. // Store away the old range
  156. oldRng = sel.getRng();
  157. // Select the container
  158. rng = dom.doc.body.createTextRange();
  159. rng.moveToElementText(n);
  160. rng.execCommand('Paste');
  161. // Remove container
  162. dom.remove(n);
  163. // Check if the contents was changed, if it wasn't then clipboard extraction failed probably due
  164. // to IE security settings so we pass the junk though better than nothing right
  165. if (n.innerHTML === '\uFEFF\uFEFF') {
  166. ed.execCommand('mcePasteWord');
  167. e.preventDefault();
  168. return;
  169. }
  170. // Restore the old range and clear the contents before pasting
  171. sel.setRng(oldRng);
  172. sel.setContent('');
  173. // For some odd reason we need to detach the the mceInsertContent call from the paste event
  174. // It's like IE has a reference to the parent element that you paste in and the selection gets messed up
  175. // when it tries to restore the selection
  176. setTimeout(function() {
  177. // Process contents
  178. process({content : n.innerHTML});
  179. }, 0);
  180. // Block the real paste event
  181. return tinymce.dom.Event.cancel(e);
  182. } else {
  183. function block(e) {
  184. e.preventDefault();
  185. };
  186. // Block mousedown and click to prevent selection change
  187. dom.bind(ed.getDoc(), 'mousedown', block);
  188. dom.bind(ed.getDoc(), 'keydown', block);
  189. or = ed.selection.getRng();
  190. // Move select contents inside DIV
  191. n = n.firstChild;
  192. rng = ed.getDoc().createRange();
  193. rng.setStart(n, 0);
  194. rng.setEnd(n, 2);
  195. sel.setRng(rng);
  196. // Wait a while and grab the pasted contents
  197. window.setTimeout(function() {
  198. var h = '', nl;
  199. // Paste divs duplicated in paste divs seems to happen when you paste plain text so lets first look for that broken behavior in WebKit
  200. if (!dom.select('div.mcePaste > div.mcePaste').length) {
  201. nl = dom.select('div.mcePaste');
  202. // WebKit will split the div into multiple ones so this will loop through then all and join them to get the whole HTML string
  203. each(nl, function(n) {
  204. var child = n.firstChild;
  205. // WebKit inserts a DIV container with lots of odd styles
  206. if (child && child.nodeName == 'DIV' && child.style.marginTop && child.style.backgroundColor) {
  207. dom.remove(child, 1);
  208. }
  209. // Remove apply style spans
  210. each(dom.select('span.Apple-style-span', n), function(n) {
  211. dom.remove(n, 1);
  212. });
  213. // Remove bogus br elements
  214. each(dom.select('br[data-mce-bogus]', n), function(n) {
  215. dom.remove(n);
  216. });
  217. // WebKit will make a copy of the DIV for each line of plain text pasted and insert them into the DIV
  218. if (n.parentNode.className != 'mcePaste')
  219. h += n.innerHTML;
  220. });
  221. } else {
  222. // Found WebKit weirdness so force the content into paragraphs this seems to happen when you paste plain text from Nodepad etc
  223. // So this logic will replace double enter with paragraphs and single enter with br so it kind of looks the same
  224. h = '<p>' + dom.encode(textContent).replace(/\r?\n\r?\n/g, '</p><p>').replace(/\r?\n/g, '<br />') + '</p>';
  225. }
  226. // Remove the nodes
  227. each(dom.select('div.mcePaste'), function(n) {
  228. dom.remove(n);
  229. });
  230. // Restore the old selection
  231. if (or)
  232. sel.setRng(or);
  233. process({content : h});
  234. // Unblock events ones we got the contents
  235. dom.unbind(ed.getDoc(), 'mousedown', block);
  236. dom.unbind(ed.getDoc(), 'keydown', block);
  237. }, 0);
  238. }
  239. }
  240. // Check if we should use the new auto process method
  241. if (getParam(ed, "paste_auto_cleanup_on_paste")) {
  242. // Is it's Opera or older FF use key handler
  243. if (tinymce.isOpera || /Firefox\/2/.test(navigator.userAgent)) {
  244. ed.onKeyDown.addToTop(function(ed, e) {
  245. if (((tinymce.isMac ? e.metaKey : e.ctrlKey) && e.keyCode == 86) || (e.shiftKey && e.keyCode == 45))
  246. grabContent(e);
  247. });
  248. } else {
  249. // Grab contents on paste event on Gecko and WebKit
  250. ed.onPaste.addToTop(function(ed, e) {
  251. return grabContent(e);
  252. });
  253. }
  254. }
  255. ed.onInit.add(function() {
  256. ed.controlManager.setActive("pastetext", ed.pasteAsPlainText);
  257. // Block all drag/drop events
  258. if (getParam(ed, "paste_block_drop")) {
  259. ed.dom.bind(ed.getBody(), ['dragend', 'dragover', 'draggesture', 'dragdrop', 'drop', 'drag'], function(e) {
  260. e.preventDefault();
  261. e.stopPropagation();
  262. return false;
  263. });
  264. }
  265. });
  266. // Add legacy support
  267. t._legacySupport();
  268. },
  269. getInfo : function() {
  270. return {
  271. longname : 'Paste text/word',
  272. author : 'Moxiecode Systems AB',
  273. authorurl : 'http://tinymce.moxiecode.com',
  274. infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/paste',
  275. version : tinymce.majorVersion + "." + tinymce.minorVersion
  276. };
  277. },
  278. _preProcess : function(pl, o) {
  279. var ed = this.editor,
  280. h = o.content,
  281. grep = tinymce.grep,
  282. explode = tinymce.explode,
  283. trim = tinymce.trim,
  284. len, stripClass;
  285. //console.log('Before preprocess:' + o.content);
  286. function process(items) {
  287. each(items, function(v) {
  288. // Remove or replace
  289. if (v.constructor == RegExp)
  290. h = h.replace(v, '');
  291. else
  292. h = h.replace(v[0], v[1]);
  293. });
  294. }
  295. if (ed.settings.paste_enable_default_filters == false) {
  296. return;
  297. }
  298. // IE9 adds BRs before/after block elements when contents is pasted from word or for example another browser
  299. if (tinymce.isIE && document.documentMode >= 9) {
  300. // IE9 adds BRs before/after block elements when contents is pasted from word or for example another browser
  301. process([[/(?:<br>&nbsp;[\s\r\n]+|<br>)*(<\/?(h[1-6r]|p|div|address|pre|form|table|tbody|thead|tfoot|th|tr|td|li|ol|ul|caption|blockquote|center|dl|dt|dd|dir|fieldset)[^>]*>)(?:<br>&nbsp;[\s\r\n]+|<br>)*/g, '$1']]);
  302. // IE9 also adds an extra BR element for each soft-linefeed and it also adds a BR for each word wrap break
  303. process([
  304. [/<br><br>/g, '<BR><BR>'], // Replace multiple BR elements with uppercase BR to keep them intact
  305. [/<br>/g, ' '], // Replace single br elements with space since they are word wrap BR:s
  306. [/<BR><BR>/g, '<br>'], // Replace back the double brs but into a single BR
  307. ]);
  308. }
  309. // Detect Word content and process it more aggressive
  310. if (/class="?Mso|style="[^"]*\bmso-|w:WordDocument/i.test(h) || o.wordContent) {
  311. o.wordContent = true; // Mark the pasted contents as word specific content
  312. //console.log('Word contents detected.');
  313. // Process away some basic content
  314. process([
  315. /^\s*(&nbsp;)+/gi, // &nbsp; entities at the start of contents
  316. /(&nbsp;|<br[^>]*>)+\s*$/gi // &nbsp; entities at the end of contents
  317. ]);
  318. if (getParam(ed, "paste_convert_headers_to_strong")) {
  319. h = h.replace(/<p [^>]*class="?MsoHeading"?[^>]*>(.*?)<\/p>/gi, "<p><strong>$1</strong></p>");
  320. }
  321. if (getParam(ed, "paste_convert_middot_lists")) {
  322. process([
  323. [/<!--\[if !supportLists\]-->/gi, '$&__MCE_ITEM__'], // Convert supportLists to a list item marker
  324. [/(<span[^>]+(?:mso-list:|:\s*symbol)[^>]+>)/gi, '$1__MCE_ITEM__'], // Convert mso-list and symbol spans to item markers
  325. [/(<p[^>]+(?:MsoListParagraph)[^>]+>)/gi, '$1__MCE_ITEM__'] // Convert mso-list and symbol paragraphs to item markers (FF)
  326. ]);
  327. }
  328. process([
  329. // Word comments like conditional comments etc
  330. /<!--[\s\S]+?-->/gi,
  331. // Remove comments, scripts (e.g., msoShowComment), XML tag, VML content, MS Office namespaced tags, and a few other tags
  332. /<(!|script[^>]*>.*?<\/script(?=[>\s])|\/?(\?xml(:\w+)?|img|meta|link|style|\w:\w+)(?=[\s\/>]))[^>]*>/gi,
  333. // Convert <s> into <strike> for line-though
  334. [/<(\/?)s>/gi, "<$1strike>"],
  335. // Replace nsbp entites to char since it's easier to handle
  336. [/&nbsp;/gi, "\u00a0"]
  337. ]);
  338. // Remove bad attributes, with or without quotes, ensuring that attribute text is really inside a tag.
  339. // If JavaScript had a RegExp look-behind, we could have integrated this with the last process() array and got rid of the loop. But alas, it does not, so we cannot.
  340. do {
  341. len = h.length;
  342. h = h.replace(/(<[a-z][^>]*\s)(?:id|name|language|type|on\w+|\w+:\w+)=(?:"[^"]*"|\w+)\s?/gi, "$1");
  343. } while (len != h.length);
  344. // Remove all spans if no styles is to be retained
  345. if (getParam(ed, "paste_retain_style_properties").replace(/^none$/i, "").length == 0) {
  346. h = h.replace(/<\/?span[^>]*>/gi, "");
  347. } else {
  348. // We're keeping styles, so at least clean them up.
  349. // CSS Reference: http://msdn.microsoft.com/en-us/library/aa155477.aspx
  350. process([
  351. // Convert <span style="mso-spacerun:yes">___</span> to string of alternating breaking/non-breaking spaces of same length
  352. [/<span\s+style\s*=\s*"\s*mso-spacerun\s*:\s*yes\s*;?\s*"\s*>([\s\u00a0]*)<\/span>/gi,
  353. function(str, spaces) {
  354. return (spaces.length > 0)? spaces.replace(/./, " ").slice(Math.floor(spaces.length/2)).split("").join("\u00a0") : "";
  355. }
  356. ],
  357. // Examine all styles: delete junk, transform some, and keep the rest
  358. [/(<[a-z][^>]*)\sstyle="([^"]*)"/gi,
  359. function(str, tag, style) {
  360. var n = [],
  361. i = 0,
  362. s = explode(trim(style).replace(/&quot;/gi, "'"), ";");
  363. // Examine each style definition within the tag's style attribute
  364. each(s, function(v) {
  365. var name, value,
  366. parts = explode(v, ":");
  367. function ensureUnits(v) {
  368. return v + ((v !== "0") && (/\d$/.test(v)))? "px" : "";
  369. }
  370. if (parts.length == 2) {
  371. name = parts[0].toLowerCase();
  372. value = parts[1].toLowerCase();
  373. // Translate certain MS Office styles into their CSS equivalents
  374. switch (name) {
  375. case "mso-padding-alt":
  376. case "mso-padding-top-alt":
  377. case "mso-padding-right-alt":
  378. case "mso-padding-bottom-alt":
  379. case "mso-padding-left-alt":
  380. case "mso-margin-alt":
  381. case "mso-margin-top-alt":
  382. case "mso-margin-right-alt":
  383. case "mso-margin-bottom-alt":
  384. case "mso-margin-left-alt":
  385. case "mso-table-layout-alt":
  386. case "mso-height":
  387. case "mso-width":
  388. case "mso-vertical-align-alt":
  389. n[i++] = name.replace(/^mso-|-alt$/g, "") + ":" + ensureUnits(value);
  390. return;
  391. case "horiz-align":
  392. n[i++] = "text-align:" + value;
  393. return;
  394. case "vert-align":
  395. n[i++] = "vertical-align:" + value;
  396. return;
  397. case "font-color":
  398. case "mso-foreground":
  399. n[i++] = "color:" + value;
  400. return;
  401. case "mso-background":
  402. case "mso-highlight":
  403. n[i++] = "background:" + value;
  404. return;
  405. case "mso-default-height":
  406. n[i++] = "min-height:" + ensureUnits(value);
  407. return;
  408. case "mso-default-width":
  409. n[i++] = "min-width:" + ensureUnits(value);
  410. return;
  411. case "mso-padding-between-alt":
  412. n[i++] = "border-collapse:separate;border-spacing:" + ensureUnits(value);
  413. return;
  414. case "text-line-through":
  415. if ((value == "single") || (value == "double")) {
  416. n[i++] = "text-decoration:line-through";
  417. }
  418. return;
  419. case "mso-zero-height":
  420. if (value == "yes") {
  421. n[i++] = "display:none";
  422. }
  423. return;
  424. }
  425. // Eliminate all MS Office style definitions that have no CSS equivalent by examining the first characters in the name
  426. if (/^(mso|column|font-emph|lang|layout|line-break|list-image|nav|panose|punct|row|ruby|sep|size|src|tab-|table-border|text-(?!align|decor|indent|trans)|top-bar|version|vnd|word-break)/.test(name)) {
  427. return;
  428. }
  429. // If it reached this point, it must be a valid CSS style
  430. n[i++] = name + ":" + parts[1]; // Lower-case name, but keep value case
  431. }
  432. });
  433. // If style attribute contained any valid styles the re-write it; otherwise delete style attribute.
  434. if (i > 0) {
  435. return tag + ' style="' + n.join(';') + '"';
  436. } else {
  437. return tag;
  438. }
  439. }
  440. ]
  441. ]);
  442. }
  443. }
  444. // Replace headers with <strong>
  445. if (getParam(ed, "paste_convert_headers_to_strong")) {
  446. process([
  447. [/<h[1-6][^>]*>/gi, "<p><strong>"],
  448. [/<\/h[1-6][^>]*>/gi, "</strong></p>"]
  449. ]);
  450. }
  451. process([
  452. // Copy paste from Java like Open Office will produce this junk on FF
  453. [/Version:[\d.]+\nStartHTML:\d+\nEndHTML:\d+\nStartFragment:\d+\nEndFragment:\d+/gi, '']
  454. ]);
  455. // Class attribute options are: leave all as-is ("none"), remove all ("all"), or remove only those starting with mso ("mso").
  456. // Note:- paste_strip_class_attributes: "none", verify_css_classes: true is also a good variation.
  457. stripClass = getParam(ed, "paste_strip_class_attributes");
  458. if (stripClass !== "none") {
  459. function removeClasses(match, g1) {
  460. if (stripClass === "all")
  461. return '';
  462. var cls = grep(explode(g1.replace(/^(["'])(.*)\1$/, "$2"), " "),
  463. function(v) {
  464. return (/^(?!mso)/i.test(v));
  465. }
  466. );
  467. return cls.length ? ' class="' + cls.join(" ") + '"' : '';
  468. };
  469. h = h.replace(/ class="([^"]+)"/gi, removeClasses);
  470. h = h.replace(/ class=([\-\w]+)/gi, removeClasses);
  471. }
  472. // Remove spans option
  473. if (getParam(ed, "paste_remove_spans")) {
  474. h = h.replace(/<\/?span[^>]*>/gi, "");
  475. }
  476. //console.log('After preprocess:' + h);
  477. o.content = h;
  478. },
  479. /**
  480. * Various post process items.
  481. */
  482. _postProcess : function(pl, o) {
  483. var t = this, ed = t.editor, dom = ed.dom, styleProps;
  484. if (ed.settings.paste_enable_default_filters == false) {
  485. return;
  486. }
  487. if (o.wordContent) {
  488. // Remove named anchors or TOC links
  489. each(dom.select('a', o.node), function(a) {
  490. if (!a.href || a.href.indexOf('#_Toc') != -1)
  491. dom.remove(a, 1);
  492. });
  493. if (getParam(ed, "paste_convert_middot_lists")) {
  494. t._convertLists(pl, o);
  495. }
  496. // Process styles
  497. styleProps = getParam(ed, "paste_retain_style_properties"); // retained properties
  498. // Process only if a string was specified and not equal to "all" or "*"
  499. if ((tinymce.is(styleProps, "string")) && (styleProps !== "all") && (styleProps !== "*")) {
  500. styleProps = tinymce.explode(styleProps.replace(/^none$/i, ""));
  501. // Retains some style properties
  502. each(dom.select('*', o.node), function(el) {
  503. var newStyle = {}, npc = 0, i, sp, sv;
  504. // Store a subset of the existing styles
  505. if (styleProps) {
  506. for (i = 0; i < styleProps.length; i++) {
  507. sp = styleProps[i];
  508. sv = dom.getStyle(el, sp);
  509. if (sv) {
  510. newStyle[sp] = sv;
  511. npc++;
  512. }
  513. }
  514. }
  515. // Remove all of the existing styles
  516. dom.setAttrib(el, 'style', '');
  517. if (styleProps && npc > 0)
  518. dom.setStyles(el, newStyle); // Add back the stored subset of styles
  519. else // Remove empty span tags that do not have class attributes
  520. if (el.nodeName == 'SPAN' && !el.className)
  521. dom.remove(el, true);
  522. });
  523. }
  524. }
  525. // Remove all style information or only specifically on WebKit to avoid the style bug on that browser
  526. if (getParam(ed, "paste_remove_styles") || (getParam(ed, "paste_remove_styles_if_webkit") && tinymce.isWebKit)) {
  527. each(dom.select('*[style]', o.node), function(el) {
  528. el.removeAttribute('style');
  529. el.removeAttribute('data-mce-style');
  530. });
  531. } else {
  532. if (tinymce.isWebKit) {
  533. // We need to compress the styles on WebKit since if you paste <img border="0" /> it will become <img border="0" style="... lots of junk ..." />
  534. // Removing the mce_style that contains the real value will force the Serializer engine to compress the styles
  535. each(dom.select('*', o.node), function(el) {
  536. el.removeAttribute('data-mce-style');
  537. });
  538. }
  539. }
  540. },
  541. /**
  542. * Converts the most common bullet and number formats in Office into a real semantic UL/LI list.
  543. */
  544. _convertLists : function(pl, o) {
  545. var dom = pl.editor.dom, listElm, li, lastMargin = -1, margin, levels = [], lastType, html;
  546. // Convert middot lists into real semantic lists
  547. each(dom.select('p', o.node), function(p) {
  548. var sib, val = '', type, html, idx, parents;
  549. // Get text node value at beginning of paragraph
  550. for (sib = p.firstChild; sib && sib.nodeType == 3; sib = sib.nextSibling)
  551. val += sib.nodeValue;
  552. val = p.innerHTML.replace(/<\/?\w+[^>]*>/gi, '').replace(/&nbsp;/g, '\u00a0');
  553. // Detect unordered lists look for bullets
  554. if (/^(__MCE_ITEM__)+[\u2022\u00b7\u00a7\u00d8o\u25CF]\s*\u00a0*/.test(val))
  555. type = 'ul';
  556. // Detect ordered lists 1., a. or ixv.
  557. if (/^__MCE_ITEM__\s*\w+\.\s*\u00a0+/.test(val))
  558. type = 'ol';
  559. // Check if node value matches the list pattern: o&nbsp;&nbsp;
  560. if (type) {
  561. margin = parseFloat(p.style.marginLeft || 0);
  562. if (margin > lastMargin)
  563. levels.push(margin);
  564. if (!listElm || type != lastType) {
  565. listElm = dom.create(type);
  566. dom.insertAfter(listElm, p);
  567. } else {
  568. // Nested list element
  569. if (margin > lastMargin) {
  570. listElm = li.appendChild(dom.create(type));
  571. } else if (margin < lastMargin) {
  572. // Find parent level based on margin value
  573. idx = tinymce.inArray(levels, margin);
  574. parents = dom.getParents(listElm.parentNode, type);
  575. listElm = parents[parents.length - 1 - idx] || listElm;
  576. }
  577. }
  578. // Remove middot or number spans if they exists
  579. each(dom.select('span', p), function(span) {
  580. var html = span.innerHTML.replace(/<\/?\w+[^>]*>/gi, '');
  581. // Remove span with the middot or the number
  582. if (type == 'ul' && /^__MCE_ITEM__[\u2022\u00b7\u00a7\u00d8o\u25CF]/.test(html))
  583. dom.remove(span);
  584. else if (/^__MCE_ITEM__[\s\S]*\w+\.(&nbsp;|\u00a0)*\s*/.test(html))
  585. dom.remove(span);
  586. });
  587. html = p.innerHTML;
  588. // Remove middot/list items
  589. if (type == 'ul')
  590. html = p.innerHTML.replace(/__MCE_ITEM__/g, '').replace(/^[\u2022\u00b7\u00a7\u00d8o\u25CF]\s*(&nbsp;|\u00a0)+\s*/, '');
  591. else
  592. html = p.innerHTML.replace(/__MCE_ITEM__/g, '').replace(/^\s*\w+\.(&nbsp;|\u00a0)+\s*/, '');
  593. // Create li and add paragraph data into the new li
  594. li = listElm.appendChild(dom.create('li', 0, html));
  595. dom.remove(p);
  596. lastMargin = margin;
  597. lastType = type;
  598. } else
  599. listElm = lastMargin = 0; // End list element
  600. });
  601. // Remove any left over makers
  602. html = o.node.innerHTML;
  603. if (html.indexOf('__MCE_ITEM__') != -1)
  604. o.node.innerHTML = html.replace(/__MCE_ITEM__/g, '');
  605. },
  606. /**
  607. * Inserts the specified contents at the caret position.
  608. */
  609. _insert : function(h, skip_undo) {
  610. var ed = this.editor, r = ed.selection.getRng();
  611. // First delete the contents seems to work better on WebKit when the selection spans multiple list items or multiple table cells.
  612. if (!ed.selection.isCollapsed() && r.startContainer != r.endContainer)
  613. ed.getDoc().execCommand('Delete', false, null);
  614. ed.execCommand('mceInsertContent', false, h, {skip_undo : skip_undo});
  615. },
  616. /**
  617. * Instead of the old plain text method which tried to re-create a paste operation, the
  618. * new approach adds a plain text mode toggle switch that changes the behavior of paste.
  619. * This function is passed the same input that the regular paste plugin produces.
  620. * It performs additional scrubbing and produces (and inserts) the plain text.
  621. * This approach leverages all of the great existing functionality in the paste
  622. * plugin, and requires minimal changes to add the new functionality.
  623. * Speednet - June 2009
  624. */
  625. _insertPlainText : function(ed, dom, h) {
  626. var i, len, pos, rpos, node, breakElms, before, after,
  627. w = ed.getWin(),
  628. d = ed.getDoc(),
  629. sel = ed.selection,
  630. is = tinymce.is,
  631. inArray = tinymce.inArray,
  632. linebr = getParam(ed, "paste_text_linebreaktype"),
  633. rl = getParam(ed, "paste_text_replacements");
  634. function process(items) {
  635. each(items, function(v) {
  636. if (v.constructor == RegExp)
  637. h = h.replace(v, "");
  638. else
  639. h = h.replace(v[0], v[1]);
  640. });
  641. };
  642. if ((typeof(h) === "string") && (h.length > 0)) {
  643. // If HTML content with line-breaking tags, then remove all cr/lf chars because only tags will break a line
  644. if (/<(?:p|br|h[1-6]|ul|ol|dl|table|t[rdh]|div|blockquote|fieldset|pre|address|center)[^>]*>/i.test(h)) {
  645. process([
  646. /[\n\r]+/g
  647. ]);
  648. } else {
  649. // Otherwise just get rid of carriage returns (only need linefeeds)
  650. process([
  651. /\r+/g
  652. ]);
  653. }
  654. process([
  655. [/<\/(?:p|h[1-6]|ul|ol|dl|table|div|blockquote|fieldset|pre|address|center)>/gi, "\n\n"], // Block tags get a blank line after them
  656. [/<br[^>]*>|<\/tr>/gi, "\n"], // Single linebreak for <br /> tags and table rows
  657. [/<\/t[dh]>\s*<t[dh][^>]*>/gi, "\t"], // Table cells get tabs betweem them
  658. /<[a-z!\/?][^>]*>/gi, // Delete all remaining tags
  659. [/&nbsp;/gi, " "], // Convert non-break spaces to regular spaces (remember, *plain text*)
  660. [/(?:(?!\n)\s)*(\n+)(?:(?!\n)\s)*/gi, "$1"], // Cool little RegExp deletes whitespace around linebreak chars.
  661. [/\n{3,}/g, "\n\n"], // Max. 2 consecutive linebreaks
  662. /^\s+|\s+$/g // Trim the front & back
  663. ]);
  664. h = dom.decode(tinymce.html.Entities.encodeRaw(h));
  665. // Delete any highlighted text before pasting
  666. if (!sel.isCollapsed()) {
  667. d.execCommand("Delete", false, null);
  668. }
  669. // Perform default or custom replacements
  670. if (is(rl, "array") || (is(rl, "array"))) {
  671. process(rl);
  672. }
  673. else if (is(rl, "string")) {
  674. process(new RegExp(rl, "gi"));
  675. }
  676. // Treat paragraphs as specified in the config
  677. if (linebr == "none") {
  678. process([
  679. [/\n+/g, " "]
  680. ]);
  681. }
  682. else if (linebr == "br") {
  683. process([
  684. [/\n/g, "<br />"]
  685. ]);
  686. }
  687. else {
  688. process([
  689. /^\s+|\s+$/g,
  690. [/\n\n/g, "</p><p>"],
  691. [/\n/g, "<br />"]
  692. ]);
  693. }
  694. // This next piece of code handles the situation where we're pasting more than one paragraph of plain
  695. // text, and we are pasting the content into the middle of a block node in the editor. The block
  696. // node gets split at the selection point into "Para A" and "Para B" (for the purposes of explaining).
  697. // The first paragraph of the pasted text is appended to "Para A", and the last paragraph of the
  698. // pasted text is prepended to "Para B". Any other paragraphs of pasted text are placed between
  699. // "Para A" and "Para B". This code solves a host of problems with the original plain text plugin and
  700. // now handles styles correctly. (Pasting plain text into a styled paragraph is supposed to make the
  701. // plain text take the same style as the existing paragraph.)
  702. if ((pos = h.indexOf("</p><p>")) != -1) {
  703. rpos = h.lastIndexOf("</p><p>");
  704. node = sel.getNode();
  705. breakElms = []; // Get list of elements to break
  706. do {
  707. if (node.nodeType == 1) {
  708. // Don't break tables and break at body
  709. if (node.nodeName == "TD" || node.nodeName == "BODY") {
  710. break;
  711. }
  712. breakElms[breakElms.length] = node;
  713. }
  714. } while (node = node.parentNode);
  715. // Are we in the middle of a block node?
  716. if (breakElms.length > 0) {
  717. before = h.substring(0, pos);
  718. after = "";
  719. for (i=0, len=breakElms.length; i<len; i++) {
  720. before += "</" + breakElms[i].nodeName.toLowerCase() + ">";
  721. after += "<" + breakElms[breakElms.length-i-1].nodeName.toLowerCase() + ">";
  722. }
  723. if (pos == rpos) {
  724. h = before + after + h.substring(pos+7);
  725. }
  726. else {
  727. h = before + h.substring(pos+4, rpos+4) + after + h.substring(rpos+7);
  728. }
  729. }
  730. }
  731. // Insert content at the caret, plus add a marker for repositioning the caret
  732. ed.execCommand("mceInsertRawHTML", false, h + '<span id="_plain_text_marker">&nbsp;</span>');
  733. // Reposition the caret to the marker, which was placed immediately after the inserted content.
  734. // Needs to be done asynchronously (in window.setTimeout) or else it doesn't work in all browsers.
  735. // The second part of the code scrolls the content up if the caret is positioned off-screen.
  736. // This is only necessary for WebKit browsers, but it doesn't hurt to use for all.
  737. window.setTimeout(function() {
  738. var marker = dom.get('_plain_text_marker'),
  739. elm, vp, y, elmHeight;
  740. sel.select(marker, false);
  741. d.execCommand("Delete", false, null);
  742. marker = null;
  743. // Get element, position and height
  744. elm = sel.getStart();
  745. vp = dom.getViewPort(w);
  746. y = dom.getPos(elm).y;
  747. elmHeight = elm.clientHeight;
  748. // Is element within viewport if not then scroll it into view
  749. if ((y < vp.y) || (y + elmHeight > vp.y + vp.h)) {
  750. d.body.scrollTop = y < vp.y ? y : y - vp.h + 25;
  751. }
  752. }, 0);
  753. }
  754. },
  755. /**
  756. * This method will open the old style paste dialogs. Some users might want the old behavior but still use the new cleanup engine.
  757. */
  758. _legacySupport : function() {
  759. var t = this, ed = t.editor;
  760. // Register command(s) for backwards compatibility
  761. ed.addCommand("mcePasteWord", function() {
  762. ed.windowManager.open({
  763. file: t.url + "/pasteword.htm",
  764. width: parseInt(getParam(ed, "paste_dialog_width")),
  765. height: parseInt(getParam(ed, "paste_dialog_height")),
  766. inline: 1
  767. });
  768. });
  769. if (getParam(ed, "paste_text_use_dialog")) {
  770. ed.addCommand("mcePasteText", function() {
  771. ed.windowManager.open({
  772. file : t.url + "/pastetext.htm",
  773. width: parseInt(getParam(ed, "paste_dialog_width")),
  774. height: parseInt(getParam(ed, "paste_dialog_height")),
  775. inline : 1
  776. });
  777. });
  778. }
  779. // Register button for backwards compatibility
  780. ed.addButton("pasteword", {title : "paste.paste_word_desc", cmd : "mcePasteWord"});
  781. }
  782. });
  783. // Register plugin
  784. tinymce.PluginManager.add("paste", tinymce.plugins.PastePlugin);
  785. })();