Samuli Natri
Aug. 31, 2016
Updated: Sep. 28, 2016
By Samuli NatriAug. 31, 2016
(Updated: Sep. 28, 2016)

Drupal 8 Tutorial #44 : CKEditor CodeSnippet Module

With CKEditor CodeSnippet module you can insert code snippets with syntax highlighting into the editor.

How to install it?

mkdir libraries
cd libraries
  • Download and install the module:
drush -y en codesnippet

An example how to use it

  • Go to Configuration > Content authoring > Text formats and editors
  • Configure Full HTML text format
  • Drag CodeSnippet icon to the toolbar:

If you choose other text format, make sure it allows pre and and code tags.

  • Select syntax highlighting style and supported languages:

If you know beforehand what languages you are going to use, select only those so it's faster to pickup the right language when you are inserting a code snippet. Choose XML if you are inserting HTML.

  • Use the CodeSnippet icon to add snippets:

  • Select language and paste the code:

And now we have syntax highlighting:

The grey border and background around the snippet came from bootstrap styling the pre tags.

How to add more languages

  • Go to and select languages you want to use. Hit Download.
  • Replace /libraries/codesnippet/lib/highlight/highlight.pack.js with the file in the downloaded package.

Create a module:

  • Create a folder /modules/custom/mymodule
  • Create a file /modules/custom/mymodule/ with these lines:
name: My Module
type: module
description: My module
package: Custom
core: 8.x
  • Create a file /modules/custom/mymodule/mymodule.module with these lines:
use Drupal\Core\Form\FormStateInterface;

 * Implements hook_form_FORM_ID_alter().
 * Add extra languages for CodeSnippet
 * @param $form
 * @param FormStateInterface $form_state
 * @param $form_id
function mymodule_form_filter_format_edit_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  if (isset($form['editor']['settings']['subform']['plugins']['codesnippet'])) {
    $form['editor']['settings']['subform']['plugins']['codesnippet']['highlight_languages']['#options']['stylus'] = 'Stylus';
  • You can find the original code example in the module readme file.
  • Add ?php tag at the top
  • Replace function mymodule_form_filter.. with your module name
  • Replace ['stylus'] = 'Stylus'; with the language name

Go to and investigate source code of the example block to find the right class name to use. Like for example C++ blocks use cpp so you would use ['cpp'] = 'C++' here. I'm using Stylus for the example.

  • Enable the module and flush caches:
drush -y en mymodule
drush cr
  • Enable Stylus in the text format settings and you can select it when adding code snippets.

Sources and links

Samuli Natri is the founder of He started building Drupal sites in 2010 with Drupal 6. He attended Helsinki University and Helsinki University of Technology (Social Sciences and Computer Science). Read more...

Add new comment