Map tab key to indent and shift+tab to outdent in TinyMCE (in Wicket)

Today’s post is about changing the behavior of the TinyMCE implementation in the wicket stuff library. In this library TinyMCE functionality can be implemented by just adding the TinyMCEBehaviour to the wicket component TextArea and calling the behavior’s constructor with an instance of TinyMCESettings, where you can set all kind of parameters.

Generally very content with our implementation, our customer wanted a way to define pre-formatted text blocks to use in documents at a later point. For ease of use, pressing the tab key should indent the text and shift+tab should revert the effect = outdent the current line. Although the advanced edit settings showed indent/outdent buttons we also wanted it to work when the buttons aren’t shown, in forms where space is precious for example. After some google searches I found this post (cached google version), about how to execute TinyMCE functionality in javascript and this stackoverflow answer, about where to put this info.

The solution, which works pretty well for us, was to insert a method in our TinyMCE class, which just adds the following function to the settings instance.

public static TinyMCESettings addTabFunctionality(TinyMCESettings settings) {
settings.addCustomSetting("setup : function(ed) { " +
"ed.onKeyDown.add(function(ed, e) { " +
"if(e.keyCode == 9) {" +
"if(e.shiftKey) {" +
"ed.execCommand('Outdent');" +
"}else{" +
"ed.execCommand('Indent');" +
"}" +
"e.preventDefault();" +
"return false;" +
"}" +
"});" +
"}");
return settings;
}

The addCustomSetting() method adds code to the init() function created by the TinyMCE addon and in the javascript code we listen for keydown in the textarea. If keycode equals ‘9’ (tab) we check if shift is also pressed, if so an outdent action is performed using execCommand(‘Outdent’), if not, an indent is executed. By calling preventDefault() afterwards, the default action of the tab key is prevented – in our case it just was a 4 space-tab, which wasn’t written to the created html code. Calling the TinyMCE indent and outdent commands, padding is added to the affected line’s <p> tag (30px per tab) so the format can be saved to a database, without loosing the tabbed white-spaces.

Hope this helps someone, have a nice weekend! Until next time, feedback’s very welcome!

Leave a Reply

Your email address will not be published. Required fields are marked *