Code Editing Improvements in WordPress 4.9

The themes outlined for WordPress 4.9 are “editing code, managing plugins and themes, a user-centric way to customize a site, and polishing some recently added features over this last year.” Within the themes of editing code and polishing recent features, we’re improving the code editing functionality in the CustomizerCustomizer Tool built into WordPress core that hooks into most modern themes. You can use it to preview and modify many of your site’s appearance settings.’s Additional CSS feature, the Custom HTML widget, and the PluginPlugin A plugin is a piece of software containing a group of functions that can be added to a WordPress website. They can extend functionality or add new features to your WordPress websites. WordPress plugins are written in the PHP programming language and integrate seamlessly with WordPress. These can be free in the WordPress.org Plugin Directory https://wordpress.org/plugins/ or can be cost-based plugin from a third-party and Theme file editors. We included these improvements to code editing among the 4.9 goals and this release is packed with them.

CodeMirror: Syntax Highlighting, Linting, and Auto-completion

The most visible and drastic improvement to code editing in 4.9 is that there is now an actual code editing control rather than just a textarea input. If you’ve been using WordPress for a long time (over 8 years), this may sound like déjà vu. Syntax highlighting for the theme and plugin editors was originally introduced in WordPress 2.8 (#9173) but it was removed shortly after in 2.8.1 due to browser compatibility problems with the “CodePress” library (no relation to WordPress). So in the 8 years since the feature was re-proposed in #12423, after considering a slew of code editor libraries, we decided on incorporating CodeMirror:

CodeMirror is a versatile text editor implemented in JavaScriptJavaScript JavaScript or JS is an object-oriented computer programming language commonly used to create interactive effects within web browsers. WordPress makes extensive use of JS for a better user experience. While PHP is executed on the server, JS executes within a user’s browser. https://www.javascript.com/. for the browser. It is specialized for editing code, and comes with a number of language modes and add-ons that implement more advanced editing functionality. ¶ A rich programming APIAPI An API or Application Programming Interface is a software intermediary that allows programs to interact with each other and share data in limited, clearly defined ways. and a CSSCSS Cascading Style Sheets. theming system are available for customizing CodeMirror to fit your application, and extending it with new functionality.

You have probably already used this CodeMirror library a lot online, since it powers the editors in many familiar products and services including Brackets.io, Bitbucket, Chrome’s DevTools, Codepen, Firefox Developer Tools, GitHubGitHub GitHub is a website that offers online implementation of git repositories that can easily be shared, copied and modified by other developers. Public repositories are free to host, private repositories require a paid subscription. GitHub introduced the concept of the ‘pull request’ where code changes done in branches by contributors can be reviewed and discussed before being merged be the repository owner. https://github.com/, and JSFiddle, among many others. In the WordPress world specifically CodeMirror is also very familiar. Jetpack switched from ACE to CodeMirror in 2013 for its Custom CSS module, and there are close to 100 search results for CodeMirror on the plugin directory. Many of them should be updated to re-use CodeMirror as bundled with coreCore Core is the set of software required to run WordPress. The Core Development Team builds WordPress. as well. See below for some details on how to do that.

The syntax highlighting abilities of CodeMirror can help authors catch many mistakes visually while writing code, as the color coding can quickly clue in that something isn’t right. In addition to color coding, WordPress also enables by default the add-ons which will auto-close brackets and tags, and then also highlight matching braces and tags which have already been written.

CodeMirror also supports linting to actually add explicit error checking beyond just stylistic helps. WordPress is initially bundling the following linters: CSSLint, JSHintHTMLHint, and JSONLint. See #41873 for adding a PHPPHP The web scripting language in which WordPress is primarily architected. WordPress requires PHP 5.6.20 or higher linter as well, though as described below, the theme and plugin editors have a more robust means of checking for PHP errors by running the code on the server itself. The linters will report either errors or warnings with your code:

When a linter finds an error in your code (CSS, HTMLHTML HyperText Markup Language. The semantic scripting language primarily used for outputting content in web browsers., JSJS JavaScript, a web scripting language typically executed in the browser. Often used for advanced user interfaces and behaviors., or JSONJSON JSON, or JavaScript Object Notation, is a minimal, readable format for structuring data. It is used primarily to transmit data between a server and web application, as an alternative to XML.) the code editor in WordPress will prompt you to fix the error before allowing you to proceed with saving. The nature of this error notice varies by whether the code editor is in Custom CSS control, Custom HTML widgetWidget A WordPress Widget is a small block that performs a specific function. You can add these widgets in sidebars also known as widget-ready areas on your web page. WordPress widgets were originally created to provide a simple and easy-to-use way of giving design and structure control of the WordPress theme to the user., or the file editor.

Another feature of CodeMirror which reduces mistakes is auto-completion (or hinting). As you start typing out a CSS property, JavaScript DOM object, or HTML tagtag A directory in Subversion. WordPress uses tags to store a single snapshot of a version (3.6, 3.6.1, etc.), the common convention of tags in version control systems. (Not to be confused with post tags.), an autocomplete dropdown will appear which you can use your keyboard to select an option:

 

There is still room for improvement with auto-completion (see #42213), but the feature does help suggest possibilities when you generally have an idea of what you’re wanting to enter.

Theme and Language Modes

For the CodeMirror library now bundled in core, we decided to not include any of the alternate themes, so the default theme is used with some styles added to bring it in line with core. Additionally we also did not include all of the language modes, as many would be very unlikely to be relevant in the WordPress context (e.g. Fortran). The WordPress-relevant modes we are including with the core bundle are: clikecss, diff, htmlmixed, http, javascript, jsx, markdown, gfm, nginx, php, sass, shellsql, xml, and yaml. If a plugin wants to use a mode that is not bundled with core, they may bundle and enqueue the mode script separately (e.g. fortran.js); a plugin may also bundle and enqueue a custom theme if desired.

AccessibilityAccessibility Accessibility (commonly shortened to a11y) refers to the design of products, devices, services, or environments for people with disabilities. The concept of accessible design ensures both “direct access” (i.e. unassisted) and “indirect access” meaning compatibility with a person’s assistive technology (for example, computer screen readers). (https://en.wikipedia.org/wiki/Accessibility) and User Preference

One of the biggest challenges when exploring the incorporation of a code editor library into WordPress was the concerns raised regarding accessibility. For users of screen readers, a plain textarea is just going to be easier to navigate and use. CodeMirror does have an inputStyle option which:

Selects the way CodeMirror handles input and focus. The core library defines the "textarea" and "contenteditable" input models. On mobile browsers, the default is "contenteditable". On desktop browsers, the default is "textarea". Support for IME and screen readers is better in the "contenteditable" model. The intention is to make it the default on modern desktop browsers in the future.

The code editor in WordPress goes ahead and explicitly defines contenteditable as being the default for both desktop and mobile due to better accessibility. Nevertheless, since there are still accessibility concerns we decided to not yet integrate CodeMirror in the post editor’s Text tab; as CodeMirror is enabled by default it could impede users of screen readers from performing the primary writing workflow upon upgrading to 4.9. Additionally, it doesn’t make sense to work on integrating CodeMirror in the post editor since it is being heavily revamped right now in Gutenberg; we should instead focus on integrating CodeMirror into GutenbergGutenberg The Gutenberg project is the new Editor Interface for WordPress. The editor improves the process and experience of creating new content, making writing rich content much simpler. It uses ‘blocks’ to add richness rather than shortcodes, custom HTML etc. https://wordpress.org/gutenberg/ itself.

Lastly, if a user still does not want the CodeMirror library to be used when they edit code then there is now a user preference to turn it off. It is available on one’s user profile and it is called “Syntax Highlighting”. Again, it is enabled by default:

Additional CSS Integration

When the Additional CSS feature was introduced in 4.7, it used a plain textarea to edit the CSS code in the Customizer. For several years prior, Jetpack had already featured a Custom CSS module but it allowed CSS to be edited via a CodeMirror editor on an Edit CSS adminadmin (and super admin) screen. After 4.7 was released, Jetpack was updated to use Additional CSS in the Customizer instead, but enhanced it with the CodeMirror editor it had used on its Edit CSS admin screen. So now in WordPress 4.9, core is following suit and integrating CodeMirror into the Additional CSS feature as well (#38707), and there’s now an issue for Jetpack to newly re-use CodeMirror as bundled in core.

One key improvement from the initial implementation of Additional CSS is in regards to the detection of syntax errors. In 4.7 the error detection logic merely checked to make sure that the number of braces, brackets, and parentheses were balanced. This was not ideal because there were false positives when a balancing character was present in a comment (e.g. #39198). The goal was to eventually harden validation of CSS syntax validity by utilizing a tokenizer/parser (#39218). Instead of having to implement this logic in PHP, however, we now rely on client-side logic via CodeMirror and CSSLint to check for CSS errors and the unreliable server-side validation has been removed.

Code Editor Customizer Control

As when the Additional CSS feature was first introduced as being extensible, the updates feature new extensibility as well. When the feature was under development in 4.7 we debated whether or not to add a reusable code editor control for the Customizer. At that time we decided to opt for a regular textarea control with some enhancements since there wasn’t enough unique about the code editor to justify a separate control at that time. With the availability of CodeMirror, however, there is now justification for a reusable code editor Customizer control (#41897). This control is what is used to power the Additional CSS editor.

The code editor control may be registered in PHP via instantiating the WP_Customize_Code_Editor_Control class as can be seen in core. It allows you to pass a code_type param to indicate the file type being edited. Alternatively, an editor_settings array param may be passed which is the same format the new wp_enqueue_code_editor() function accepts (described below).

As with any Customizer control, the code editor control may also be added dynamically with just JavaScript. One example of this can be seen in the Customize Posts CSS plugin. Another example would be to add a second code editor control for Additional CSS to show up in the Colors section of the Customizer:

wp.customize.control.add( new wp.customize.CodeEditorControl( 'custom_colors', {
	section: 'colors',
	priority: 100,
	label: 'Custom CSS',
	editor_settings: {
		codemirror: {
			mode: 'css'
		}
	},
	setting: 'custom_css[' + wp.customize.settings.theme.stylesheet + ']'
} ) );

The code editor control registered for Additional CSS can itself also be extended. Either the registered custom_css control can be swapped out for a subclass of wp.customize.CodeEditorControl in JS (as seen in Jetpack PR), or the existing control can be modified at runtime. For example, in keeping with 4.7’s Custom SCSS Demo plugin, here is how you can dynamically change the Additional CSS control to use SCSS instead of plain CSS:

wp.customize.control( 'custom_css', function( control ) {

	/*
	 * CodeMirror gets initialized once the control's containing
	 * section is expanded. Note that if the Syntax Highlighting
	 * user preference is disabled, then the deferred will be
	 * rejected.
	 */
	control.deferred.codemirror.done( function() {
		var scssOptions = {
			mode: 'text/x-scss',
			lint: false, // CSSLint doesn't like SCSS.
			// The lint-marker gutter is automatically
			// toggled when lint option changes. 
		}
		_.each( scssOptions, function( value, option ) {
			control.editor.codemirror.setOption( option, value );
		} );
	} );
} );

And similarly, here is how you can change the default from CSS to SCSS via PHP:

add_action( 'customize_register', function( $wp_customize ) {
	$control = $wp_customize->get_control( 'custom_css' );
	if ( $control instanceof WP_Customize_Code_Editor_Control ) {
		$options = array();
		if ( isset( $control->editor_settings['codemirror'] ) ) {
			$options = isset( $control->editor_settings['codemirror'] );
		}
		$control->editor_settings['codemirror'] = array_merge(
			$options,
			array(
				'mode' => 'text/x-scss',
				'lint' => false,
				'gutters' => array(),
			)
		);
	}
}, 11 );

Custom HTML Widget Improvements

In WordPress 4.8.1 a dedicated Custom HTML widget was introduced in order to take over the role the Text widget had for adding arbitrary markup to sidebars, as the Text widget in 4.8 featured the TinyMCE visual editor. This new Custom HTML widget was introduced as essentially a clone of the old Text widget, aside from the absence of the “automatically add paragraphs” checkbox. Well now in WordPress 4.9 the Custom HTML widget comes into its own as it also now incorporates CodeMirror to provide users with syntax highlighting, auto-completion, and error checking. As with the Additional CSS feature, if you make a coding error in the Custom HTML widget, you will be blocked from saving until you fix the error. This guards against a misplaced div tag from breaking your site’s entire layout.

On multisitemultisite Used to describe a WordPress installation with a network of multiple blogs, grouped by sites. This installation type has shared users tables, and creates separate database tables for each blog (wp_posts becomes wp_0_posts). See also network, blog, site installs or any site on which an admin user lacks the unfiltered_html capability, there are restrictions for what HTML a user can provide in post content, Text widgets, and Custom HTML widgets alike. In 4.8.1 we resorted to listing out some common tags that would be illegal when a user cannot do unfiltered_html. With CodeMirror, however, this is greatly improved due to its integration with HTMLHint and because it is extensibleExtensible This is the ability to add additional functionality to the code. Plugins extend the WordPress core software. to allow custom rules to be added. There is now a custom kses rule for HTMLHint (htmlhint-kses.js) which checks HTML for any tags or attributes that are not returned by wp_kses_allowed_html( 'post' ). This means that we don’t need to tell users what they can’t do if they have no intention of doing it in the first place, and HTMLHint provides contextual inline error reporting when they do provide something invalidinvalid A resolution on the bug tracker (and generally common in software development, sometimes also notabug) that indicates the ticket is not a bug, is a support request, or is generally invalid.. Plus, since saving is blocked when there are errors, a user’s illegal HTML will not be silently stripped from them when they attempt to save (as wp_kses_post() is still applied on the content when saving on the server).

The CodeMirror component in the Custom HTML widget is integrated in a similar way to TinyMCE being integrated into the Text widget, adopting the same approach for integrating dynamic JavaScript-initialized fields. See custom-html-widgets.js which exports a wp.customHtmlWidgets object to JS.

Just as CodeMirror has been integrated into the Custom HTML widget, once 4.9 is released a logical next step would then be to integrate CodeMirror into Gutenberg’s Custom HTML blockBlock Block is the abstract term used to describe units of markup that, composed together, form the content or layout of a webpage using the WordPress editor. The idea combines concepts of what in the past may have achieved with shortcodes, custom HTML, and embed discovery into a single consistent API and user experience., as per PR comment. Similarly, once CodeMirror is available in core it can then be explored for use in Gutenberg’s Text view (see issue).

Theme and Plugin File Editors

Now, about those theme and plugin editors. The file editor in WordPress has been the subject of much debate and skepticism over the years. This may be also why hasn’t received a lot of love in terms of improvements. For reasons why the file editor is still a valuable part of WordPress in its mission to democratize publishing, please see @melchoyce‘s post “From No Code to Pro Code”. She goes on to outline a few ways that the file editor can be improved and in WordPress 4.9 almost all of them have been implemented and beyond.

Nevertheless, when a user first visits the theme or plugin editor, they will be presented with the new warnings as follows:

Notice how the theme editor has a link directing a user to the Additional CSS feature in the Customizer. It is the hope that CodeMirror will be primarily used in Additional CSS and the Custom HTML widget, but for users who do need to make theme and plugin changes the editors have been vastly improved.

The file editors now also feature the same CodeMirror-powered syntax highlighting, auto-completion, and error checking. The allowed file extensions in the file editors can edit have been expanded to include formats which CodeMirror has modes for: conf, css, diff, patch, html, htm, http, js, json, jsx, less, md, php, phtml, php3, php4, php5, php7, phps, scss, sass, sh, bash, sql, svg, xml, yml, yaml, txt. In addition to increasing the number of editable file types, the file editors also now allow you to edit files deeper than two directories deep. And now given that the file list can be much longer than before, the files and their directories are now presented in an scrollable expandable tree like most editors provide:

When editing CSS, JS, HTML, and JSON files there is the same error checking powered by client side linters. As with Additional CSS and the Custom HTML widget, if a linter detects an error it will display an error and block you from saving the change. Here there is also a way for a user to override the error to proceed with saving anyway:

When editing PHP files, however, client-side linting is not enough (though it would be a nice enhancementenhancement Enhancements are simple improvements to WordPress, such as the addition of a hook, a new feature, or an improvement to an existing feature., see #41873). If attempting to call an undefined function this will not be a syntax error, but it will cause a fatal error and whitescreen your site. The plugin editor did previously have some basic safeguards for this by temporarily deactivating the plugin and then re-activating it in a sandbox to check for fatal errors, though it was not very reliable (see #39766). And even when it was able to check for errors, a fatal error would result in the plugin being deactivated, a plugin which could be critical to a site to function properly. For themes on the other hand, there was no such ability to temporarily deactivate the theme and do a sandboxed check for fatal errors since a theme cannot be deactivated like a plugin can.

Ultimately what was worked out in #21622 was a new sandboxed method for making PHP file changes in both plugins and themes. When attempting to save a PHP file edit for a plugin or theme, during the user’s save request WordPress will write the file to disk after first copying the old file’s contents into a variable. Then immediately after writing the change it will do a loopback request back to the file editor screen with the user’s same cookies to check to see if the PHP file edit would lock them out of the editor. If that loopback request generates a PHP fatal error, then the original PHP file is restored. Otherwise, if there is no fatal error then WordPress will open another loopback request to the homepage of the site to check if there is a fatal error generated there. If so, again, the PHP file edit is undone with the old version of the file restored. At that point, an error message is shown to the user informing them of what specifically the error was and prompting them to fix it. The user’s modifications to the PHP file remain in the editor for them to fix (also these save requests now happen over Ajax so the user never leaves the page). If they try leaving the page without fixing the error and successfully re-saving, they’ll get an “Are you sure?” dialog informing them they would lose their changes, in the same way as leaving the Customizer or the Add New Post screen. If the loopback requests aren’t able to complete, the file edits will also be reverted and the user will be prompted to use SFTPSFTP SFTP is an acronym for Secure File Transfer Protocol: A standard protocol to move computer files from one host to another over the Internet with enhanced security. to edit the file.

The JavaScript powering the new updated interface for the theme and plugin editors is located in theme-plugin-editor.js, which exports a wp.themePluginEditor object.

Code Editor APIs

The Customizer code editor control, Custom HTML widget, and file editor all make use of an underlying “code editor” API that provides an abstraction on top of CodeMirror. In PHP there is the wp_enqueue_code_editor() function which is named and functionally similar to wp_enqueue_editor() for TinyMCE. The wp_enqueue_code_editor() function takes an array of args, including the ability to specify the file type that you intend to edit, or else the file name itself. Alternatively, you can pass a codemirror array arg that has the same structure as what you would pass when initializing CodeMirror in JS. Then depending on the language mode that is either explicitly provided via codemirror arg or which is deduced from the file or type args, the function will specify various defaults depending on the selected mode. For example, if editing CSS then it will enable linting and if editing HTML it will enable the auto-closing of tags. Once the settings array is fully assembled it is then passed into a wp_code_editor_settings filterFilter Filters are one of the two types of Hooks https://codex.wordpress.org/Plugin_API/Hooks. They provide a way for functions to modify data of other functions. They are the counterpart to Actions. Unlike Actions, filters are meant to work in an isolated manner, and should never have side effects such as affecting global variables and output. to give plugins a chance to further modify the settings. If this filter returns false or if the user had previously disabled the syntax highlighting preference, then the function will return false and no scripts will be enqueued. Otherwise, the function will proceed to then enqueue the code-editor script and style along with the wp-codemirror script/style dependencies and then any supporting linter scripts.

The wp_enqueue_code_editor() function will exported its settings array to wp.codeEditor.defaultSettings in JS while also returning it to that a feature can directly pass it into the wp.codeEditor.initialize() API. This initialize method is modeled after CodeMirror.fromTextArea() in that it takes a textarea object or ID as its first argument and then the settings as its second. In addition to the settings exported from wp_qneueue_code_editor() the settings passed into the initialize method can also include several callbacks including onChangeLintingErrors, onUpdateErrorNotice, onTabPrevious, onTabNext. These callbacks are what the various integrations rely on to manage the displaying of linting errors as well as ensuring keyboard navigation.

Here is a simple example of turning the user’s bio into a CodeMirror HTML editor on their profile screen:

add_action( 'admin_enqueue_scripts', function() {
	if ( 'profile' !== get_current_screen()->id ) {
		return;
	}

	// Enqueue code editor and settings for manipulating HTML.
	$settings = wp_enqueue_code_editor( array( 'type' => 'text/html' ) );

	// Bail if user disabled CodeMirror.
	if ( false === $settings ) {
		return;
	}

	wp_add_inline_script(
		'code-editor',
		sprintf(
			'jQuery( function() { wp.codeEditor.initialize( "description", %s ); } );',
			wp_json_encode( $settings )
		)
	);
} );

As noted above, CodeMirror and its bundled modes and add-ons are registered in a wp-codemirror script handle. Also important to note here that this script does not define a global CodeMirror object but rather a wp.CodeMirror one. This ensures that other plugins that may be including other CodeMirror bundles won’t have conflicts. This also means that if you do want to include fortran.js from CodeMirror, that you’ll need to bundle it to call wp.CodeMirror.defineMode() instead of CodeMirror.defineMode(). A workaround for having to do this would be the following, but be aware of potential conflicts:

wp_add_inline_script( 
	'wp-codemirror', 
	'window.CodeMirror = wp.CodeMirror;'
);

Development History

The integration of CodeMirror into core was initially worked on in the Better Code Editing feature pluginFeature Plugin A plugin that was created with the intention of eventually being proposed for inclusion in WordPress Core. See Features as Plugins. on GitHub. A full development history can be found there in the issues, pull requests, and commit log.

The principal contributors to code editing in this release were @afercia, @helen, @georgestephanis, @obenland, @melchoyce, @westonruter, and @WraithKenny.

The key tickets related to code editor improvements in 4.9 are:

  • #6531: Recursively search for files in theme and plugin editors
  • #12423: Include default code editor
  • #21622: Validate or sandbox theme file edits before saving them (as is done for plugins)
  • #24048: Code Editors: Increase the usability of Code Editor’s files list
  • #31779: Warn users before using a built-in file editor for the first time
  • #38707: Customizer: Additional CSS highlight, revisionsRevisions The WordPress revisions system stores a record of each saved draft or published update. The revision system allows you to see what changes were made in each revision by dragging a slider (or using the Next/Previous buttons). The display indicates what has changed in each revision., selection, per-page, pop-out (partially completed for this release)
  • #39218: Customize: Harden validation of CSS syntax validity by utilizing tokenizer
  • #39766: Plugin does not gracefully fail when editing active plugin causes fatal error
  • #39892: Default value in Additional CSS
  • #41073: Linting code changes: prevent saving, or add confirm message
  • #41872: Code Editor: Minor accessibility improvements to the CodeMirror editing areas
  • #41887: Code Editor: Error disables the Update File button.
  • #41897: Code Editor: Add reusable code editor Customizer control

#4-9, #codemirror, #dev-notes