Preventing tinyMCE 4 from inserting <br /> within <code> blocks.

Problem

I was trying to hook in TinyMCE 4 as a editor that allows me to specify code blocks. However, in visual editing mode, <code> blocks ended up having embedded <br /> tags that displayed when rendered.

There is an old plugin, Pre Element Fix, that may have done what I wanted it to do, but it didn't appear to be developed beyond TinyMCE 2.

Solution

It took a bit of work to handle spanning multiline with a match (/[^]*/) and hook into the editor setup (setup: function(editor) {...}).

Complete with initialization code, the following is what I came up with:

fixNewLines = function(content)
{
  var codeBlocks=content.match(/<code.*?>[^]*?<\/code>/m)

  if(codeBlocks == null) return content;
  for(var index=0; index < codeBlocks.length; index++) {
    content = content.replace(codeBlocks[index], codeBlocks[index].replace(/<br\s*\/?>/mgi, "\n"));
  }
  return content;
}


tinymce.init({
    selector: "textarea",
    theme: "modern",
    entity_encoding : "raw",
    plugins: [
        "advlist autolink lists link image charmap print preview hr anchor pagebreak",
        "searchreplace wordcount visualblocks visualchars code fullscreen",
        "insertdatetime media nonbreaking save table contextmenu directionality",
        "emoticons template paste textcolor" ],
    toolbar1: "insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image",
    toolbar2: "print preview media | forecolor backcolor emoticons",
    image_advtab: true,
    templates: [
        {title: 'Test template 1', content: 'Test 1'},
        {title: 'Test template 2', content: 'Test 2'}
    ],
    setup: function(editor) {
      editor.on('BeforeSetContent', function(e) {
        e.content = fixNewLines(e.content);
      });
      editor.on('SaveContent', function(e) {
        e.content = fixNewLines(e.content);
      });
    }

});

The key parts are the fixNewLines function, the setup hooks, the code plugin, and (possibly) the entity_encoding:"raw".

When you view the source code, you will still see break tags with the code sections. However, these will be cleared out on save.

Useful References That I Found

Syntax Highlighting Javascript

http://craig.is/making/rainbows

TinyMCE event research

Hook into onExecCommand event with tinymce 4

api:class.tinymce.Editor events

BeforeSetContent event.

SaveContent event.

tinymce.init({
    ...
    setup:function(editor){
        editor.on('BeforeSetContent',function(e){
            console.log('BeforeSetContent event', e);
        });
    }
});