PageRenderTime 56ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/BlogEngine/BlogEngine.NET/editors/tiny_mce_3_4_3_1/plugins/paste/editor_plugin_src.js

#
JavaScript | 941 lines | 757 code | 88 blank | 96 comment | 106 complexity | 2caede40468244e2403392c5a2a4d902 MD5 | raw file
Possible License(s): LGPL-2.1, Apache-2.0, BSD-3-Clause
  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 plain text mode
  223. h = '<pre>' + dom.encode(textContent).replace(/\r?\n/g, '<br />') + '</pre>';
  224. }
  225. // Remove the nodes
  226. each(dom.select('div.mcePaste'), function(n) {
  227. dom.remove(n);
  228. });
  229. // Restore the old selection
  230. if (or)
  231. sel.setRng(or);
  232. process({content : h});
  233. // Unblock events ones we got the contents
  234. dom.unbind(ed.getDoc(), 'mousedown', block);
  235. dom.unbind(ed.getDoc(), 'keydown', block);
  236. }, 0);
  237. }
  238. }
  239. // Check if we should use the new auto process method
  240. if (getParam(ed, "paste_auto_cleanup_on_paste")) {
  241. // Is it's Opera or older FF use key handler
  242. if (tinymce.isOpera || /Firefox\/2/.test(navigator.userAgent)) {
  243. ed.onKeyDown.addToTop(function(ed, e) {
  244. if (((tinymce.isMac ? e.metaKey : e.ctrlKey) && e.keyCode == 86) || (e.shiftKey && e.keyCode == 45))
  245. grabContent(e);
  246. });
  247. } else {
  248. // Grab contents on paste event on Gecko and WebKit
  249. ed.onPaste.addToTop(function(ed, e) {
  250. return grabContent(e);
  251. });
  252. }
  253. }
  254. ed.onInit.add(function() {
  255. ed.controlManager.setActive("pastetext", ed.pasteAsPlainText);
  256. // Block all drag/drop events
  257. if (getParam(ed, "paste_block_drop")) {
  258. ed.dom.bind(ed.getBody(), ['dragend', 'dragover', 'draggesture', 'dragdrop', 'drop', 'drag'], function(e) {
  259. e.preventDefault();
  260. e.stopPropagation();
  261. return false;
  262. });
  263. }
  264. });
  265. // Add legacy support
  266. t._legacySupport();
  267. },
  268. getInfo : function() {
  269. return {
  270. longname : 'Paste text/word',
  271. author : 'Moxiecode Systems AB',
  272. authorurl : 'http://tinymce.moxiecode.com',
  273. infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/paste',
  274. version : tinymce.majorVersion + "." + tinymce.minorVersion
  275. };
  276. },
  277. _preProcess : function(pl, o) {
  278. var ed = this.editor,
  279. h = o.content,
  280. grep = tinymce.grep,
  281. explode = tinymce.explode,
  282. trim = tinymce.trim,
  283. len, stripClass;
  284. //console.log('Before preprocess:' + o.content);
  285. function process(items) {
  286. each(items, function(v) {
  287. // Remove or replace
  288. if (v.constructor == RegExp)
  289. h = h.replace(v, '');
  290. else
  291. h = h.replace(v[0], v[1]);
  292. });
  293. }
  294. if (ed.settings.paste_enable_default_filters == false) {
  295. return;
  296. }
  297. // IE9 adds BRs before/after block elements when contents is pasted from word or for example another browser
  298. if (tinymce.isIE && document.documentMode >= 9) {
  299. // IE9 adds BRs before/after block elements when contents is pasted from word or for example another browser
  300. 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']]);
  301. // IE9 also adds an extra BR element for each soft-linefeed and it also adds a BR for each word wrap break
  302. process([
  303. [/<br><br>/g, '<BR><BR>'], // Replace multiple BR elements with uppercase BR to keep them intact
  304. [/<br>/g, ' '], // Replace single br elements with space since they are word wrap BR:s
  305. [/<BR><BR>/g, '<br>'], // Replace back the double brs but into a single BR
  306. ]);
  307. }
  308. // Detect Word content and process it more aggressive
  309. if (/class="?Mso|style="[^"]*\bmso-|w:WordDocument/i.test(h) || o.wordContent) {
  310. o.wordContent = true; // Mark the pasted contents as word specific content
  311. //console.log('Word contents detected.');
  312. // Process away some basic content
  313. process([
  314. /^\s*(&nbsp;)+/gi, // &nbsp; entities at the start of contents
  315. /(&nbsp;|<br[^>]*>)+\s*$/gi // &nbsp; entities at the end of contents
  316. ]);
  317. if (getParam(ed, "paste_convert_headers_to_strong")) {
  318. h = h.replace(/<p [^>]*class="?MsoHeading"?[^>]*>(.*?)<\/p>/gi, "<p><strong>$1</strong></p>");
  319. }
  320. if (getParam(ed, "paste_convert_middot_lists")) {
  321. process([
  322. [/<!--\[if !supportLists\]-->/gi, '$&__MCE_ITEM__'], // Convert supportLists to a list item marker
  323. [/(<span[^>]+(?:mso-list:|:\s*symbol)[^>]+>)/gi, '$1__MCE_ITEM__'], // Convert mso-list and symbol spans to item markers
  324. [/(<p[^>]+(?:MsoListParagraph)[^>]+>)/gi, '$1__MCE_ITEM__'] // Convert mso-list and symbol paragraphs to item markers (FF)
  325. ]);
  326. }
  327. process([
  328. // Word comments like conditional comments etc
  329. /<!--[\s\S]+?-->/gi,
  330. // Remove comments, scripts (e.g., msoShowComment), XML tag, VML content, MS Office namespaced tags, and a few other tags
  331. /<(!|script[^>]*>.*?<\/script(?=[>\s])|\/?(\?xml(:\w+)?|img|meta|link|style|\w:\w+)(?=[\s\/>]))[^>]*>/gi,
  332. // Convert <s> into <strike> for line-though
  333. [/<(\/?)s>/gi, "<$1strike>"],
  334. // Replace nsbp entites to char since it's easier to handle
  335. [/&nbsp;/gi, "\u00a0"]
  336. ]);
  337. // Remove bad attributes, with or without quotes, ensuring that attribute text is really inside a tag.
  338. // 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.
  339. do {
  340. len = h.length;
  341. h = h.replace(/(<[a-z][^>]*\s)(?:id|name|language|type|on\w+|\w+:\w+)=(?:"[^"]*"|\w+)\s?/gi, "$1");
  342. } while (len != h.length);
  343. // Remove all spans if no styles is to be retained
  344. if (getParam(ed, "paste_retain_style_properties").replace(/^none$/i, "").length == 0) {
  345. h = h.replace(/<\/?span[^>]*>/gi, "");
  346. } else {
  347. // We're keeping styles, so at least clean them up.
  348. // CSS Reference: http://msdn.microsoft.com/en-us/library/aa155477.aspx
  349. process([
  350. // Convert <span style="mso-spacerun:yes">___</span> to string of alternating breaking/non-breaking spaces of same length
  351. [/<span\s+style\s*=\s*"\s*mso-spacerun\s*:\s*yes\s*;?\s*"\s*>([\s\u00a0]*)<\/span>/gi,
  352. function(str, spaces) {
  353. return (spaces.length > 0)? spaces.replace(/./, " ").slice(Math.floor(spaces.length/2)).split("").join("\u00a0") : "";
  354. }
  355. ],
  356. // Examine all styles: delete junk, transform some, and keep the rest
  357. [/(<[a-z][^>]*)\sstyle="([^"]*)"/gi,
  358. function(str, tag, style) {
  359. var n = [],
  360. i = 0,
  361. s = explode(trim(style).replace(/&quot;/gi, "'"), ";");
  362. // Examine each style definition within the tag's style attribute
  363. each(s, function(v) {
  364. var name, value,
  365. parts = explode(v, ":");
  366. function ensureUnits(v) {
  367. return v + ((v !== "0") && (/\d$/.test(v)))? "px" : "";
  368. }
  369. if (parts.length == 2) {
  370. name = parts[0].toLowerCase();
  371. value = parts[1].toLowerCase();
  372. // Translate certain MS Office styles into their CSS equivalents
  373. switch (name) {
  374. case "mso-padding-alt":
  375. case "mso-padding-top-alt":
  376. case "mso-padding-right-alt":
  377. case "mso-padding-bottom-alt":
  378. case "mso-padding-left-alt":
  379. case "mso-margin-alt":
  380. case "mso-margin-top-alt":
  381. case "mso-margin-right-alt":
  382. case "mso-margin-bottom-alt":
  383. case "mso-margin-left-alt":
  384. case "mso-table-layout-alt":
  385. case "mso-height":
  386. case "mso-width":
  387. case "mso-vertical-align-alt":
  388. n[i++] = name.replace(/^mso-|-alt$/g, "") + ":" + ensureUnits(value);
  389. return;
  390. case "horiz-align":
  391. n[i++] = "text-align:" + value;
  392. return;
  393. case "vert-align":
  394. n[i++] = "vertical-align:" + value;
  395. return;
  396. case "font-color":
  397. case "mso-foreground":
  398. n[i++] = "color:" + value;
  399. return;
  400. case "mso-background":
  401. case "mso-highlight":
  402. n[i++] = "background:" + value;
  403. return;
  404. case "mso-default-height":
  405. n[i++] = "min-height:" + ensureUnits(value);
  406. return;
  407. case "mso-default-width":
  408. n[i++] = "min-width:" + ensureUnits(value);
  409. return;
  410. case "mso-padding-between-alt":
  411. n[i++] = "border-collapse:separate;border-spacing:" + ensureUnits(value);
  412. return;
  413. case "text-line-through":
  414. if ((value == "single") || (value == "double")) {
  415. n[i++] = "text-decoration:line-through";
  416. }
  417. return;
  418. case "mso-zero-height":
  419. if (value == "yes") {
  420. n[i++] = "display:none";
  421. }
  422. return;
  423. }
  424. // Eliminate all MS Office style definitions that have no CSS equivalent by examining the first characters in the name
  425. 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)) {
  426. return;
  427. }
  428. // If it reached this point, it must be a valid CSS style
  429. n[i++] = name + ":" + parts[1]; // Lower-case name, but keep value case
  430. }
  431. });
  432. // If style attribute contained any valid styles the re-write it; otherwise delete style attribute.
  433. if (i > 0) {
  434. return tag + ' style="' + n.join(';') + '"';
  435. } else {
  436. return tag;
  437. }
  438. }
  439. ]
  440. ]);
  441. }
  442. }
  443. // Replace headers with <strong>
  444. if (getParam(ed, "paste_convert_headers_to_strong")) {
  445. process([
  446. [/<h[1-6][^>]*>/gi, "<p><strong>"],
  447. [/<\/h[1-6][^>]*>/gi, "</strong></p>"]
  448. ]);
  449. }
  450. process([
  451. // Copy paste from Java like Open Office will produce this junk on FF
  452. [/Version:[\d.]+\nStartHTML:\d+\nEndHTML:\d+\nStartFragment:\d+\nEndFragment:\d+/gi, '']
  453. ]);
  454. // Class attribute options are: leave all as-is ("none"), remove all ("all"), or remove only those starting with mso ("mso").
  455. // Note:- paste_strip_class_attributes: "none", verify_css_classes: true is also a good variation.
  456. stripClass = getParam(ed, "paste_strip_class_attributes");
  457. if (stripClass !== "none") {
  458. function removeClasses(match, g1) {
  459. if (stripClass === "all")
  460. return '';
  461. var cls = grep(explode(g1.replace(/^(["'])(.*)\1$/, "$2"), " "),
  462. function(v) {
  463. return (/^(?!mso)/i.test(v));
  464. }
  465. );
  466. return cls.length ? ' class="' + cls.join(" ") + '"' : '';
  467. };
  468. h = h.replace(/ class="([^"]+)"/gi, removeClasses);
  469. h = h.replace(/ class=([\-\w]+)/gi, removeClasses);
  470. }
  471. // Remove spans option
  472. if (getParam(ed, "paste_remove_spans")) {
  473. h = h.replace(/<\/?span[^>]*>/gi, "");
  474. }
  475. //console.log('After preprocess:' + h);
  476. o.content = h;
  477. },
  478. /**
  479. * Various post process items.
  480. */
  481. _postProcess : function(pl, o) {
  482. var t = this, ed = t.editor, dom = ed.dom, styleProps;
  483. if (ed.settings.paste_enable_default_filters == false) {
  484. return;
  485. }
  486. if (o.wordContent) {
  487. // Remove named anchors or TOC links
  488. each(dom.select('a', o.node), function(a) {
  489. if (!a.href || a.href.indexOf('#_Toc') != -1)
  490. dom.remove(a, 1);
  491. });
  492. if (getParam(ed, "paste_convert_middot_lists")) {
  493. t._convertLists(pl, o);
  494. }
  495. // Process styles
  496. styleProps = getParam(ed, "paste_retain_style_properties"); // retained properties
  497. // Process only if a string was specified and not equal to "all" or "*"
  498. if ((tinymce.is(styleProps, "string")) && (styleProps !== "all") && (styleProps !== "*")) {
  499. styleProps = tinymce.explode(styleProps.replace(/^none$/i, ""));
  500. // Retains some style properties
  501. each(dom.select('*', o.node), function(el) {
  502. var newStyle = {}, npc = 0, i, sp, sv;
  503. // Store a subset of the existing styles
  504. if (styleProps) {
  505. for (i = 0; i < styleProps.length; i++) {
  506. sp = styleProps[i];
  507. sv = dom.getStyle(el, sp);
  508. if (sv) {
  509. newStyle[sp] = sv;
  510. npc++;
  511. }
  512. }
  513. }
  514. // Remove all of the existing styles
  515. dom.setAttrib(el, 'style', '');
  516. if (styleProps && npc > 0)
  517. dom.setStyles(el, newStyle); // Add back the stored subset of styles
  518. else // Remove empty span tags that do not have class attributes
  519. if (el.nodeName == 'SPAN' && !el.className)
  520. dom.remove(el, true);
  521. });
  522. }
  523. }
  524. // Remove all style information or only specifically on WebKit to avoid the style bug on that browser
  525. if (getParam(ed, "paste_remove_styles") || (getParam(ed, "paste_remove_styles_if_webkit") && tinymce.isWebKit)) {
  526. each(dom.select('*[style]', o.node), function(el) {
  527. el.removeAttribute('style');
  528. el.removeAttribute('data-mce-style');
  529. });
  530. } else {
  531. if (tinymce.isWebKit) {
  532. // 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 ..." />
  533. // Removing the mce_style that contains the real value will force the Serializer engine to compress the styles
  534. each(dom.select('*', o.node), function(el) {
  535. el.removeAttribute('data-mce-style');
  536. });
  537. }
  538. }
  539. },
  540. /**
  541. * Converts the most common bullet and number formats in Office into a real semantic UL/LI list.
  542. */
  543. _convertLists : function(pl, o) {
  544. var dom = pl.editor.dom, listElm, li, lastMargin = -1, margin, levels = [], lastType, html;
  545. // Convert middot lists into real semantic lists
  546. each(dom.select('p', o.node), function(p) {
  547. var sib, val = '', type, html, idx, parents;
  548. // Get text node value at beginning of paragraph
  549. for (sib = p.firstChild; sib && sib.nodeType == 3; sib = sib.nextSibling)
  550. val += sib.nodeValue;
  551. val = p.innerHTML.replace(/<\/?\w+[^>]*>/gi, '').replace(/&nbsp;/g, '\u00a0');
  552. // Detect unordered lists look for bullets
  553. if (/^(__MCE_ITEM__)+[\u2022\u00b7\u00a7\u00d8o\u25CF]\s*\u00a0*/.test(val))
  554. type = 'ul';
  555. // Detect ordered lists 1., a. or ixv.
  556. if (/^__MCE_ITEM__\s*\w+\.\s*\u00a0+/.test(val))
  557. type = 'ol';
  558. // Check if node value matches the list pattern: o&nbsp;&nbsp;
  559. if (type) {
  560. margin = parseFloat(p.style.marginLeft || 0);
  561. if (margin > lastMargin)
  562. levels.push(margin);
  563. if (!listElm || type != lastType) {
  564. listElm = dom.create(type);
  565. dom.insertAfter(listElm, p);
  566. } else {
  567. // Nested list element
  568. if (margin > lastMargin) {
  569. listElm = li.appendChild(dom.create(type));
  570. } else if (margin < lastMargin) {
  571. // Find parent level based on margin value
  572. idx = tinymce.inArray(levels, margin);
  573. parents = dom.getParents(listElm.parentNode, type);
  574. listElm = parents[parents.length - 1 - idx] || listElm;
  575. }
  576. }
  577. // Remove middot or number spans if they exists
  578. each(dom.select('span', p), function(span) {
  579. var html = span.innerHTML.replace(/<\/?\w+[^>]*>/gi, '');
  580. // Remove span with the middot or the number
  581. if (type == 'ul' && /^__MCE_ITEM__[\u2022\u00b7\u00a7\u00d8o\u25CF]/.test(html))
  582. dom.remove(span);
  583. else if (/^__MCE_ITEM__[\s\S]*\w+\.(&nbsp;|\u00a0)*\s*/.test(html))
  584. dom.remove(span);
  585. });
  586. html = p.innerHTML;
  587. // Remove middot/list items
  588. if (type == 'ul')
  589. html = p.innerHTML.replace(/__MCE_ITEM__/g, '').replace(/^[\u2022\u00b7\u00a7\u00d8o\u25CF]\s*(&nbsp;|\u00a0)+\s*/, '');
  590. else
  591. html = p.innerHTML.replace(/__MCE_ITEM__/g, '').replace(/^\s*\w+\.(&nbsp;|\u00a0)+\s*/, '');
  592. // Create li and add paragraph data into the new li
  593. li = listElm.appendChild(dom.create('li', 0, html));
  594. dom.remove(p);
  595. lastMargin = margin;
  596. lastType = type;
  597. } else
  598. listElm = lastMargin = 0; // End list element
  599. });
  600. // Remove any left over makers
  601. html = o.node.innerHTML;
  602. if (html.indexOf('__MCE_ITEM__') != -1)
  603. o.node.innerHTML = html.replace(/__MCE_ITEM__/g, '');
  604. },
  605. /**
  606. * Inserts the specified contents at the caret position.
  607. */
  608. _insert : function(h, skip_undo) {
  609. var ed = this.editor, r = ed.selection.getRng();
  610. // First delete the contents seems to work better on WebKit when the selection spans multiple list items or multiple table cells.
  611. if (!ed.selection.isCollapsed() && r.startContainer != r.endContainer)
  612. ed.getDoc().execCommand('Delete', false, null);
  613. ed.execCommand('mceInsertContent', false, h, {skip_undo : skip_undo});
  614. },
  615. /**
  616. * Instead of the old plain text method which tried to re-create a paste operation, the
  617. * new approach adds a plain text mode toggle switch that changes the behavior of paste.
  618. * This function is passed the same input that the regular paste plugin produces.
  619. * It performs additional scrubbing and produces (and inserts) the plain text.
  620. * This approach leverages all of the great existing functionality in the paste
  621. * plugin, and requires minimal changes to add the new functionality.
  622. * Speednet - June 2009
  623. */
  624. _insertPlainText : function(ed, dom, h) {
  625. var i, len, pos, rpos, node, breakElms, before, after,
  626. w = ed.getWin(),
  627. d = ed.getDoc(),
  628. sel = ed.selection,
  629. is = tinymce.is,
  630. inArray = tinymce.inArray,
  631. linebr = getParam(ed, "paste_text_linebreaktype"),
  632. rl = getParam(ed, "paste_text_replacements");
  633. function process(items) {
  634. each(items, function(v) {
  635. if (v.constructor == RegExp)
  636. h = h.replace(v, "");
  637. else
  638. h = h.replace(v[0], v[1]);
  639. });
  640. };
  641. if ((typeof(h) === "string") && (h.length > 0)) {
  642. // If HTML content with line-breaking tags, then remove all cr/lf chars because only tags will break a line
  643. if (/<(?:p|br|h[1-6]|ul|ol|dl|table|t[rdh]|div|blockquote|fieldset|pre|address|center)[^>]*>/i.test(h)) {
  644. process([
  645. /[\n\r]+/g
  646. ]);
  647. } else {
  648. // Otherwise just get rid of carriage returns (only need linefeeds)
  649. process([
  650. /\r+/g
  651. ]);
  652. }
  653. process([
  654. [/<\/(?: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
  655. [/<br[^>]*>|<\/tr>/gi, "\n"], // Single linebreak for <br /> tags and table rows
  656. [/<\/t[dh]>\s*<t[dh][^>]*>/gi, "\t"], // Table cells get tabs betweem them
  657. /<[a-z!\/?][^>]*>/gi, // Delete all remaining tags
  658. [/&nbsp;/gi, " "], // Convert non-break spaces to regular spaces (remember, *plain text*)
  659. [/(?:(?!\n)\s)*(\n+)(?:(?!\n)\s)*/gi, "$1"], // Cool little RegExp deletes whitespace around linebreak chars.
  660. [/\n{3,}/g, "\n\n"], // Max. 2 consecutive linebreaks
  661. /^\s+|\s+$/g // Trim the front & back
  662. ]);
  663. h = dom.decode(tinymce.html.Entities.encodeRaw(h));
  664. // Delete any highlighted text before pasting
  665. if (!sel.isCollapsed()) {
  666. d.execCommand("Delete", false, null);
  667. }
  668. // Perform default or custom replacements
  669. if (is(rl, "array") || (is(rl, "array"))) {
  670. process(rl);
  671. }
  672. else if (is(rl, "string")) {
  673. process(new RegExp(rl, "gi"));
  674. }
  675. // Treat paragraphs as specified in the config
  676. if (linebr == "none") {
  677. process([
  678. [/\n+/g, " "]
  679. ]);
  680. }
  681. else if (linebr == "br") {
  682. process([
  683. [/\n/g, "<br />"]
  684. ]);
  685. }
  686. else {
  687. process([
  688. /^\s+|\s+$/g,
  689. [/\n\n/g, "</p><p>"],
  690. [/\n/g, "<br />"]
  691. ]);
  692. }
  693. // This next piece of code handles the situation where we're pasting more than one paragraph of plain
  694. // text, and we are pasting the content into the middle of a block node in the editor. The block
  695. // node gets split at the selection point into "Para A" and "Para B" (for the purposes of explaining).
  696. // The first paragraph of the pasted text is appended to "Para A", and the last paragraph of the
  697. // pasted text is prepended to "Para B". Any other paragraphs of pasted text are placed between
  698. // "Para A" and "Para B". This code solves a host of problems with the original plain text plugin and
  699. // now handles styles correctly. (Pasting plain text into a styled paragraph is supposed to make the
  700. // plain text take the same style as the existing paragraph.)
  701. if ((pos = h.indexOf("</p><p>")) != -1) {
  702. rpos = h.lastIndexOf("</p><p>");
  703. node = sel.getNode();
  704. breakElms = []; // Get list of elements to break
  705. do {
  706. if (node.nodeType == 1) {
  707. // Don't break tables and break at body
  708. if (node.nodeName == "TD" || node.nodeName == "BODY") {
  709. break;
  710. }
  711. breakElms[breakElms.length] = node;
  712. }
  713. } while (node = node.parentNode);
  714. // Are we in the middle of a block node?
  715. if (breakElms.length > 0) {
  716. before = h.substring(0, pos);
  717. after = "";
  718. for (i=0, len=breakElms.length; i<len; i++) {
  719. before += "</" + breakElms[i].nodeName.toLowerCase() + ">";
  720. after += "<" + breakElms[breakElms.length-i-1].nodeName.toLowerCase() + ">";
  721. }
  722. if (pos == rpos) {
  723. h = before + after + h.substring(pos+7);
  724. }
  725. else {
  726. h = before + h.substring(pos+4, rpos+4) + after + h.substring(rpos+7);
  727. }
  728. }
  729. }
  730. // Insert content at the caret, plus add a marker for repositioning the caret
  731. ed.execCommand("mceInsertRawHTML", false, h + '<span id="_plain_text_marker">&nbsp;</span>');
  732. // Reposition the caret to the marker, which was placed immediately after the inserted content.
  733. // Needs to be done asynchronously (in window.setTimeout) or else it doesn't work in all browsers.
  734. // The second part of the code scrolls the content up if the caret is positioned off-screen.
  735. // This is only necessary for WebKit browsers, but it doesn't hurt to use for all.
  736. window.setTimeout(function() {
  737. var marker = dom.get('_plain_text_marker'),
  738. elm, vp, y, elmHeight;
  739. sel.select(marker, false);
  740. d.execCommand("Delete", false, null);
  741. marker = null;
  742. // Get element, position and height
  743. elm = sel.getStart();
  744. vp = dom.getViewPort(w);
  745. y = dom.getPos(elm).y;
  746. elmHeight = elm.clientHeight;
  747. // Is element within viewport if not then scroll it into view
  748. if ((y < vp.y) || (y + elmHeight > vp.y + vp.h)) {
  749. d.body.scrollTop = y < vp.y ? y : y - vp.h + 25;
  750. }
  751. }, 0);
  752. }
  753. },
  754. /**
  755. * This method will open the old style paste dialogs. Some users might want the old behavior but still use the new cleanup engine.
  756. */
  757. _legacySupport : function() {
  758. var t = this, ed = t.editor;
  759. // Register command(s) for backwards compatibility
  760. ed.addCommand("mcePasteWord", function() {
  761. ed.windowManager.open({
  762. file: t.url + "/pasteword.htm",
  763. width: parseInt(getParam(ed, "paste_dialog_width")),
  764. height: parseInt(getParam(ed, "paste_dialog_height")),
  765. inline: 1
  766. });
  767. });
  768. if (getParam(ed, "paste_text_use_dialog")) {
  769. ed.addCommand("mcePasteText", function() {
  770. ed.windowManager.open({
  771. file : t.url + "/pastetext.htm",
  772. width: parseInt(getParam(ed, "paste_dialog_width")),
  773. height: parseInt(getParam(ed, "paste_dialog_height")),
  774. inline : 1
  775. });
  776. });
  777. }
  778. // Register button for backwards compatibility
  779. ed.addButton("pasteword", {title : "paste.paste_word_desc", cmd : "mcePasteWord"});
  780. }
  781. });
  782. // Register plugin
  783. tinymce.PluginManager.add("paste", tinymce.plugins.PastePlugin);
  784. })();