Tuesday, November 23, 2010

CKEditor: Plugin And Toolbar Button For PRE, CODE, H1, H2, H3, H4, H5, H6, DIV, P Style Formatting

Hi all.

This small howto help you to create a plugin for CKEditor 3.4 and add a new toolbar button for p, h1, h2, h3, h4, h5, h6, pre, address and div style formatting.

1. Directory structure:
ckeditor/
    config.js
    plugins/
        button-pre/
            button-pre.png
            plugin.js

2. Create plugin.js:
(function(){
 var a= {
  exec:function(editor){
   var format = {
    element : "pre"
   };
   var style = new CKEDITOR.style(format);
   style.apply(editor.document);
  }
 },

 b="button-pre";
 CKEDITOR.plugins.add(b,{
  init:function(editor){
   editor.addCommand(b,a);
   editor.ui.addButton("button-pre",{
    label:"Button PRE",
    icon: this.path + "button-pre.png",
    command:b
   });
  }
 });
})();

3. Download a button-pre.png: CKEditor PRE plugin button.

4. Register the plugin and add a toolbar button. Modify config.js:
CKEDITOR.editorConfig = function( config )
{
 CKEDITOR.config.toolbar_Basic = [['button-pre', 'Bold', 'Italic', 'Underline' ]];
 config.toolbar = 'Basic';
 config.startupOutlineBlocks = true;
 config.extraPlugins = "button-pre";
};

Result:
CKEditor PRE plugin button sample

P.S. You can change pre with code, h1, h2, h3, h4, h5, h6, address, div and p tags.
P.P.S. This plugin also work with the code tag pretty good.

6 comments:

  1. Thank you Nikolay, your post has been immensely useful. I was asking on Stack Overflow, looking precisely for this piece of functionality. Great job! :)

    ReplyDelete
  2. Thanks for great tutorial. I was Searching this for weeks. You saved me.

    ReplyDelete
  3. Thanks. That CKeditor ships without a basic &lth;ODE&gth; button is a huge oversight, I think.

    I did not even want an editor - I prefer hand coded markup - but FTP-ing and organizing images is a pain... images is the only reason I even tried an editor. *sigh*.

    ReplyDelete
  4. Thannnnksss a lot mann... i have been trying to add a new plugin to the toolbar since the last 3 days... but i knew i was missing something ... coz i just cudnt't make it work in the end...

    after goin thru 4 - 5 tutorials on this topic... i finally found urs... and i made it in 5 mins :)

    You are a savior mann... thanks a lot :)
    Carry on the great work.

    ReplyDelete
  5. Hi,

    Can I also add class to pre tag? and if it's possible can user select the name of it?

    BTW, Thanks a lot :)

    ReplyDelete
  6. Sure you can.
    For example, i defined attributes lang="ruby" for my code tag.

    element : "code",
    attributes : {
    lang: "ruby"
    }

    ReplyDelete