Force Plain Text Paste in CKEditor

Force Plain Text Paste in CKEditor with Drupal WYSIWYG by using WYSIWYG’s ‘hook_wysiwyg_editor_settings_alter’ hook and CKEditor’s ‘forcePasteAsPlainText setting’.

Why Force Plain Text Paste?

One of the challenges of migrating content into a new Drupal site is the formatting that comes along with copied text, whether it comes from existing HTML or from a Word document. For example, a client’s new Drupal template dictates all body text be left aligned. Therefore, no WYSIWYG alignment buttons are provided. However, when pasting from their old website, text-alignment inline styles get getting copied over with no way to rectify once pasted. This example is only the tip of the iceberg.

The solution is to strip all formatting during pasting. It may take a little extra effort to reformat content in the WYSIWYG editor; however, the errant formatting is eliminated.

CKEditor ‘forcePasteAsPlainText’ Setting

CKEditor provides a number of settings to modify the editor’s behavior. The one needed in this case is the ‘forcePasteAsPlainText’ setting:

Whether to force all pasting operations to insert on plain text into the editor, loosing any formatting information possibly available in the source text.

Setting 'forcePasteAsPlainText = TRUE' is the first half of the solution.

hook_wysiwyg_editor_settings_alter

The ‘hook_wysiwyg_editor_settings_alter’ hook allows for the forcePasteAsPlainText setting to be implemented without hacking or patching the CKEditor library. This hook is the second half of the solution.

In my case, I created a custom module called ckeditor_override. Below is the code from ckeditor_override.module:

<?php
/**
* Implementation of hook_wysiwyg_editor_settings_alter().
*/
function ckeditor_override_wysiwyg_editor_settings_alter(&$settings, $context) {
  if($context['profile']->editor == 'ckeditor') {
    $settings['forcePasteAsPlainText'] = TRUE;
  }
}

If you’re new to Drupal and building modules, see the Creating Drupal 7.x modules documentation on Drupal.org

Add new comment