Pages

Tuesday, December 7, 2010

TinyMCE: Paste as plain text

I just started using TinyMCE as a WYSIWYG editor for texts in a project and I ran into a problem:

When a user copies some text from an external source such as Open Office into the editor, formatting such as font family, colour, font-size etc. will be preserved even if not intended.

There is a plugin called "paste" that can be configured at the initialization of TinyMCE:

tinyMCE.init({
   ...
   plugins : "paste",
   paste_remove_styles : true,
   paste_retain_style_properties : 'none',
   paste_auto_cleanup_on_paste : true,
   paste_convert_headers_to_strong : false,
   paste_strip_class_attributes : "all",
   paste_remove_spans : true,
   ...
});


But even with all these options set, the text still appears formatted after pasting.

There is also a button called "Paste as plain text"  that does exactly what is intended: no formatting is applied, only the bare naked text is pasted into the editor.
But the user has to click this button before pasting the text, and that's not what I want: I just want text always as plain text.
There should be a way to enable the function on startup...

So I looked in the source code of the plugin and found the flag "pasteAsPlainText" that is set to true when the button gets clicked on. So all we have to do is set this flag after initializing TinyMCE. Fortunately, TinyMCE comes with the callback "oninit" that calls as a named or an anonymous function with the current editor object as argument:

tinyMCE.init({
   ...
   plugins : "paste",
   paste_text_sticky : true,
   oninit: function(ed){
      ed.pasteAsPlainText = true;
   },
   ...
});

You have to add the line "paste_text_sticky : true", because TinyMCE would change the status of "pasteAsPlainText" to false after pasting some text.

Everything's fine now: no more Verdana 16pt in my Arial 12px textarea!
But I got used to the "Paste as plain text" button (called "pastetext" in the button list) so I decided to leave it in my toolbar and show that it is activated on startup, so the user still could deactivate it to paste some formatting intentionally:

tinyMCE.init({
   ...
   theme : "advanced",
   theme_advanced_buttons1 : "bold,italic,pastetext",
   plugins : "paste",
   paste_text_sticky : true,
   oninit: function(ed){
      ed.pasteAsPlainText = true;
      ed.controlManager.setActive("pastetext", true);
   },
   ...
});

So easy!
Hope it helps someone having the same problem!

0 comments:

Post a Comment