TinyMCE WYSIWYG BBCode Editor

TinyMCE does have a pretty functional BBCode Editor, but the latest version doesn’t work perfectly out of the box.  Specifically, in the sample on the TinyMCE page, quotes and code styles are not displayed differently and quotes cannot be embedded (i.e. you can’t quote a quote).  Since we want to use this in the forums of NITRC, it was important to us to get embedded quotes working.

The TinyMCE BBCode plugin works by using JavaScript to translate back and forth between HTML and BBCode.  If you don’t care about embedded quotes, getting the sample to work correctly is not that hard.  First, we need to tell BBCode to use “SPAN” tags instead of “P” tags for the quote and code style.  This is done by replacing some options in the call to tinyMCE.init.  Specifically, replace:

theme_advanced_styles : “Code=codeStyle;Quote=quoteStyle”,

with:

style_formats : [
  {title: ‘Code’, inline : ‘span’, classes: “codeStyle”},
  {title: ‘Quote’, inline : ‘span’, classes: “quoteStyle”}
],

Then, to fix issues with newlines in the BBCode, add:

apply_source_formatting : false,

Finally, to make the styles work, add a bbcode.css to the tinyMCE.init() call

content_css : “/tinymce/css/bbcode.css”,

and create a bbcode.css file with a appropriate styles:

p {margin:0; padding: 0;}
span.quoteStyle{  display: block;  background-color: #ffffff;  border: 1px solid #c9d2d8;  margin: 3px 3px 3px 20px;  color: #660002;}
span.codeStyle{  display: block;  background-color: #ffffff;  border: 1px solid #c9d2d8;  margin: 3px 3px 3px 20px;  font-family: Monaco,“Andale Mono”,“Courier New”,Courier,mono;  color: #006600;}

To get embedded quotes working is a bit more of a trick.  Instead of using SPAN for quotes, we want to use BLOCKQUOTE (that way we can easily match ending tags with the quote).  This requires us to use (in tinyMCE.init()):

style_formats : [
  {title: ‘Code’, inline : ‘span’, classes: “codeStyle”},
  {title: ‘Quote’, block : ‘blockquote’}
],

change our bbcode.css:

blockquote {  display: block;  background-color: #ffffff;  border: 1px solid #c9d2d8;  margin: 3px 3px 3px 20px;  color: #660002;}

and modify tinymce/jscripts/tiny_mce/plugins/bbcode/editor_plugin.js (which is done by editing editor_plugin_src.js, and running the result through http://javascriptcompressor.com/ to plut in editor_plugin.js) by replacing (around line 111):

rep(/\[quote.*?\](.*?)\[\/quote\]/gi,”<span class=\“quoteStyle\”>$1</span>&nbsp;”);

with

rep(/\[quote.*?\]/gi,”<blockquote>”);
rep(/\[\/quote\]/gi,”</blockquote>”);

This causes quotes to be translated into blockquotes instead of spans by the bbcode plugin.