How to include a code sample command in the TinyMCE Rich Text Editor Toolbar
With technology-related blog posts it is always useful to have a way to insert code sample and give it a nice highlighting on the front-end. In this post I will explain how I added a code sample toolbar option to the TinyMCE Rich Text Editor in Umbraco and display it with formatting on the website.
The real power of TinyMCE is in the plugins. Plugins can be used to extend default functionality or add new functionality. Documentation about using plugins in TinyMCE can be found here. The complete list of TinyMCE plugins can be found here.
The tinymceConfig.config file in the config folder controls the configuration of TinyMCE Rich Text Editor in Umbraco. In order to add the code sample toolbar to the Rich Text Editor in Umbraco, the first thing we need to do is to add the code sample command to the list of commands.
<command alias="codesample" name="Code Sample" mode="Insert" />
The alias is a unique alias for the command within Umbraco. The name defines the name that appears for the command in the Toolbar configuration options for the Rich Text Editor datatype. The mode determines the "quick menu" in which the command appears in the "distraction free" mode for the Rich Text Editor.
The next thing to do is to configure the codesample plugin. The plugin ships with TinyMCE in Umbraco so no additional references apart from configuring it in the config file are required.
Finally, we need to add code[*] to the validElements. Recycle the app pool and that is the backoffice part complete. There should be a new toolbar option available.
I can insert code samples by clicking the toolbar option. A default list of languages is available out of the box.
To display the code with highlighting on the website, we need the Prism library. This library is used by default to embed the code samples within the Rich Text Editor. Your templates will need a reference to prism.js and prism.css which can be downloaded from the website. But what I like about the download is that I can tailor it according to the languages as well as the plugins like Copy to Clipboard. Thats it! I have code samples displaying well on my website.
I also tailored the list of languages in the Insert/Edit Code Sample dialog in the backoffice. To do this, you need to add a custom config to the customConfig section. Add the config key and specify the list you need as shown below to override the default list.