Class CodeEditor
- All Implemented Interfaces:
Animation, Editable, EditorHost, StyleListener, Iterable<Component>
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);
-
Field Summary
FieldsModifier and TypeFieldDescriptionstatic final intShift+Tab, in an editor of one line.static final intThe down arrow, in an editor of one line.static final intEnter or the keyboard's action key, in an editor of one line.static final intEscape, in an editor of one line.static final intF4, in an editor of one line, on a port with a keyboard that delivers it.static final intTab, in an editor of one line.static final intThe up arrow, in an editor of one line.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
ConstructorsConstructorDescriptionCreates an empty code editor.CodeEditor(String language, String text) Creates a code editor initialized with the supplied source and language. -
Method Summary
Modifier and TypeMethodDescriptionvoidAdds a listener told of the keys an editor of one line leaves to the application.voidaddProtectedEditListener(ActionListener listener) Registers a listener notified when an edit is refused because it falls inside a protected region.Returns the current completion provider, or null if none is set.voidgetCursorPosition(SuccessCallback<Integer> callback) Retrieves the current caret character offset.Returns the current highlighting language id.static SyntaxHighlightergetRegisteredSyntaxHighlighter(String language) Returns the third-party syntax highlighter registered for a language, or null.intReturns the indentation width in spaces.voidgetText(SuccessCallback<String> callback) Retrieves the current source code.getTheme()Returns the current theme id.voidinsertAtCursor(String text) Inserts text at the current caret position, replacing any active selection.booleanReturns true when the editor is read-only.booleanReturns true if the line-number gutter is shown.booleanWhether the editor holds one line.static voidregisterSyntaxHighlighter(String language, SyntaxHighlighter highlighter) Registers a syntax highlighter for a language id.voidRemoves a listener added with#addKeyListener(ActionListener).voidremoveProtectedEditListener(ActionListener listener) Removes a listener added by#addProtectedEditListener(ActionListener).voidsetCompletionProvider(CodeCompletionProvider provider) Sets the provider that supplies code completion proposals.voidsetCursorPosition(int offset) Moves the caret to a character offset, clamped by the editor backend to the document bounds.voidsetDiagnostics(List<CodeDiagnostic> diagnostics) Sets the diagnostics (errors / warnings / hints) displayed in the editor as squiggly underlines, gutter markers and tooltips.voidsetLanguage(String language) Sets the language used for syntax highlighting.voidsetProtectedRegionMarkers(String startMarker, String endMarker) Protects all text between matching marker lines from editing.voidsetReadOnly(boolean readOnly) Makes the editor read-only or editable.voidsetShowLineNumbers(boolean show) Shows or hides the line-number gutter.voidsetSingleLine(boolean singleLine) Sets whether the editor holds one line, as a field does: the editor of a spreadsheet cell or a search box.voidsetTabSize(int tabSize) Sets the number of spaces inserted for a tab / used for indentation.voidReplaces the entire editor content.voidSets the color theme.Methods inherited from class AbstractEditorComponent
addChangeListener, addReadyListener, blurEditor, command, editorChanged, fireEditorEvent, focusEditor, isEditable, isEditorReady, isNativeEditor, isTextInputSupported, onReady, query, removeChangeListener, removeReadyListener, setEditable, startTextInput, stopTextInput, updateTextInputStateMethods 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, updateTabIndicesMethods inherited from class Component
accessibilityChanged, accessibilityChanged, addContextMenuListener, addDragFinishedListener, addDragOverListener, addDropListener, addFocusListener, addLongPressListener, addMouseWheelListener, addNativeDragOverListener, addNativeDropListener, addPointerDraggedListener, addPointerPressedListener, addPointerReleasedListener, addPullToRefresh, addScrollListener, addStateChangeListener, addStylusListener, animate, announceForAccessibility, bindProperty, blocksSideSwipe, calcScrollSize, canAcceptNativeDrop, consumesRawTextInput, contains, containsOrOwns, createNativeDragOperation, createStyleAnimation, deinitialize, deinitializeCustomStyle, deregisterFromAnimation, dragEnter, dragExit, dragFinished, draggingOver, drawDraggedImage, focusGained, focusLost, getAbsoluteX, getAbsoluteY, getAcceptedDropActions, getAcceptedDropMimeTypes, getAccessibilityNode, getAccessibilityText, getAllStyles, getAnimationManager, getBaseline, getBaselineResizeBehavior, getBindablePropertyNames, getBindablePropertyTypes, getBorder, getBoundPropertyValue, getBounds, getBounds, getClientProperty, getCloudBoundProperty, getCloudDestinationProperty, getComponentForm, getComponentState, getContextMenuCommands, getCursor, getDefaultDragTransparency, getDirtyRegion, getDisabledStyle, getDraggedx, getDraggedy, getDragImage, getDragRegionStatus, getDragSpeed, getDragTransparency, getEditingDelegate, getHeight, getHoverStyle, getInlineAllStyles, getInlineDisabledStyles, getInlinePressedStyles, getInlineSelectedStyles, getInlineStylesTheme, getInlineUnselectedStyles, getInnerHeight, getInnerPreferredH, getInnerPreferredW, getInnerWidth, getInnerX, getInnerY, getLabelForComponent, getName, getNativeDragOperation, 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, getSemantics, getStyle, getTabIndex, getTensileLength, getTextSelectionSupport, getTooltip, getTopLevelContainer, 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, isHovered, isHScrollThumbGrabbed, isHScrollThumbHover, isIgnorePointerEvents, isInClippingRegion, isInitialized, isNativeDragSource, isNativeDropTarget, isOpaque, isOwnedBy, isPinchBlocksDragAndDrop, isRippleEffect, isRTL, isScrollable, isScrollVisible, isSetCursorSupported, isSmoothScrolling, isSnapToGrid, isStickyDrag, isTactileTouch, isTactileTouch, isTensileDragEnabled, isTraversable, isVisible, isVScrollThumbGrabbed, isVScrollThumbHover, keyRepeated, laidOut, longKeyPress, longPointerPress, mouseWheel, nativeDragEnter, nativeDragExit, nativeDragOver, nativeDrop, 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, registerForAnimation, remove, removeContextMenuListener, removeDragFinishedListener, removeDragOverListener, removeDropListener, removeFocusListener, removeLongPressListener, removeMouseWheelListener, removeNativeDragOverListener, removeNativeDropListener, removePointerDraggedListener, removePointerPressedListener, removePointerReleasedListener, removeScrollListener, removeStateChangeListener, removeStylusListener, repaint, repaint, requestFocus, resetFocusable, respondsToPointerEvents, rotation, scrollRectToVisible, scrollRectToVisible, setAcceptedDropActions, setAcceptedDropMimeTypes, setAccessibilityText, setAlwaysTensile, setBlockLead, setBoundPropertyValue, setCloudBoundProperty, setCloudDestinationProperty, setComponentState, setContextMenuCommands, setCursor, setDefaultDragTransparency, setDirtyRegion, setDisabledStyle, setDraggable, setDragTransparency, setDropTarget, setEditingDelegate, setFlatten, setFocus, setFocusable, setGrabsPointerEvents, setHandlesInput, setHeight, setHidden, setHidden, setHideInLandscape, setHideInPortrait, setHorizontalScrollBounds, setHovered, setHoverStyle, setIgnorePointerEvents, setInitialized, setInlineAllStyles, setInlineDisabledStyles, setInlinePressedStyles, setInlineSelectedStyles, setInlineStylesTheme, setInlineUnselectedStyles, setIsScrollVisible, setLabelForComponent, setName, setNativeDragOperation, setNativeDragSource, setNativeDropTarget, 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, stopScrollMomentum, stripMarginAndPadding, styleChanged, toImage, toString, unbindProperty, updateNativeOverlay, visibleBoundsContainsMethods inherited from class Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, waitMethods inherited from interface Iterable
forEach, spliterator
-
Field Details
-
KEY_ENTER
public static final int KEY_ENTEREnter or the keyboard's action key, in an editor of one line. See#setSingleLine(boolean).- See Also:
-
KEY_TAB
public static final int KEY_TABTab, in an editor of one line.- See Also:
-
KEY_BACK_TAB
public static final int KEY_BACK_TABShift+Tab, in an editor of one line.- See Also:
-
KEY_ESCAPE
public static final int KEY_ESCAPEEscape, in an editor of one line.- See Also:
-
KEY_UP
public static final int KEY_UPThe up arrow, in an editor of one line.- See Also:
-
KEY_DOWN
public static final int KEY_DOWNThe down arrow, in an editor of one line.- See Also:
-
KEY_F4
public static final int KEY_F4F4, in an editor of one line, on a port with a keyboard that delivers it.- See Also:
-
-
Constructor Details
-
CodeEditor
public CodeEditor()Creates an empty code editor. -
CodeEditor
-
-
Method Details
-
setText
Replaces the entire editor content.
Parameters
text: the source code
-
getText
Retrieves the current source code. The callback is invoked on the EDT.
Parameters
callback: receives the source code
-
setLanguage
Sets the language used for syntax highlighting.
Parameters
language: the language id (e.g."java","javascript","kotlin","css","xml","json","python")
-
getLanguage
Returns the current highlighting language id. -
registerSyntaxHighlighter
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
Returns the third-party syntax highlighter registered for a language, or null. -
setTheme
Sets the color theme. Currently
"light"and"dark"are supported.Parameters
theme: the theme id
-
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
Inserts text at the current caret position, replacing any active selection.
Parameters
text: the text to insert
-
setProtectedRegionMarkers
-
addProtectedEditListener
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: invoked once per refused edit
-
removeProtectedEditListener
Removes a listener added by
#addProtectedEditListener(ActionListener).Parameters
listener: 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
Retrieves the current caret character offset. The callback is invoked on the EDT.
Parameters
callback: receives the caret offset as an Integer
-
setDiagnostics
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
-
setCompletionProvider
Sets the provider that supplies code completion proposals. Passing null disables completion.
Parameters
provider: 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: true for one line
-
isSingleLine
public boolean isSingleLine()Whether the editor holds one line.
Returns
true when it was set to one line
-
addKeyListener
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_DOWNand#KEY_F4.Parameters
l: the listener
-
removeKeyListener
Removes a listener added with
#addKeyListener(ActionListener).Parameters
l: the listener
-
getCompletionProvider
Returns the current completion provider, or null if none is set.
-