Client API. The Codename One framework your app is built on: this runs on the device, not in a backend.

public class CodeEditor

  1. Object
  2. Component
  3. Container
  4. AbstractEditorComponent
  5. CodeEditor

ImplementsAnimation, Editable, EditorHost, Iterable<Component>, StyleListener

An IDE style source code editor with syntax highlighting, a line-number gutter and asynchronous code completion.

CodeEditor is built for editing source code on both touch devices (with the virtual keyboard) and desktops (with a physical keyboard). Code completion is driven by a CodeCompletionProvider, which can resolve proposals locally or from a remote language server.

Like RichTextArea, ports with low-level text input use the pure Codename One text engine (com.codename1.ui.editor) with a built-in incremental syntax highlighter. Ports without that input contract use an editable BrowserComponent fallback, and a port can transparently supply a native code editor instead.

Example

CodeEditor editor = new CodeEditor();
editor.setLanguage("java");
editor.setText("public class Main {\n\n}");
editor.setCompletionProvider((ed, code, cursor, results) -> {
    List<CodeCompletion> out = new ArrayList<>();
    out.add(new CodeCompletion("System.out.println(", "System.out.println()").setType("method"));
    results.onSucess(out);
});
form.add(BorderLayout.CENTER, editor);

Fields

public static final int KEY_ENTER = 1Enter or the keyboard’s action key, in an editor of one line.
public static final int KEY_TAB = 2Tab, in an editor of one line.
public static final int KEY_BACK_TAB = 3Shift+Tab, in an editor of one line.
public static final int KEY_ESCAPE = 4Escape, in an editor of one line.
public static final int KEY_UP = 5The up arrow, in an editor of one line.
public static final int KEY_DOWN = 6The down arrow, in an editor of one line.
public static final int KEY_F4 = 7F4, in an editor of one line, on a port with a keyboard that delivers it.

Constructors

public CodeEditor()Creates an empty code editor.
public CodeEditor(String language, String text)Creates a code editor initialized with the supplied source and language.

Methods

public void setText(String text)Replaces the entire editor content.
public void getText(SuccessCallback<String> callback)Retrieves the current source code.
public void setLanguage(String language)Sets the language used for syntax highlighting.
public String getLanguage()Returns the current highlighting language id.
public static void registerSyntaxHighlighter(String language, SyntaxHighlighter highlighter)Registers a syntax highlighter for a language id.
public static SyntaxHighlighter getRegisteredSyntaxHighlighter(String language)Returns the third-party syntax highlighter registered for a language, or null.
public void setTheme(String theme)Sets the color theme.
public String getTheme()Returns the current theme id.
public void setShowLineNumbers(boolean show)Shows or hides the line-number gutter.
public boolean isShowLineNumbers()Returns true if the line-number gutter is shown.
public void setTabSize(int tabSize)Sets the number of spaces inserted for a tab / used for indentation.
public int getTabSize()Returns the indentation width in spaces.
public void setReadOnly(boolean readOnly)Makes the editor read-only or editable.
public boolean isReadOnly()Returns true when the editor is read-only.
public void insertAtCursor(String text)Inserts text at the current caret position, replacing any active selection.
public void setProtectedRegionMarkers(String startMarker, String endMarker)Protects all text between matching marker lines from editing.
public void addProtectedEditListener(ActionListener listener)Registers a listener notified when an edit is refused because it falls inside a protected region.
public void removeProtectedEditListener(ActionListener listener)Removes a listener added by #addProtectedEditListener(ActionListener).
public void setCursorPosition(int offset)Moves the caret to a character offset, clamped by the editor backend to the document bounds.
public void getCursorPosition(SuccessCallback<Integer> callback)Retrieves the current caret character offset.
public void setDiagnostics(List<CodeDiagnostic> diagnostics)Sets the diagnostics (errors / warnings / hints) displayed in the editor as squiggly underlines, gutter markers and tooltips.
public void setCompletionProvider(CodeCompletionProvider provider)Sets the provider that supplies code completion proposals.
public void setSingleLine(boolean singleLine)Sets whether the editor holds one line, as a field does: the editor of a spreadsheet cell or a search box.
public boolean isSingleLine()Whether the editor holds one line.
public void addKeyListener(ActionListener l)Adds a listener told of the keys an editor of one line leaves to the application.
public void removeKeyListener(ActionListener l)Removes a listener added with #addKeyListener(ActionListener).
public CodeCompletionProvider getCompletionProvider()Returns the current completion provider, or null if none is set.

Inherited fields

Inherited methods

From Container

encloseIn, encloseIn, initLaf, getUIManager, setUIManager, isSurface, add, addAll, add, add, add, add, add, getLeadComponent, setLeadComponent, getLeadParent, keyPressed, keyReleased, getLayout, setLayout, invalidate, setShouldLayout, setShouldCalcPreferredSize, getLayoutWidth, getLayoutHeight, applyRTL, constrainWidthWhenScrollable, constrainHeightWhenScrollable, addComponent, addComponent, addComponent, addComponent, replaceAndWait, replaceAndWait, replace, replaceAndWait, replace, createReplaceTransition, isEnabled, setEnabled, removeComponent, cancelRepaints, flushReplace, removeAll, revalidateWithAnimationSafety, revalidate, revalidateLater, forceRevalidate, clearClientProperties, paint, paintGlass, layoutContainer, isSafeArea, setSafeArea, isSafeAreaRoot, getSafeAreaRoot, setSafeAreaRoot, getComponentCount, getComponentAt, getComponentIndex, contains, scrollComponentToVisible, getClosestComponentTo, getResponderAt, getComponentAt, findDropTargetAt, pointerPressed, calcPreferredSize, paramString, refreshTheme, isScrollableX, setScrollableX, isScrollableY, setScrollableY, getSideGap, getBottomGap, setScrollable, setCellRenderer, getScrollIncrement, setScrollIncrement, findFirstFocusable, dragInitiated, fireClicked, isSelectableInteraction, getGridPosY, paintComponentBackground, getGridPosX, animateHierarchyAndWait, createAnimateHierarchy, animateHierarchy, animateHierarchyFadeAndWait, createAnimateHierarchyFade, animateHierarchyFade, animateLayoutFadeAndWait, createAnimateLayoutFadeAndWait, animateLayoutFade, createAnimateLayoutFade, animateLayoutAndWait, animateLayout, updateTabIndices, createAnimateLayout, drop, createAnimateMotion, morph, morphAndWait, animateUnlayout, animateUnlayoutAndWait, createAnimateUnlayout, getChildrenAsList, iterator, iterator

From Component

setSameSize, isSetCursorSupported, parsePreferredSize, getDefaultDragTransparency, setDefaultDragTransparency, getEditingDelegate, setEditingDelegate, getCursor, setCursor, showNativeOverlay, hideNativeOverlay, updateNativeOverlay, getNativeOverlay, getAllStyles, getSameWidth, setSameWidth, getSameHeight, setSameHeight, getX, setX, getOuterX, getInnerX, getY, setY, getOuterY, getInnerY, isVisible, setVisible, getClientProperty, stripMarginAndPadding, putClientProperty, getDirtyRegion, setDirtyRegion, isOpaque, setOpaque, getWidth, setWidth, getOuterWidth, getInnerWidth, getHeight, setHeight, getOuterHeight, getInnerHeight, isDragRegion, getDragRegionStatus, getBaseline, getBaselineResizeBehavior, getPreferredSizeStr, setPreferredSizeStr, getPreferredSize, setPreferredSize, getScrollDimension, calcScrollSize, setScrollSize, getPreferredW, setPreferredW, getPreferredH, setPreferredH, getOuterPreferredH, getInnerPreferredH, getOuterPreferredW, getInnerPreferredW, setSize, getUIID, setUIID, setUIIDFinal, setUIID, getInlineAllStyles, setInlineAllStyles, getInlineSelectedStyles, setInlineSelectedStyles, getInlineUnselectedStyles, setInlineUnselectedStyles, getInlineDisabledStyles, setInlineDisabledStyles, getInlinePressedStyles, setInlinePressedStyles, remove, getParent, getOwner, setOwner, isOwnedBy, containsOrOwns, addFocusListener, removeFocusListener, addScrollListener, removeScrollListener, getSelectCommandText, setSelectCommandText, getLabelForComponent, setLabelForComponent, focusGained, focusLost, paintBackgrounds, paintShadows, getAbsoluteX, getAbsoluteY, isInClippingRegion, paintIntersectingComponentsAbove, paintScrollbars, paintScrollbarX, getScrollOpacity, getSelectedRect, paintScrollbarY, paintComponent, paintComponent, getBorder, getScrollable, paintBackground, isScrollable, getScrollX, setScrollX, getScrollY, setScrollY, onScrollX, onScrollY, getDraggedx, getDraggedy, contains, visibleBoundsContains, hasFixedPreferredSize, getBounds, getBounds, getVisibleBounds, getVisibleBounds, isFocusable, setFocusable, onSetFocusable, resetFocusable, getTabIndex, setTabIndex, getPreferredTabIndex, setPreferredTabIndex, isTraversable, setTraversable, handlesInput, setHandlesInput, consumesRawTextInput, hasFocus, setFocus, getComponentForm, getTopLevelContainer, repaint, repaint, longKeyPress, keyRepeated, registerForAnimation, deregisterFromAnimation, getAnimationManager, getScrollAnimationSpeed, setScrollAnimationSpeed, isBlockLead, setBlockLead, isIgnorePointerEvents, setIgnorePointerEvents, isRippleEffect, setRippleEffect, getInlineStylesTheme, setInlineStylesTheme, shouldRenderComponentSelection, isHideInLandscape, setHideInLandscape, createStyleAnimation, isSmoothScrolling, setSmoothScrolling, pointerHover, stopScrollMomentum, pointerHoverReleased, pointerHoverPressed, pinch, pinchReleased, pinch, rotation, isPinchBlocksDragAndDrop, setPinchBlocksDragAndDrop, pointerDragged, getDragImage, getDragTransparency, setDragTransparency, toImage, drawDraggedImage, draggingOver, dragEnter, dragExit, addPullToRefresh, setPullToRefresh, respondsToPointerEvents, pointerDragged, isStickyDrag, pointerPressed, isDragAndDropOperation, pointerReleased, longPointerPress, pointerReleased, setVerticalScrollBounds, setHorizontalScrollBounds, isVScrollThumbGrabbed, isHScrollThumbGrabbed, isVScrollThumbHover, isHScrollThumbHover, isTensileDragEnabled, setTensileDragEnabled, getTextSelectionSupport, addDropListener, removeDropListener, addDragOverListener, removeDragOverListener, isNativeDragSource, setNativeDragSource, getNativeDragOperation, setNativeDragOperation, createNativeDragOperation, isNativeDropTarget, setNativeDropTarget, getAcceptedDropMimeTypes, setAcceptedDropMimeTypes, getAcceptedDropActions, setAcceptedDropActions, canAcceptNativeDrop, nativeDragEnter, nativeDragOver, nativeDragExit, nativeDrop, addNativeDropListener, removeNativeDropListener, addNativeDragOverListener, removeNativeDragOverListener, dragFinished, addDragFinishedListener, addStateChangeListener, removeStateChangeListener, addPointerPressedListener, addLongPressListener, addContextMenuListener, removeContextMenuListener, addMouseWheelListener, removeMouseWheelListener, addStylusListener, removeStylusListener, getContextMenuCommands, setContextMenuCommands, mouseWheel, paintRippleOverlay, removePointerPressedListener, removeLongPressListener, removeDragFinishedListener, addPointerReleasedListener, removePointerReleasedListener, addPointerDraggedListener, removePointerDraggedListener, getDragSpeed, getStyle, getPressedStyle, getHoverStyle, setHoverStyle, isHovered, setHovered, setPressedStyle, initUnselectedStyle, initPressedStyle, initDisabledStyle, initSelectedStyle, getUnselectedStyle, setUnselectedStyle, getSelectedStyle, setSelectedStyle, getDisabledStyle, setDisabledStyle, installDefaultPainter, requestFocus, toString, refreshTheme, refreshTheme, isDragActivated, animate, scrollRectToVisible, scrollRectToVisible, paintBorder, paintBorderBackground, isCellRenderer, isScrollVisible, setScrollVisible, setIsScrollVisible, startEditingAsync, stopEditing, isEditing, laidOut, deinitialize, initComponent, isInitialized, setInitialized, styleChanged, getNextFocusDown, setNextFocusDown, getNextFocusUp, setNextFocusUp, getNextFocusLeft, setNextFocusLeft, getNextFocusRight, setNextFocusRight, getName, setName, initCustomStyle, deinitializeCustomStyle, isRTL, setRTL, isTactileTouch, isTactileTouch, setTactileTouch, getPropertyNames, getPropertyTypes, getPropertyTypeNames, getPropertyValue, setPropertyValue, paintLockRelease, paintLock, isSnapToGrid, setSnapToGrid, shouldBlockSideSwipe, shouldBlockSideSwipeLeft, shouldBlockSideSwipeRight, blocksSideSwipe, isFlatten, setFlatten, getTensileLength, setTensileLength, isGrabsPointerEvents, setGrabsPointerEvents, getScrollOpacityChangeSpeed, setScrollOpacityChangeSpeed, growShrink, isAlwaysTensile, setAlwaysTensile, isDraggable, setDraggable, isDropTarget, setDropTarget, isChildOf, isHideInPortrait, setHideInPortrait, getBindablePropertyNames, getBindablePropertyTypes, bindProperty, unbindProperty, getBoundPropertyValue, setBoundPropertyValue, getCloudBoundProperty, setCloudBoundProperty, getCloudDestinationProperty, setCloudDestinationProperty, getComponentState, setComponentState, setHidden, isHidden, setHidden, isHidden, announceForAccessibility, getAccessibilityText, setAccessibilityText, getSemantics, getAccessibilityNode, accessibilityChanged, accessibilityChanged, getTooltip, setTooltip

Field details

KEY_ENTER

public static final int KEY_ENTER = 1
Enter or the keyboard’s action key, in an editor of one line. See #setSingleLine(boolean).

KEY_TAB

public static final int KEY_TAB = 2
Tab, in an editor of one line.

KEY_BACK_TAB

public static final int KEY_BACK_TAB = 3
Shift+Tab, in an editor of one line.

KEY_ESCAPE

public static final int KEY_ESCAPE = 4
Escape, in an editor of one line.

KEY_UP

public static final int KEY_UP = 5
The up arrow, in an editor of one line.

KEY_DOWN

public static final int KEY_DOWN = 6
The down arrow, in an editor of one line.

KEY_F4

public static final int KEY_F4 = 7
F4, in an editor of one line, on a port with a keyboard that delivers it.

Constructor details

CodeEditor

public CodeEditor()
Creates an empty code editor.

CodeEditor

public CodeEditor(String language, String text)
Creates a code editor initialized with the supplied source and language.

Parameters

language String
the language id used for syntax highlighting (e.g. "java", "javascript", "kotlin", "css", "xml", "json", "python")
text String
the initial source code

Method details

setText

public void setText(String text)
Replaces the entire editor content.

Parameters

text String
the source code

getText

public void getText(SuccessCallback<String> callback)
Retrieves the current source code. The callback is invoked on the EDT.

Parameters

callback SuccessCallback<String>
receives the source code

setLanguage

public void setLanguage(String language)
Sets the language used for syntax highlighting.

Parameters

language String
the language id (e.g. "java", "javascript", "kotlin", "css", "xml", "json", "python")

getLanguage

public String getLanguage()
Returns the current highlighting language id.

registerSyntaxHighlighter

public static void registerSyntaxHighlighter(String language, SyntaxHighlighter highlighter)
Registers a syntax highlighter for a language id. Registration is global and affects existing editors the next time their language is set. Passing null removes a previous registration.

getRegisteredSyntaxHighlighter

public static SyntaxHighlighter getRegisteredSyntaxHighlighter(String language)
Returns the third-party syntax highlighter registered for a language, or null.

setTheme

public void setTheme(String theme)
Sets the color theme. Currently "light" and "dark" are supported.

Parameters

theme String
the theme id

getTheme

public String getTheme()
Returns the current theme id.

setShowLineNumbers

public void setShowLineNumbers(boolean show)
Shows or hides the line-number gutter.

Parameters

show boolean
true to show line numbers

isShowLineNumbers

public boolean isShowLineNumbers()
Returns true if the line-number gutter is shown.

setTabSize

public void setTabSize(int tabSize)
Sets the number of spaces inserted for a tab / used for indentation.

Parameters

tabSize int
the indentation width in spaces

getTabSize

public int getTabSize()
Returns the indentation width in spaces.

setReadOnly

public void setReadOnly(boolean readOnly)
Makes the editor read-only or editable. This is a convenience around AbstractEditorComponent#setEditable(boolean).

Parameters

readOnly boolean
true to prevent editing

isReadOnly

public boolean isReadOnly()
Returns true when the editor is read-only.

insertAtCursor

public void insertAtCursor(String text)
Inserts text at the current caret position, replacing any active selection.

Parameters

text String
the text to insert

setProtectedRegionMarkers

public void setProtectedRegionMarkers(String startMarker, String endMarker)
Protects all text between matching marker lines from editing. This is intended for generated source previews that contain explicit user-editable regions. Passing null clears protection.

addProtectedEditListener

public void addProtectedEditListener(ActionListener listener)
Registers a listener notified when an edit is refused because it falls inside a protected region. Without it a protected region is silent, and one covering most of the document is indistinguishable from an editor that ignores the keyboard. The event source is this editor and the event is fired on the EDT.

Parameters

listener ActionListener
invoked once per refused edit

removeProtectedEditListener

public void removeProtectedEditListener(ActionListener listener)
Removes a listener added by #addProtectedEditListener(ActionListener).

Parameters

listener ActionListener
the listener to remove

setCursorPosition

public void setCursorPosition(int offset)
Moves the caret to a character offset, clamped by the editor backend to the document bounds.

getCursorPosition

public void getCursorPosition(SuccessCallback<Integer> callback)
Retrieves the current caret character offset. The callback is invoked on the EDT.

Parameters

callback SuccessCallback<Integer>
receives the caret offset as an Integer

setDiagnostics

public void setDiagnostics(List<CodeDiagnostic> diagnostics)
Sets the diagnostics (errors / warnings / hints) displayed in the editor as squiggly underlines, gutter markers and tooltips. Pass an empty list (or null) to clear all diagnostics.

Parameters

diagnostics List<CodeDiagnostic>
the diagnostics to display

setCompletionProvider

public void setCompletionProvider(CodeCompletionProvider provider)
Sets the provider that supplies code completion proposals. Passing null disables completion.

Parameters

provider CodeCompletionProvider
the completion provider, or null to disable completion

setSingleLine

public void setSingleLine(boolean singleLine)
Sets whether the editor holds one line, as a field does: the editor of a spreadsheet cell or a search box. Enter, Tab, Shift+Tab, Escape and the up and down arrows then change nothing in the text; each is reported to the listeners of #addKeyListener(ActionListener) instead, which decide what it does (end the edit, move to the next field, pick from a list the application shows). Line numbers are hidden, and a line break typed, pasted or set becomes a space.

Parameters

singleLine boolean
true for one line

isSingleLine

public boolean isSingleLine()
Whether the editor holds one line.

Returns

true when it was set to one line

addKeyListener

public void addKeyListener(ActionListener l)
Adds a listener told of the keys an editor of one line leaves to the application. The event’s ActionEvent#getKeyEvent() is one of #KEY_ENTER, #KEY_TAB, #KEY_BACK_TAB, #KEY_ESCAPE, #KEY_UP, #KEY_DOWN and #KEY_F4.

Parameters

l ActionListener
the listener

removeKeyListener

public void removeKeyListener(ActionListener l)
Removes a listener added with #addKeyListener(ActionListener).

Parameters

l ActionListener
the listener

getCompletionProvider

public CodeCompletionProvider getCompletionProvider()
Returns the current completion provider, or null if none is set.