PHPackages                             nystudio107/craft-code-editor - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Templating &amp; Views](/categories/templating)
4. /
5. nystudio107/craft-code-editor

ActiveYii2-extension[Templating &amp; Views](/categories/templating)

nystudio107/craft-code-editor
=============================

Provides a code editor field with Twig &amp; Craft API autocomplete

1.0.29(3mo ago)71.2M↓12.9%7[2 issues](https://github.com/nystudio107/craft-code-editor/issues)17MITPHPCI failing

Since Nov 1Pushed 3mo ago1 watchersCompare

[ Source](https://github.com/nystudio107/craft-code-editor)[ Packagist](https://packagist.org/packages/nystudio107/craft-code-editor)[ GitHub Sponsors](https://github.com/khalwat)[ RSS](/packages/nystudio107-craft-code-editor/feed)WikiDiscussions develop Synced 1mo ago

READMEChangelog (10)Dependencies (5)Versions (32)Used By (17)

[![Scrutinizer Code Quality](https://camo.githubusercontent.com/b194ab94ab4618c7171e7104ef5c15f44fb039e2b26ed50e65837e0e4e1195f2/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f6e7973747564696f3130372f63726166742d636f64652d656469746f722f6261646765732f7175616c6974792d73636f72652e706e673f623d7631)](https://scrutinizer-ci.com/g/nystudio107/craft-code-editor/?branch=v1) [![Code Coverage](https://camo.githubusercontent.com/52afdeb68abd1207aeaa8fc7a0c9d00caedc251dd76b4c3d20ed070b0c1ca186/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f6e7973747564696f3130372f63726166742d636f64652d656469746f722f6261646765732f636f7665726167652e706e673f623d7631)](https://scrutinizer-ci.com/g/nystudio107/craft-code-editor/?branch=v1) [![Build Status](https://camo.githubusercontent.com/8dc141b24ace99fb176cf8b645cd29c3e055bfce3ff8d10c07d53a8627e0bddf/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f6e7973747564696f3130372f63726166742d636f64652d656469746f722f6261646765732f6275696c642e706e673f623d7631)](https://scrutinizer-ci.com/g/nystudio107/craft-code-editor/build-status/v1) [![Code Intelligence Status](https://camo.githubusercontent.com/f01cd18b9a6dcd3eb1e660bd2bc6b6ba3b64f89131879914031ea8f1c0b7c929/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f6e7973747564696f3130372f63726166742d636f64652d656469746f722f6261646765732f636f64652d696e74656c6c6967656e63652e7376673f623d7631)](https://scrutinizer-ci.com/code-intelligence)

Code Editor for Craft CMS 3.x, 4.x &amp; 5.0
============================================

[](#code-editor-for-craft-cms-3x-4x--50)

Provides a code editor field with Twig &amp; Craft API autocomplete

[![Demo](./resources/code-editor-demo.gif)](./resources/code-editor-demo.gif)

Requirements
------------

[](#requirements)

Code Editor requires Craft CMS 3.x, 4.x or 5.x.

Installation
------------

[](#installation)

To install Code Editor, follow these steps:

1. Open your terminal and go to your Craft project:

    ```
     cd /path/to/project

    ```
2. Then tell Composer to require the package:

    ```
     composer require nystudio107/craft-code-editor

    ```

About Code Editor
-----------------

[](#about-code-editor)

Code Editor provides a full-featured code editor with syntax highlighting via the powerful [Monaco Editor](https://microsoft.github.io/monaco-editor/) (the same editor that is the basis for VS Code).

It also can handle hundreds of other code languages, such as [JavaScript](https://github.com/doublesecretagency/craft-cpjs/pull/6), TypeScript, [CSS](https://github.com/doublesecretagency/craft-cpcss/pull/20), Markdown, and a [whole lot more](https://microsoft.github.io/monaco-editor/).

Code Editor provides full autocompletion for [Twig](https://twig.symfony.com/doc/3.x/) filters/functions/tags, and the full [Craft CMS](https://craftcms.com/docs/4.x/) API, including installed plugins:

[![Autocomplete](./resources/code-editor-autocomplete.png)](./resources/code-editor-autocomplete.png)

And it adds hover documentation when you hover the cursor over an expression:

[![Hovers](./resources/code-editor-hovers.png)](./resources/code-editor-hovers.png)

You can also add your own custom Autocompletes, and customize the behavior of the editor.

Code Editor also provides a [Yii2 Validator](https://www.yiiframework.com/doc/guide/2.0/en/tutorial-core-validators) for Twig templates and object templates.

If instead you need a Craft CMS field, use the [Code Field plugin](https://plugins.craftcms.com/codefield), which provides Code Editor wrapped in a field type.

Using Code Editor
-----------------

[](#using-code-editor)

Once you've added the `nystudio107/craft-code-editor` package to your plugin, module, or project, no further setup is needed. This is because it operates as an auto-bootstrapping Yii2 Module.

Code Editor is not a Craft CMS plugin, rather a package to be utilized by a plugin, module, or project.

It can be very easy to add to an existing project, as you can see from the [Preparse field pull request](https://github.com/besteadfast/craft-preparse-field/pull/87) that adds it the [Preparse plugin](https://github.com/besteadfast/craft-preparse-field).

### In the Craft CP

[](#in-the-craft-cp)

Code Editor works just like the Craft CMS `forms` macros that should be familiar to plugin and module developers.

#### Import Macros

[](#import-macros)

Simply import the macros:

```
{% import "codeeditor/codeEditor" as codeEditor %}
```

#### Multi-line Editor

[](#multi-line-editor)

Then to create a `textarea` multi-line editor, do the following:

```
{{ codeEditor.textarea({
    id: "myCodeEditor",
    name: "myCodeEditor",
    value: textAreaText,
}) }}
```

...where `textAreaText` is a variable containing the initial text that should be in the editor field. This will create the Twig editor.

To create a `textareaField` multi-line editor, do the following:

```
{{ codeEditor.textareaField({
    label: "Twig Editor"|t,
    instructions: "Enter any Twig code below, with full API autocompletion."|t,
    id: "myCodeEditor",
    name: "myCodeEditor",
    value: textAreaText,
}) }}
```

...where `textAreaText` is a variable containing the initial text that should be in the editor field. This will create the `label` and `instructions`, along with the Twig editor.

#### Single-line Editor

[](#single-line-editor)

Then to create a `text` single-line editor, do the following:

```
{{ codeEditor.text({
    id: "myCodeEditor",
    name: "myCodeEditor",
    value: text,
}) }}
```

...where `text` is a variable containing the initial text that should be in the editor field. This will create the Twig editor that is restricted to a single line, for simple Twig expressions.

To create a `textField` single-line editor, do the following:

```
{{ codeEditor.textField({
    label: "Twig Editor"|t,
    instructions: "Enter any Twig code below, with full API autocompletion."|t,
    id: "myCodeEditor",
    name: "myCodeEditor",
    value: text,
}) }}
```

...where `text` is a variable containing the initial text that should be in the editor field. This will create the `label` and `instructions`, along with the Twig editor that is restricted to a single line, for simple Twig expressions.

Regardless of the macro used, an Asset Bundle containing the necessary CSS &amp; JavaScript for the editor to function will be included, and the editor initialized.

### In Frontend Templates

[](#in-frontend-templates)

Code Editor also works in frontend templates, but you can disable it via the `allowTemplateAccess` config setting. This is enabled by default.

There is also a `allowFrontendAccess` which is disabled by default. This allows access to the `codeeditor/autocomplete/index` endpoint for Twig &amp; Craft API autocompletes. This is disabled by default, so if you want these completions on the frontend, you'll need to specifically enable it.

Do so by copying the `config.php` file to the Craft CMS `config/` directory, renaming the file to `codeeditor.php` in the process, then set the `allowFrontendAccess` setting to `true`:

```
return [
    // Whether to allow anonymous access be allowed to the codeeditor/autocomplete/index endpoint
    'allowFrontendAccess' => true,
    // Whether to allow frontend templates access to the `codeeditor/codeEditor.twig` Twig template
    'allowTemplateAccess' => true,
    // The default autocompletes to use for the default `CodeEditor` field type
    'defaultCodeEditorAutocompletes' => [
        CraftApiAutocomplete::class,
        TwigLanguageAutocomplete::class,
        SectionShorthandFieldsAutocomplete::class,
    ]
];
```

Then import the macros:

```
{% import "codeeditor/codeEditor" as codeEditor %}
```

Create your own `` element and include the necessary JavaScript, passing in the `id` of your `textarea` element:

```

{{ codeEditor.includeJs("myCodeEditor") }}
```

Enabling the `allowFrontendAccess` setting allows access to the `codeeditor/autocomplete/index` endpoint, and add the `codeeditor/templates` directory to the template roots.

The following `monacoOptions` allow you to make the field read-only (though the user can still interact with the code):

```
{
    "domReadOnly": true,
    "readOnly": true
}
```

### Additional Options

[](#additional-options)

The `textarea`, `textareaField`, `text`, `textField`, and `includeJs` macros all take three additional optional parameters:

```
{{ textarea(config, fieldType, editorOptions, codeEditorOptions) }}

{{ textareaField(config, fieldType, editorOptions, codeEditorOptions }}

{{ text(config, fieldType, editorOptions, codeEditorOptions) }}

{{ textField(config, fieldType, editorOptions, codeEditorOptions }}

{{ includeJs(fieldId, fieldType, editorOptions, codeEditorOptions }}
```

#### `fieldType`

[](#fieldtype)

**`fieldType`** - an optional 2nd parameter. By default this is set to `Code Editor`. You only need to change it to something else if you're using a custom Autocomplete (see below)

e.g.:

```
{{ codeEditor.textarea({
    id: 'myCodeEditor',
    name: 'myCodeEditor',
    value: textAreaText,
}), "MyCustomFieldType" }}
```

#### `editorOptions`

[](#editoroptions)

**`editorOptions`** - an optional 4th parameter. This is an [EditorOption](https://microsoft.github.io/monaco-editor/api/interfaces/monaco.editor.IEditorOptions.html) passed in to configure the Monaco editor. By default, this is an empty object.

You would commonly use `editorOptions` to specify the `language` to be used for the Code Editor, or the `theme`, but you can override any [EditorOption](https://microsoft.github.io/monaco-editor/api/interfaces/monaco.editor.IEditorOptions.html) you like.

e.g.:

```
{{ codeEditor.textareaField({
    label: "Twig Editor"|t,
    instructions: "Enter any Twig code below, with full API autocompletion."|t,
    id: 'myCodeEditor',
    name: "myCodeEditor",
    value: textAreaText,
    }), "Code Editor", {
        language: "javascript",
        theme: "vs-dark",
    }
}}
```

#### `codeEditorOptions`

[](#codeeditoroptions)

**`codeEditorOptions`** - an optional 5th parameter. This object that can contain any data you want to pass from your Twig template down to the Autocomplete. This can be leveraged in custom Autocompletes to pass contextual for a particular field to the Autocomplete (see below)

e.g.:

```
{{ codeEditor.textareaField({
    label: "Twig Editor"|t,
    instructions: "Enter any Twig code below, with full API autocompletion."|t,
    id: "myCodeEditor",
    name: "myCodeEditor",
    value: textAreaText,
    }), "Code Editor", { lineNumbers: "on" }, {
        wrapperClass: "my-css-class another-css-class",
        placeholderText: "Type something!",
   }
}}
```

You can pass in any options you like to `codeEditorOptions` (which might be used in a custom Autocomplete), but the following pre-defined options have a special meaning:

- **`wrapperClass`** - `string` - An additional class that is added to the Code Editor editor wrapper `div`. By default, this is an empty string. The `monaco-editor-background-frame` class is bundled, and will cause the field to look like a Craft CMS editor field, but you can use your own class as well. There also a `monaco-editor-inline-frame` bundled style for an inline editor in a table cell (or elsewhere that no chrome is desired).
- **`singleLineEditor`** - `boolean` - Whether this editor should behave like a single line text field. This is set to `true` for the `text` and `textField` Twig macros, and `false` for the `textarea` and `textareaField` Twig macros.
- **`placeholderText`** - `string` - Placeholder text that should be displayed if the Code Editor field is empty.
- **`displayLanguageIcon`** - `boolean` - Whether the language icon should be displayed in the upper-right corner of the Code Editor, if available.
- **fileName** - `string` - The name of the file being displayed, used to let Monaco determine the language to use based on the fileName suffix
- **fixedHeightEditor** - `boolean` - Normally the editor will dynamically size to fit the content contained with it. If this option is set to `true` then instead, the editor will be a fixed height determined by its parent container (with a scrollbar when needed)
- **maxEditorRows** - `number` - The maximum number of rows the editor can be before the height is fixed, and a scrollbar is added. Set this to `0` if you want an infinite number of rows, with no scrollbar. Defaults to `50`

Using Additional Autocompletes
------------------------------

[](#using-additional-autocompletes)

Code Editor adds autocompletes only when the editor language is `twig`. The reason is twofold:

- The VScode-derived Monaco editor that powers Code Editor has poor support for Twig, so Code Editor provides Autocompletes for the Twig language
- Craft dynamically adds a raft of functionality to the Twig language in the form of the Craft API, filters, functions, etc. that Code Editor takes care of providing to the Monaco editor

Other languages have more robust support, and come with baked-in autocomplete and syntax highlighting.

By default, Code Editor uses the `CraftApiAutocomplete` &amp; `TwigLanguageAutocomplete`, but it also includes an optional `EnvironmentVariableAutocomplete` which provides autocompletion of any Craft CMS [Environment Variables](https://craftcms.com/docs/4.x/config/#environmental-configuration) and [Aliases](https://craftcms.com/docs/4.x/config/#aliases).

If you want to use the `EnvironmentVariableAutocomplete` or a custom Autocomplete you write, you'll need to add a little PHP code to your plugin, module, or project:

```
use nystudio107\codeeditor\autocompletes\EnvironmentVariableAutocomplete;
use nystudio107\codeeditor\events\RegisterCodeEditorAutocompletesEvent;
use nystudio107\codeeditor\services\AutocompleteService;

Event::on(
    AutocompleteService::class,
    AutocompleteService::EVENT_REGISTER_CODEEDITOR_AUTOCOMPLETES,
    function (RegisterCodeEditorAutocompletesEvent $event) {
        $event->types[] = EnvironmentVariableAutocomplete::class;
    }
);
```

The above code will add Environment Variable &amp; Alias autocompletes to all of your Code Editor editors.

However, because you might have several instances of a Code Editor on the same page, and they each may provide separate Autocompletes, you may want to selectively add a custom Autocomplete only when the `fieldType` matches a specific.

Here's an example from the [Sprig plugin](https://github.com/putyourlightson/craft-sprig):

```
use nystudio107\codeeditor\events\RegisterCodeEditorAutocompletesEvent;
use nystudio107\codeeditor\services\AutocompleteService;
use putyourlightson\sprig\plugin\autocompletes\SprigApiAutocomplete;

public const SPRIG_TWIG_FIELD_TYPE = 'SprigField';

Event::on(
    AutocompleteService::class,
    AutocompleteService::EVENT_REGISTER_CODEEDITOR_AUTOCOMPLETES,
    function (RegisterCodeEditorAutocompletesEvent $event) {
        if ($event->fieldType === self::SPRIG_TWIG_FIELD_TYPE) {
            $event->types[] = SprigApiAutocomplete::class;
        }
    }
);
```

This ensures that the `SprigApiAutocomplete` Autocomplete will only be added when the `fieldType` passed into the Code Editor macros is set to `SprigField`.

Additionally, you may have an Autocomplete that you want to pass config information down to when it is instantiated. You can accomplish that by adding the Autocomplete as an array:

```
use nystudio107\codeeditor\autocompletes\CraftApiAutocomplete;
use nystudio107\codeeditor\events\RegisterCodeEditorAutocompletesEvent;
use nystudio107\codeeditor\services\AutocompleteService;

Event::on(
    AutocompleteService::class,
    AutocompleteService::EVENT_REGISTER_CODEEDITOR_AUTOCOMPLETES,
    function (RegisterCodeEditorAutocompletesEvent $event) {
         $config = [
             'additionalGlobals' => $arrayOfVariables,
         ];
        $event->types[] = [CraftApiAutocomplete::class => $config];
    }
);
```

Note that all of the above examples *add* Autocompletes to the Autocompletes that Code Editor provides by default (`CraftApiAutocomplete` and `TwigLanguageAutocomplete`). If you want to *replace* them entirely, just empty the `types[]` array first:

```
        $event->types[] = [];
        $event->types[] = [CraftApiAutocomplete::class => $config];
```

Writing a Custom Autocomplete
-----------------------------

[](#writing-a-custom-autocomplete)

Autocompletes extend from the base [Autocomplete](https://github.com/nystudio107/craft-code-editor/blob/develop/src/base/Autocomplete.php) class, and implement the [AutocompleteInterface](https://github.com/nystudio107/craft-code-editor/blob/develop/src/base/AutocompleteInterface.php)

A simple Autocomplete would look like this:

```
