# Class CodeEditor

java.lang.Object
com.codename1.ui.Component
com.codename1.ui.Container
com.codename1.ui.AbstractEditorComponent
com.codename1.ui.CodeEditor

All Implemented Interfaces:
  `Animation, Editable, StyleListener, Iterable<Component>`

public class CodeEditor extends AbstractEditorComponent

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`, the editor uses a 100% cross platform `BrowserComponent` backend by default and can be transparently upgraded to a native code editor by a platform port. The built-in editing surface is fully self contained and offline. When the optional bundled CodeMirror library is present (the Codename One build server adds it automatically when, and only when, an app actually uses `CodeEditor`) the editor upgrades to CodeMirror for richer language support; otherwise it uses a lightweight built-in highlighter.

##### 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);

- ## Field Summary

  ### Fields inherited from class Component

  `BASELINE, BOTTOM, BRB_CENTER_OFFSET, BRB_CONSTANT_ASCENT, BRB_CONSTANT_DESCENT, BRB_OTHER, CENTER, CROSSHAIR_CURSOR, DEFAULT_CURSOR, DRAG_REGION_IMMEDIATELY_DRAG_X, DRAG_REGION_IMMEDIATELY_DRAG_XY, DRAG_REGION_IMMEDIATELY_DRAG_Y, DRAG_REGION_LIKELY_DRAG_X, DRAG_REGION_LIKELY_DRAG_XY, DRAG_REGION_LIKELY_DRAG_Y, DRAG_REGION_NOT_DRAGGABLE, DRAG_REGION_POSSIBLE_DRAG_X, DRAG_REGION_POSSIBLE_DRAG_XY, DRAG_REGION_POSSIBLE_DRAG_Y, E_RESIZE_CURSOR, HAND_CURSOR, LEFT, MOVE_CURSOR, N_RESIZE_CURSOR, NE_RESIZE_CURSOR, NW_RESIZE_CURSOR, RIGHT, S_RESIZE_CURSOR, SE_RESIZE_CURSOR, SW_RESIZE_CURSOR, TEXT_CURSOR, TOP, W_RESIZE_CURSOR, WAIT_CURSOR`

- ## Constructor Summary

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

- ## Method Summary

  Modifier and Type
  Method
  Description
  `CodeCompletionProvider`
  `getCompletionProvider()`
  Returns the current completion provider, or null if none is set.
  `void`
  `getCursorPosition(SuccessCallback<Integer> callback)`
  Retrieves the current caret character offset.
  `String`
  `getEngineURL()`
  Returns the custom engine URL set with `#setEngineURL(String)`, or null when the built-in engine is used.
  `String`
  `getLanguage()`
  Returns the current highlighting language id.
  `int`
  `getTabSize()`
  Returns the indentation width in spaces.
  `void`
  `getText(SuccessCallback<String> callback)`
  Retrieves the current source code.
  `String`
  `getTheme()`
  Returns the current theme id.
  `void`
  `insertAtCursor(String text)`
  Inserts text at the current caret position, replacing any active selection.
  `boolean`
  `isReadOnly()`
  Returns true when the editor is read-only.
  `boolean`
  `isShowLineNumbers()`
  Returns true if the line-number gutter is shown.
  `void`
  `setCompletionProvider(CodeCompletionProvider provider)`
  Sets the provider that supplies code completion proposals.
  `void`
  `setDiagnostics(List<CodeDiagnostic> diagnostics)`
  Sets the diagnostics (errors / warnings / hints) displayed in the editor as squiggly underlines, gutter markers and tooltips.
  `void`
  `setEngineURL(String url)`
  Points the editor at a custom engine page bundled in the app's HTML hierarchy (loaded with `BrowserComponent#setURLHierarchy(String)`) instead of the self contained built-in engine. The custom page must implement the same `window.cn1editor` command/query bridge and post the same `cn1ed:` events, which lets an application back `CodeEditor` with a richer editor (e.g. CodeMirror or Monaco) when maximum polish is required while keeping the exact same Java API. Must be set before the editor is shown.
  `void`
  `setLanguage(String language)`
  Sets the language used for syntax highlighting.
  `void`
  `setReadOnly(boolean readOnly)`
  Makes the editor read-only or editable.
  `void`
  `setShowLineNumbers(boolean show)`
  Shows or hides the line-number gutter.
  `void`
  `setTabSize(int tabSize)`
  Sets the number of spaces inserted for a tab / used for indentation.
  `void`
  `setText(String text)`
  Replaces the entire editor content.
  `void`
  `setTheme(String theme)`
  Sets the color theme.

  ### Methods inherited from class AbstractEditorComponent

  `addChangeListener, addReadyListener, blurEditor, command, fireEditorEvent, focusEditor, getInternalBrowser, isEditable, isEditorReady, isNativeEditor, onReady, query, removeChangeListener, removeReadyListener, setEditable`

  ### Methods inherited from class Container

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

  ### Methods inherited from class Component

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

  ### Methods inherited from class Object

  `clone, equals, getClass, hashCode, notify, notifyAll, wait, wait, wait`

  ### Methods inherited from interface Iterable

  `forEach`

- ## 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`: the language id used for syntax highlighting (e.g. `"java"`, `"javascript"`, `"kotlin"`, `"css"`, `"xml"`, `"json"`, `"python"`)

    - `text`: the initial source code

- ## Method Details

  - ### setText

    public void setText(String text)

    Replaces the entire editor content.

    ###### Parameters

    - `text`: the source code

  - ### getText

    public void getText(SuccessCallback<String> callback)

    Retrieves the current source code. The callback is invoked on the EDT.

    ###### Parameters

    - `callback`: receives the source code

  - ### setLanguage

    public void setLanguage(String language)

    Sets the language used for syntax highlighting.

    ###### Parameters

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

  - ### getLanguage

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

  - ### setTheme

    public void setTheme(String theme)

    Sets the color theme. Currently `"light"` and `"dark"` are supported.

    ###### Parameters

    - `theme`: 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`: 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`: 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`: 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`: the text to insert

  - ### getCursorPosition

    public void getCursorPosition(SuccessCallback<Integer> callback)

    Retrieves the current caret character offset. The callback is invoked on the EDT.

    ###### Parameters

    - `callback`: 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`: the diagnostics to display

  - ### setEngineURL

    public void setEngineURL(String url)

    Points the editor at a custom engine page bundled in the app's HTML hierarchy (loaded with `BrowserComponent#setURLHierarchy(String)`) instead of the self contained built-in engine. The custom page must implement the same `window.cn1editor` command/query bridge and post the same `cn1ed:` events, which lets an application back `CodeEditor` with a richer editor (e.g. CodeMirror or Monaco) when maximum polish is required while keeping the exact same Java API. Must be set before the editor is shown.

    ###### Parameters

    - `url`: an app-hierarchy URL such as `"/my-editor/index.html"`, or null to use the built-in engine

  - ### getEngineURL

    public String getEngineURL()
    Returns the custom engine URL set with `#setEngineURL(String)`, or null when the built-in engine is used.

  - ### setCompletionProvider

    public void setCompletionProvider(CodeCompletionProvider provider)

    Sets the provider that supplies code completion proposals. Passing null disables completion.

    ###### Parameters

    - `provider`: the completion provider, or null to disable completion

  - ### getCompletionProvider

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