/pigeoncms/Plugins/tiny_mce/plugins/paste/editor_plugin_src.js

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