Simple Code <code> CKEditor for Drupal

Mon, 19/11/2012 - 00:02 -- Remiguel

<code> tag hidden in CKEditor

When we want to use the tag <code> in Drupal in combination with the module CKEditor, the tagged text doesn't show up in the CKEditor window. The reason is, because the code is disable by default, in the ckeditor.config.js file.

To able the code, we have to add a double slash // in front of the following line as shown below:

// config.protectedSource.push(/<code>[\s\S]*?<\/code>/gi);

Additionally and optionally we can format the tag <code> in our theme style css. For example:

code {
font-family: monospace;
font-style:italic;
color: #AAAAAA;
}

Shortcut <code>

I was looking for a shortcut in the toolbox, to format my code lines. We can do so with this plugin ckeditor-syntaxhighlight-1.0.tar.bz2, but it doesn't fit my needs. We can also setup the "Style" dropdown, in /admin/config/content/ckeditor/edit/[perfil] => "show the editor appearance", to get available the "computer Code" style, but it is not really fast to get the text formatted.

I've wrote a small plugin "Simple Code (scode)" to get this tag shortcut. To build plugin I found documentation here, I've read tutorials here and finally have based my plugin on the code of Nikolay Ulyanitsky.

The plugin contain 2 files: one Java file and one icon (optionally located in a directory), all must be saved in one directory which name have to be the same as the plugin one. Plugins for CKeditor are saved in the folder /sites/all/modules/ckeditor/plugins.

File js code:

/**

* Basic sample plugin inserting <code> into CKEditor editing area.

*/

CKEDITOR.plugins.add( 'scode',

{

init: function( editor )

{

editor.addCommand( 'insertcode',

{

exec : function( editor )

{

var format = {element : "code"};

var style = new CKEDITOR.style(format);

style.apply(editor.document);

}

} );

editor.ui.addButton( 'Button',

{

label: 'Insert Code',

command: 'insertcode',

icon: this.path + 'images/icon.png'

} );

}

} );

This code works great with CKeditor 3.6.3 and Drupal 7. This code could be modified to fit your needs and can be used with whatever tags.

Once the plugin is saved on the server , it has to be enabled in the Drupal preference /admin/config/content/ckeditor/edit/[perfil] => "show the editor appearance"

Up now, you should have a new icon (in the toolbox) to format your text with the tag <code>.