How to install it?

Download the latest Code Snippet plugin for CKEditor and place it in the libraries folder (in your site root):

1
2
3
4
5
mkdir libraries
cd libraries
wget http://download.ckeditor.com/codesnippet/releases/codesnippet_4.5.10.zip
unzip codesnippet_4.5.10.zip
rm codesnippet_4.5.10.zip

Download and install the module:

1
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:

Note: ff 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:

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

How to add more languages

Go to https://highlightjs.org/download/ 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/mymodule.info.yml with these lines:

1
2
3
4
5
name: My Module
type: module
description: My module
package: Custom
core: 8.x

Create a file /modules/custom/mymodule/mymodule.module with these lines:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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';
    asort($form['editor']['settings']['subform']['plugins']['codesnippet']['highlight_languages']['#options']);
  }
}

Note: 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.

Note: go to https://highlightjs.org/static/demo/ 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:

1
2
drush -y en mymodule
drush cr

Enable Stylus in the text format settings and you can select it when adding code snippets.