Skip to main content

zuraffa_code_editor 7.3.7 copy "zuraffa_code_editor: ^7.3.7" to clipboard
zuraffa_code_editor: ^7.3.7 copied to clipboard

A customizable Flutter code field supporting syntax highlighting, code folding with visible closing lines, autocompletion and themes.

Zuraffa Code Editor #

Pub Version

flutter pub add zuraffa_code_editor

A maintained fork of flutter_code_editor 0.3.5 for the Zuraffa ecosystem.

Why a fork? Two reasons. Upstream hid a folded block through the end of its last line, so folding parsers: [ ... ] left a dangling parsers: [ with no matching ],. This fork keeps the closing line visible: parsers: [ ],. And since 0.4.0 the code is drawn by re_editor rather than by a TextField, so a document of any length costs the same to draw as a document of one screen. See the changelog for the full diff from upstream.

Migrating from flutter_code_editor is a drop-in import swap:

// Before
import 'package:flutter_code_editor/flutter_code_editor.dart';
// After
import 'package:zuraffa_code_editor/zuraffa_code_editor.dart';

The import swap is all that is needed for the API. The behaviour changed in 0.4.0: the code is now drawn by re_editor instead of by a TextField, which makes large documents editable. See Performance and Renderers.

Zuraffa Code Editor is a multi-platform code editor supporting:

  • Syntax highlighting for over 100 languages,
  • Code blocks folding,
  • Autocompletion,
  • Read-only code blocks,
  • Hiding specific code blocks,
  • Themes,
  • And many other features.

Android, iOS, Linux, macOS, Windows and the web are all supported. The web target is real rather than declared: nothing in the dependency graph reaches dart:io since the autocompletion engine became in-house, which is what pana derives the platform tags from. pubspec.yaml lists the six platforms explicitly so the claim cannot silently regress.

Basic example

Basic Usage #

import 'package:flutter/material.dart';
import 'package:zuraffa_code_editor/zuraffa_code_editor.dart';
import 'package:flutter_highlight/themes/monokai-sublime.dart';
import 'package:highlight/languages/java.dart';

void main() {
  runApp(const CodeEditor());
}

final controller = CodeController(
  text: '...', // Initial code
  language: java,
);

class CodeEditor extends StatelessWidget {
  const CodeEditor();

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: CodeTheme(
          data: CodeThemeData(styles: monokaiSublimeTheme),
          child: SingleChildScrollView(
            child: CodeField(
              controller: controller,
            ),
          ),
        ),
      ),
    );
  }
}

See the full runnable example here.

Performance #

Since 0.4.0 the code is drawn by re_editor, which lays out only the lines that are on screen. Before that, the editor built one paragraph for the whole document and re-laid it out on every keystroke, so a file of any real size stuttered.

Measured on a 50 000-line document:

before after
CodeController construction 47 000 ms 743 ms
one-character edit 58 725 ms 1 223 ms

The layout was only half of the problem. The controller also ran a whole-document highlight parse on every text change, and that parse is quadratic. It is now off by default (CodeController.highlightEnabled), because the re_editor renderer highlights the code itself.

Renderers #

A CodeField draws the code with one of two renderers:

CodeField(
  controller: controller,
  renderer: CodeFieldRenderer.reEditor, // the default
)
  • CodeFieldRenderer.reEditor — the default. Draws only the visible lines, so it is the one to use for large documents.
  • CodeFieldRenderer.textField — the old TextField-based renderer. It is still there for the cases re_editor cannot cover.

A field whose resolved text direction is right to left is drawn with the text field renderer, because re_editor 0.10.0 hardcodes TextDirection.ltr. Left to right is the fast path; right to left stays functional.

Differences on the re_editor renderer #

  • No fold marker. The text field renderer draws … at the end of a folded block's kept line. The re path does not — the marker would have to be injected into the visible text, which shifts every offset the bridge maps through it. The chevron in the gutter is the affordance there.
  • No per-line lineBackgroundBuilder. re_editor has no per-line background hook. cursorLineColor is wired.
  • The mobile enter key. On Android and iOS the enter key breaks the line rather than committing the autocomplete suggestion or moving to the next search match. Every other key keeps its usual meaning on both platforms.

Languages #

Syntax Highlighting #

Zuraffa Code Editor supports over a hundred languages, relying on the highlight package for parsing code.

To select a language, use a corresponding variable:

import 'package:highlight/languages/python.dart'; // Each language is defined in its file.

final controller = CodeController(
  text: '...', // Initial code
  language: python,
);

Language can be dynamically changed on a controller:

controller.setLanguage(go, DefaultLocalAnalyzer());

Markup: HTML is highlighted by the xml mode

highlight defines no html mode of its own. HTML — together with xhtml, rss, atom, xjb, xsd, xsl, plist, wsf and svg — is listed among the aliases of its xml mode, and that mode is what parses it: doctype, element names, attributes, attribute values, comments and entity references all come out classified. So to edit HTML, import and use xml:

import 'package:highlight/languages/xml.dart'; // Highlights HTML too.

final controller = CodeController(
  text: '<!DOCTYPE html>...',
  language: xml,
);

In practice, <script> and <style> bodies come out as plain markup rather than being re-parsed as JavaScript or CSS in highlight 0.7.0: the modes do declare subLanguage entries for both, but their <script/<style tag modes never match, so those entries never engage. (<?php ?> bodies are parsed — as PHP.) If a future highlight release fixes the matching, the bodies would start being re-parsed.

Java: # and triple-quoted strings

highlight 0.7.0's java mode stops the parse on an illegal lexeme, and _parse turns that into the whole document being handed back as one plain node — so a single # outside a comment or a string literal, or a stray </, loses the highlighting for the entire file. A triple-quoted string literal reaches the same end the other way: with no triple-quote mode, the third " opens an ordinary string whose content crosses a newline, and an ordinary java string declares a newline illegal.

The controller registers a repaired copy of the java mode — the illegal regex dropped and a """…""" string mode added — so neither costs the document anything. Only the highlight parse sees the copy: controller.language is still the mode you supplied, the autocompleter and the single-line-comment sequences still key on it, and every other language is registered exactly as you gave it.

Code Blocks Folding #

Zuraffa Code Editor can detect and fold code blocks. Code blocks folding is supported for the following languages:

  • Dart
  • Go
  • Java
  • Python
  • Scala

Foldable blocks example

Code blocks folding may support other languages in experimental mode.

Code Analysis #

The editor supports pluggable analyzers to highlight errors and show error messages:

DartPadAnalyzer

We ship the following analyzers:

  • DefaultLocalAnalyzer highlights unmatched pair characters for supported languages. It works on the client locally, and is selected by default on CodeController if no other analyzer is specified.
  • DartPadAnalyzer for Dart language, calls upon the DartPad backend for analysis.

For other languages, you can write custom analyzers that access your backend. See the code for DartPadAnalyzer for the implementation example.

To set the analyzer, call any of the following:

codeController = CodeController(language: dart, analyzer: DartPadAnalyzer());
codeController.analyzer = DartPadAnalyzer();
codeController.setLanguage(dart, analyzer: DartPadAnalyzer());

Note: Code analysis is an experimental feature. We may introduce breaking changes to Analyzer subclasses without following the semver contract. If you only use the analyzers we ship, then this will not affect you.

Themes #

Pre-defined Themes #

Zuraffa Code Editor supports themes from the highlight package — see the full list of the pre-defined themes here.

Use CodeTheme widget to set the theme for underlying editors:

return MaterialApp(
  home: Scaffold(
    body: CodeTheme(
      data: CodeThemeData(styles: monokaiSublimeTheme), // <= Pre-defined in flutter_highlight.
      child: SingleChildScrollView(
        child: CodeField(
          controller: controller,
        ),
      ),
    ),
  ),
);

Custom Themes #

To use a custom theme, create a map of styles under the pre-defined class names — see this example.

Hiding Line Numbers, Errors, and Folding Handles #

A lot of styling can be tuned with a GutterStyle object passed to a CodeField widget. See this example that dynamically changes the properties listed here.

CodeField(
  gutterStyle: GutterStyle(
    showErrors: false,
    showFoldingHandles: false,
    showLineNumbers: false,
  ),
  // ...
),

If you want to hide the entire gutter, use GutterStyle.none constant instead:

CodeField(
  gutterStyle: GutterStyle.none,
  // ...
),

Which GutterStyle.textStyle properties you can set #

The line numbers must sit exactly on the code's line grid — one row per code line — or the two columns drift apart and the gutter labels the wrong lines. The properties that decide how tall a line box is therefore come from CodeField.textStyle and cannot be changed through GutterStyle.textStyle:

GutterStyle.textStyle property forced from why
fontSize CodeField.textStyle with height, it is the line box height
fontFamily CodeField.textStyle another face has different metrics
height CodeField.textStyle the line-height multiplier itself

Everything else applies as given, so the numbers can be restyled without being moved — color, fontWeight, fontStyle, letterSpacing, wordSpacing, fontFeatures, fontVariations, fontFamilyFallback, background, decoration, foreground, shadows. A differing fontSize, fontFamily or height is ignored rather than merged, so it cannot misalign the gutter:

CodeField(
  textStyle: const TextStyle(fontSize: 13, height: 1.6),
  gutterStyle: const GutterStyle(
    textStyle: TextStyle(
      // Ignored: these three come from CodeField.textStyle.
      fontSize: 40,
      fontFamily: 'Courier New',
      height: 3.5,
      // Applied: these change how the numbers look, not where they sit.
      color: Colors.blueGrey,
      fontWeight: FontWeight.w700,
      letterSpacing: 2,
    ),
  ),
),

With no GutterStyle.textStyle at all, the numbers inherit CodeField.textStyle at half the opacity of its colour.

Accessing the Text #

CodeController extends the Flutter's built-in TextEditingController and is immediately usable as one. However, code folding and other features have impact on built-in properties:

  • text returns and sets the visible text. If any code is folded, it will not be returned.
  • value returns and sets the TextEditingValue with the visible text and selection. If any code is folded, it will not be returned.
  • fullText returns and sets the entire text, including any folded blocks and hidden service comments (see below).

Named Sections #

To manipulate parts of the source code, Zuraffa Code Editor supports named sections. They are defined in the code by adding tags that Zuraffa Code Editor recognizes.

To define a named section in your source code, add comments to tag the start and the end of the section:

  1. Add comment [START section_name] to tag the beginning of the section.
  2. Add comment [END section_name] to tag the end of the section.

Here is an example to define a named section section1:

final text = '''
class MyClass {
    public static void main(String[] args) {// [START section1]
        int num = 5;
        System.out.println("Factorial of " + num + " is " + factorial(5));
    }// [END section1]
}
''';

To process named sections in the Zuraffa Code Editor, pass the named section parser to the controller:

final controller = CodeController(
  text: text,
  language: java,
  namedSectionParser: const BracketsStartEndNamedSectionParser(), // NEW
);

The example above creates a section named section1. The built-in BracketsStartEndNamedSectionParser class is designed to parse sections from the code comments using the above syntax. It also hides any single-line comment that has a section tag with the above syntax, although such comments are still present in the editor's hidden state and will be revealed when copying the text.

To customize section parsing using any other syntax, subclass AbstractNamedSectionParser.

Read-Only Code Blocks #

Zuraffa Code Editor allows you to define read-only code blocks. This may be useful for learning use cases when users are guided to modify certain code blocks while other code is meant to be protected from changes.

To make a named section read-only, pass a set of named sections to the controller.readOnlySectionNames:

controller.readOnlySectionNames = {'section1'};

This locks the given sections from modifications in the Zuraffa Code Editor. Any non-existent section names in this set are ignored. To make the code editable again, pass an updated set to controller.readOnlySectionNames.

When using this feature, text and value properties cannot be used to change the text programmatically because they have the same effect as the user input. This means that locking affects them as well.

To change a partially locked controller, set the fullText property.

Readonly blocks example

Advanced Code Blocks Folding #

Folding the First Comment/License #

Many code snippets contain a license as their first comment, which can distract readers. To fold the first comment, use:

controller.foldCommentAtLineZero();

This method has no effect if there is no comment starting at the first line.

Folding Imports #

In many languages, the editor recognizes sequential import lines and an optional package line as one foldable block. To fold such blocks:

controller.foldImports();

Named Sections #

The editor supports folding all blocks except for specific named sections. This helps the user focus on those sections while all source code is still there and can be expanded and copied by the user.

To fold all blocks except those overlapping with the given named sections:

controller.foldOutsideSections(['section1']);

Folding Specific Blocks #

To fold and unfold blocks at a given line number:

controller.foldAt(1);
controller.unfoldAt(1);

If there is no block at a given line, this has no effect.

Note: For the controller, line numbers start at 0 although the widget displays them starting at 1.

Accessing Folded Blocks #

To get the currently folded blocks, read controller.code.foldedBlocks.

Hiding Text #

The editor allows you to completely hide all code except for a specific named section. This is useful to achieve even more focus than with folding.

To hide all the code except the given named section:

controller.visibleSectionNames = {'section1'};

visibleSectionNames

When hiding text, the full text is still preserved and available via fullText property in the Zuraffa Code Editor.

Hiding text preserves line numbering, which is not possible by just showing a cropped snippet. Preserving hidden text is also useful if you later need to send the full code for further processing but still want to hide non-informative parts.

Hiding text also makes the entire editor read-only to prevent users from modifying the code, adding imports, etc. which may conflict with the hidden parts.

Only one visible section at a time is currently supported. The behavior of passing more than one section is undefined.

Autocompletion #

The editor suggests words as they are typed. Suggested words are:

  • All keywords of the current language.
  • All words already in the text.
  • Words set with controller.autocompleter.setCustomWords(['word1', 'word2'])

All those words are merged into an unstructured dictionary. The editor does not perform any syntax analysis, so it cannot tell if a given class really has the method the user is typing. This feature is meant to simplify typing, but should not be relied on when exploring classes and methods.

Suggestions example

To disable autocompletion:

controller.popupController.enabled = false;

Completion on a custom trigger #

The default rule is "suggest the words that match the word under the caret", which means a trigger made of spaces and punctuation can never fire: there is no word at the caret after >>.

Register a CustomAutocompleteTrigger to be asked instead. When its trigger appears on the caret's own line, the editor hands your callback the text typed after it and shows whatever you return — the keyword dictionary is bypassed for that evaluation.

controller.customAutocompleteTriggers = [
  CustomAutocompleteTrigger(
    trigger: ' >> ',
    getSuggestions: (prefix) => templates
        .where((template) => template.name.startsWith(prefix))
        .map((template) => template.name),
  ),
];

The callback may be asynchronous and is called on every keystroke, so you narrow your own list by filtering on the prefix you are handed. Returning an empty list hides the popup. The trigger may be anything — ' >> ', '@', '::' — and more than one can be registered at once; the first registered trigger whose text matches is the one that fires.

Accepting a suggestion replaces the text typed after the trigger, so a caret sitting right on >> commits the whole word. The commit does not re-arm the trigger that produced it.

With no trigger registered — the default — the keyword completer behaves exactly as it did before.

Shortcuts #

  • Indent (Tab)
  • Outdent (Shift-Tab)

indent outdent example

  • Comment out (Control-/)
  • Uncomment (Control-/)

comment out uncomment example

The editor also handles the standard editing keys:

  • Undo (Control-Z)
  • Redo (Control-Shift-Z)
  • Copy (Control-C)
  • Cut (Control-X)
  • Find (Control-F)

On macOS the usual Command key stands in for Control.

Migration Guides #

Contact Us #

Attribution #

Zuraffa Code Editor is a fork of akvelon/flutter-code-editor, used under its CC0 public domain dedication. This fork's own changes are dedicated to the public domain under the same terms.