CodeEditor
Basic CodeEditor
Inherits: LayoutControl
Properties
-
autocompletion_enabled(Optional[bool]) –Whether autocompletion is enabled.
-
autocompletion_words(Optional[list[str]]) –Words offered by autocompletion.
-
autofocus(Optional[bool]) –Whether this editor should focus itself if nothing else is focused.
-
code_theme(Optional[Union[str, CodeTheme]]) –Highlighting theme or a named theme.
-
gutter_style(Optional[GutterStyle]) –Gutter styling.
-
language(Optional[str]) –Syntax highlighting language.
-
padding(Optional[PaddingValue]) –Padding around the editor.
-
read_only(Optional[bool]) –Whether the editor is read-only.
-
selection(Optional[TextSelection]) –Represents the current text selection or caret position in the editor.
-
text_style(Optional[TextStyle]) –Text style for the editor content.
-
value(Optional[str]) –Full text including folded sections and service comments.
Events
-
on_blur(Optional[ControlEventHandler[CodeEditor]]) –Called when the editor loses focus.
-
on_change(Optional[ControlEventHandler[CodeEditor]]) –Called when the editor text changes.
-
on_focus(Optional[ControlEventHandler[CodeEditor]]) –Called when the editor receives focus.
-
on_selection_change(Optional[EventHandler[TextSelectionChangeEvent[CodeEditor]]]) –Called when the text selection or caret position changes.
Methods
-
focus–Request focus for this editor.
-
fold_at–Fold the block starting at the given line number.
-
fold_comment_at_line_zero–Fold the comment block at line 0.
-
fold_imports–Fold import sections.
Usage#
Add flet-code-editor to your project dependencies:
Examples#
Basic example#
import flet_code_editor as fce
import flet as ft
CODE = """import flet as ft
def main(page: ft.Page):
counter = ft.Text("0", size=50, data=0)
def btn_click(e):
counter.data += 1
counter.value = str(counter.data)
counter.update()
page.floating_action_button = ft.FloatingActionButton(
icon=ft.Icons.ADD, on_click=btn_click
)
page.add(
ft.SafeArea(
ft.Container(
counter,
alignment=ft.Alignment.CENTER,
expand=True,
),
expand=True,
),
)
ft.run(main)
"""
def main(page: ft.Page):
page.add(
fce.CodeEditor(
language="python",
code_theme="atom-one-light",
# text_style=ft.TextStyle(font_family="monospace", size=14),
value=CODE,
expand=True,
on_change=lambda e: print("Changed:", e.data),
)
)
if __name__ == "__main__":
ft.run(main)
Selection handling#
import flet_code_editor as fce
import flet as ft
CODE = """import flet as ft
def main(page: ft.Page):
counter = ft.Text("0", size=50, data=0)
def btn_click(e):
counter.data += 1
counter.value = str(counter.data)
counter.update()
page.floating_action_button = ft.FloatingActionButton(
icon=ft.Icons.ADD, on_click=btn_click
)
page.add(
ft.SafeArea(
ft.Container(
counter,
alignment=ft.Alignment.CENTER,
expand=True,
),
expand=True,
),
)
ft.run(main)
"""
def main(page: ft.Page):
page.title = "CodeEditor selection"
max_selection_preview = 80
theme = fce.CodeTheme(
styles={
"keyword": ft.TextStyle(
color=ft.Colors.INDIGO_600, weight=ft.FontWeight.W_600
),
"string": ft.TextStyle(color=ft.Colors.RED_700),
"comment": ft.TextStyle(color=ft.Colors.GREY_600, italic=True),
}
)
text_style = ft.TextStyle(
font_family="monospace",
height=1.2,
)
gutter_style = fce.GutterStyle(
text_style=ft.TextStyle(
font_family="monospace",
height=1.2,
),
show_line_numbers=True,
show_folding_handles=True,
width=80,
)
def handle_selection_change(e: ft.TextSelectionChangeEvent[fce.CodeEditor]):
if e.selected_text:
normalized = " ".join(e.selected_text.split())
suffix = "..." if len(normalized) > max_selection_preview else ""
preview = normalized[:max_selection_preview]
selection.value = (
f"Selection ({len(e.selected_text)} chars): '{preview}{suffix}'"
)
else:
selection.value = "No selection."
selection_details.value = f"start={e.selection.start}, end={e.selection.end}"
caret.value = f"Caret position: {e.selection.end}"
async def select_all(e: ft.Event[ft.Button]):
await editor.focus()
editor.selection = ft.TextSelection(
base_offset=0,
extent_offset=len(editor.value or ""),
)
async def move_caret_to_start(e: ft.Event[ft.Button]):
await editor.focus()
editor.selection = ft.TextSelection(base_offset=0, extent_offset=0)
page.add(
ft.Column(
expand=True,
spacing=10,
controls=[
editor := fce.CodeEditor(
language="python",
code_theme=theme,
autocompletion_enabled=True,
autocompletion_words=[
"Container",
"Button",
"Text",
"Row",
"Column",
],
value=CODE,
text_style=text_style,
gutter_style=gutter_style,
on_selection_change=handle_selection_change,
expand=True,
),
selection := ft.Text("Select some text from the editor."),
selection_details := ft.Text(),
caret := ft.Text("Caret position: -"),
ft.Row(
spacing=10,
controls=[
ft.Button("Select all text", on_click=select_all),
ft.Button("Move caret to start", on_click=move_caret_to_start),
],
),
],
)
)
if __name__ == "__main__":
ft.run(main)
Folding and initial selection#
import flet_code_editor as fce
import flet as ft
CODE = """# 1
# 2
# 3
import json
import textwrap
print("Folding demo")
"""
def main(page: ft.Page):
editor = fce.CodeEditor(
language="python",
value=CODE,
selection=ft.TextSelection(base_offset=41, extent_offset=62),
autofocus=True,
expand=True,
on_selection_change=lambda e: print("Selection:", e),
)
async def fold_imports():
await editor.fold_imports()
async def fold_comment():
await editor.fold_comment_at_line_zero()
page.add(
ft.Row(
[
ft.Button("Fold imports", on_click=fold_imports),
ft.Button("Fold comment", on_click=fold_comment),
]
),
editor,
)
if __name__ == "__main__":
ft.run(main)
See also types:
- CodeTheme
- GutterStyle
Properties#
autocompletion_enabled
class-attribute
instance-attribute
#
Whether autocompletion is enabled.
autocompletion_words
class-attribute
instance-attribute
#
Words offered by autocompletion.
autofocus
class-attribute
instance-attribute
#
Whether this editor should focus itself if nothing else is focused.
code_theme
class-attribute
instance-attribute
#
Highlighting theme or a named theme.
Supported named themes
a11y-dark, a11y-light, agate, an-old-hope, androidstudio, arduino-light,
arta, ascetic, atelier-cave-dark, atelier-cave-light, atelier-dune-dark,
atelier-dune-light, atelier-estuary-dark, atelier-estuary-light,
atelier-forest-dark, atelier-forest-light, atelier-heath-dark,
atelier-heath-light, atelier-lakeside-dark, atelier-lakeside-light,
atelier-plateau-dark, atelier-plateau-light, atelier-savanna-dark,
atelier-savanna-light, atelier-seaside-dark, atelier-seaside-light,
atelier-sulphurpool-dark, atelier-sulphurpool-light, atom-one-dark,
atom-one-dark-reasonable, atom-one-light, brown-paper, codepen-embed,
color-brewer, darcula, dark, default, docco, dracula, far,
foundation, github, github-gist, gml, googlecode, gradient-dark,
grayscale, gruvbox-dark, gruvbox-light, hopscotch, hybrid, idea,
ir-black, isbl-editor-dark, isbl-editor-light, kimbie.dark, kimbie.light,
lightfair, magula, mono-blue, monokai, monokai-sublime, night-owl,
nord, obsidian, ocean, paraiso-dark, paraiso-light, pojoaque,
purebasic, qtcreator_dark, qtcreator_light, railscasts, rainbow,
routeros, school-book, shades-of-purple, solarized-dark, solarized-light,
sunburst, tomorrow, tomorrow-night, tomorrow-night-blue,
tomorrow-night-bright, tomorrow-night-eighties, vs, vs2015, xcode,
xt256, zenburn.
gutter_style
class-attribute
instance-attribute
#
gutter_style: Optional[GutterStyle] = None
Gutter styling.
language
class-attribute
instance-attribute
#
Syntax highlighting language.
Supported languages
1c, abnf, accesslog, actionscript, ada, angelscript, apache,
applescript, arcade, arduino, armasm, asciidoc, aspectj, autohotkey,
autoit, avrasm, awk, axapta, bash, basic, bnf, brainfuck, cal,
capnproto, ceylon, clean, clojure, clojure-repl, cmake, coffeescript,
coq, cos, cpp, crmsh, crystal, cs, csp, css, d, dart, delphi,
diff, django, dns, dockerfile, dos, dsconfig, dts, dust, ebnf,
elixir, elm, erb, erlang, erlang-repl, excel, fix, flix, fortran,
fsharp, gams, gauss, gcode, gherkin, glsl, gml, gn, go, golo,
gradle, graphql, groovy, haml, handlebars, haskell, haxe, hsp,
htmlbars, http, hy, inform7, ini, irpf90, isbl, java, javascript,
jboss-cli, json, julia, julia-repl, kotlin, lasso, ldif, leaf,
less, lisp, livecodeserver, livescript, llvm, lsl, lua, makefile,
markdown, mathematica, matlab, maxima, mel, mercury, mipsasm, mizar,
mojolicious, monkey, moonscript, n1ql, nginx, nimrod, nix, nsis,
objectivec, ocaml, openscad, oxygene, parser3, perl, pf, pgsql,
php, plaintext, pony, powershell, processing, profile, prolog,
properties, protobuf, puppet, purebasic, python, q, qml, r,
reasonml, rib, roboconf, routeros, rsl, ruby, ruleslanguage, rust,
sas, scala, scheme, scilab, scss, shell, smali, smalltalk, sml,
solidity, sqf, sql, stan, stata, step21, stylus, subunit, swift,
taggerscript, tap, tcl, tex, thrift, tp, twig, typescript, vala,
vbnet, vbscript, vbscript-html, verilog, vhdl, vim, vue, x86asm,
xl, xml, xquery, yaml, zephir.
padding
class-attribute
instance-attribute
#
padding: Optional[PaddingValue] = None
Padding around the editor.
read_only
class-attribute
instance-attribute
#
Whether the editor is read-only.
selection
class-attribute
instance-attribute
#
selection: Optional[TextSelection] = None
Represents the current text selection or caret position in the editor.
Setting this property updates the editor selection and may trigger
on_selection_change when the editor is focused.
text_style
class-attribute
instance-attribute
#
Text style for the editor content.
value
class-attribute
instance-attribute
#
Full text including folded sections and service comments.
Events#
on_blur
class-attribute
instance-attribute
#
on_blur: Optional[ControlEventHandler[CodeEditor]] = None
Called when the editor loses focus.
on_change
class-attribute
instance-attribute
#
on_change: Optional[ControlEventHandler[CodeEditor]] = None
Called when the editor text changes.
on_focus
class-attribute
instance-attribute
#
on_focus: Optional[ControlEventHandler[CodeEditor]] = None
Called when the editor receives focus.
on_selection_change
class-attribute
instance-attribute
#
on_selection_change: Optional[
EventHandler[TextSelectionChangeEvent[CodeEditor]]
] = None
Called when the text selection or caret position changes.



