Skip to content

The Editor

rafageist edited this page Dec 4, 2026 · 6 revisions

The Editor

turboframe.ui.editor is a code editor in a Turbo Vision window: Textual's TextArea in the palette's colours, with what a desktop for code needs around it. Three mixins give your application the editor's flows: open and save (EditorMixin), Find and Replace (SearchMixin), and a language server (LspMixin).

Use it for editing files: a code editor, a configuration editor, any text the user changes and saves
Import from turboframe.ui.editor import CodeEditor, EditorWindow; from turboframe.ui.editing import EditorMixin; from turboframe.ui.lsp import LspMixin
Needs nothing more for the editor; textual[syntax] for syntax colours (tree-sitter grammars); the lsp extra for LspMixin
Extend CodeEditor's language class attributes; EditorWindow.EDITOR; the mixins' hooks
from pathlib import Path

from turboframe.files import read_source
from turboframe.ui.editor import CodeEditor, EditorWindow


class PythonEditor(CodeEditor):
    SMART_LANGUAGES = frozenset({"python"})    # a language server knows it: completion, hovers, Ctrl+click
    BREAKPOINT_LANGUAGES = frozenset({"python"})
    INDENT_AFTER = (":",)                       # Enter indents one level more after these


class Editor(EditorWindow):
    EDITOR = PythonEditor


window = Editor(read_source(Path("app.py")), root=Path("."), number=app.free_number())
app.insert_window(window)

With EditorMixin, set EDITOR_WINDOW = Editor and let open_file(path) do this (below).

The editor

CodeEditor(text, *, path=None, read_only=False, kind="editor", show_line_numbers=True) gives you:

  • the current palette's colours, which follow Options > Colors (see Themes and Colors); the syntax colours come from Textual's tree-sitter grammars when textual[syntax] is installed;
  • Borland's block selection, drawn in the selection's colours over the syntax;
  • Enter that keeps the line's indentation, and Esc that stays in the editor;
  • go_to(row, column=0, length=0), which selects and shows the place with its line in the middle and keeps a line that fits from its start;
  • over the text: a language server's diagnostics (set_diagnostics) and your own marks (set_marks([(start, end, "diff.add")]): a blamed line, a step of a trace);
  • in the gutter: git's changed lines (set_change_marks({row: "add" | "mod" | "del"})) and a debugger's breakpoints and current line (set_debug_marks(rows, current), see Debugger Windows), with glyphs on monochrome themes.

What you say about languages are class attributes:

Class attribute
LANGUAGES a file's suffix to Textual's language name (".py": "python"); None for plain text
SMART_LANGUAGES the languages a language server knows: completion, signatures, hovers, Ctrl+click
NAVIGABLE other languages where Ctrl+click still goes to a definition
BREAKPOINT_LANGUAGES a click on a line number toggles a breakpoint
INDENT_AFTER a line ending in one of these indents the next one more
NO_COMPLETION what Ctrl+Space says where there is no completion

Override register_languages() to register grammars Textual does not have (Textual's register_language). kind="output" gives the Output window's colours (see Log and Output Windows).

Completion, signatures, hovers

The editor hosts the completion list, a call's signature, a completion's documentation and a hover (see Completion), and asks your application for them, through methods it looks for on it:

Your application's method When
lsp_complete(editor, explicit) typing, or Ctrl+Space / Ctrl+N: answer with editor.show_completion(result, explicit)
lsp_document(editor, item) a completion is selected: editor.show_doc(lines)
lsp_signature_changed(editor) the cursor moved in a call: editor.show_signature(lines, mark)
lsp_go_to_definition(editor) Ctrl+click (where the terminal reports Ctrl with the mouse; bind F12 too)
toggle_breakpoint_at(editor, row) a click on a line number

LspMixin (below) implements the first four with a language server. Without these methods the editor is a plain one, and Ctrl+Space says that there is no completion in this file. show_hover(lines) shows a box under the cursor; hide_completion(), hide_signature(), hide_doc() and hide_hover() close them.

The window

EditorWindow(source=None, *, root=None, number=0, untitled=0, read_only=False) owns one file: the text it was read with (saved_text) and the file's stamp on disk (stamp, see Files). Its title is the path relative to root. It is dirty while the editor's text differs, and its bottom border shows * 12:5. saved(source) and moved(path) keep it in step with the disk; a window without a source is untitled (NONAME01; UNTITLED is the pattern). display_name is its name for messages; EDITOR is the editor's class.

It calls your application's editor_changed(window) and cursor_moved(window), and its close icon calls request_close(window), so your application can ask about unsaved changes. EditorMixin implements all three.

Newlines: LF

By default the editor holds the file's text as it is: a file with \r\n newlines gives \r\n in editor.text, and Save writes it back byte for byte. If your code counts offsets with \n newlines (a lexer, an outline, member text), set LF on your window class (since v0.2.1):

class Editor(EditorWindow):
    LF = True   # the editor holds \n text; Save writes the file's own newlines back

The window then reads with EditorWindow.read(path) (read_source(path, lf=True)), keeps the file's newline in window.newline, and EditorMixin's Save and Save as write it back. Git's reload of an open file and the explorer's members follow the same choice. An untitled window has no newline of its own and is saved as typed. See Files for the functions underneath.

OutputWindow and LogWindow, in the same module, show text to read: see Log and Output Windows.

API: turboframe.ui.editor.

The application's editing flows

Three mixins give your DesktopApp what a code editor's menus do. Each has an async dispatcher for your command worker (editor_command, search_command, lsp_command); the keys and menus stay yours. Application Mixins composes them with the others.

from textual import work

from turboframe.ui.app import DesktopApp
from turboframe.ui.editing import EditorMixin
from turboframe.ui.lsp import LspMixin
from turboframe.ui.searching import SearchMixin


class Workbench(LspMixin, SearchMixin, EditorMixin, DesktopApp):
    EDITOR_WINDOW = Editor                       # your EditorWindow
    LSP_SERVERS = (PYRIGHT,)                     # ServerSpecs (see LSP Helpers)

    @work(group="command")
    async def run_command(self, command: int, info: object = None) -> None:
        if not (await self.editor_command(command, info) or await self.search_command(command)
                or await self.lsp_command(command, info)):
            ...                                  # your own commands

search_command takes the command alone; editor_command and lsp_command take its info too (a path for Open, a window for Close).

EditorMixin

New (untitled NONAME windows, saved through Save as), Open, Save (atomic; asks before overwriting a file another program changed), Save as (asks before replacing; refuses a file open in another window), Save all, Close (asks about unsaved changes: Yes, No, Cancel), Go to line (CM_GOTO_LINE), and goto_location(path, start, end) for results windows. editor_command runs textual-vision's Command.NEW, OPEN, SAVE, SAVE_AS, SAVE_ALL, CLOSE and CM_GOTO_LINE (EDITOR_COMMANDS).

Hook Default
EDITOR_WINDOW EditorWindow: the class of the windows it opens
editor_root() the application's folder: the windows' titles are relative to it
place_editor(window) insert_window(window); tile the editors beside the explorer, for example
after_open(window), after_save(window), after_close(window) nothing; cooperative: extend with super()
editor_changed(window), cursor_moved(window) nothing; cooperative: extend with super()

Its methods, for your own commands: new_file(text=""), await open_file(path), await choose_and_open(), await save(window), await save_as(window), await save_all(), await close_editor(window), await close_window(window), await close_all(), await goto_line(window=None), goto_location(path, start, end=None), select_in(window, start, end), editors(), editor_for(path), active_editor(). Before exiting, if await self.close_all(): asks about every unsaved editor. save_changes(name) and overwrite_changed(name) are its two questions, as message boxes.

goto_location takes offsets counted with \n newlines, as Find in files' results, references and problems give them, whatever the file's newlines (select_in_lf; lf_location(text, offset) converts one).

API: turboframe.ui.editing.

SearchMixin

Find, Replace (with its prompt and Change all) and Search again over the active editor, wrapping around, sharing the last text with Find in files. See Search.

API: turboframe.ui.searching.

LspMixin

The language server in the editor (needs the lsp extra and EditorMixin). It starts the server a file needs when the first file of its language opens (the status line's spinner says so), tells it of every change once the keys pause, answers the editor's completion, signature, documentation and Ctrl+click, draws its errors and warnings, and gives:

Command
CM_LSP_DEFINITION Go to definition (F12, say); Ctrl+click does the same
CM_LSP_REFERENCES Find references: every use, in the References window
CM_LSP_HOVER Symbol information: what the server knows of the name under the cursor, in a box
CM_LSP_BACK Go back to where the last jump started (Alt+Left, say)
CM_LSP_PROBLEMS the Problems window: the errors and warnings of the open files
CM_LSP_RESTART stop the servers and start them again

Only an editor whose language is in its SMART_LANGUAGES (and that has a file) goes to a server; the server is the ServerSpec of LSP_SERVERS whose language is the editor's language (see LSP Helpers).

Completion with a slow server (since v0.3.0): each editor has one completion in flight. Typing on starts a newer one, and the older one is cancelled, in the server too. When an explicit completion (Ctrl+Space) gets no answer in time, it is asked once more while nothing changed (the same text and cursor), and then the user is told: "basedpyright did not answer in time: no completion", or "... could not complete: " for an error. A completion that opened by itself, while typing, shows nothing instead: no answer is never shown as an empty list.

Class attribute or hook Default
LSP_SERVERS (): your ServerSpecs; several may serve one language
lsp_store None. A store (see Settings and Recent Files) whose "lsp" chooses a server per language (its name, "auto": the first found, or "off"), and whose "lsp_commands" gives a server's command line by name
lsp_session_class LspSession: your subclass, to name your application
LSP_NAME, LSP_SIGILS, LSP_TRIGGERS what a completion replaces (a regular expression ending in $); characters a name may start with that are not part of it ("$"); characters after which the list opens by itself (".")
COMPLETION_TIMEOUT, COMPLETION_RETRY 10 seconds a completion waits for the server; 10 seconds more for the one retry of an explicit completion (Ctrl+Space) that ran out of time (since v0.3.0)
SYNC_AFTER, BACK_DEPTH, LSP_BAR 0.25 seconds of quiet before the server hears of a change; 50 places Go back remembers; the status line's progress bar's width
lsp_server_for(editor) (ServerSpec, command) for the editor's file, from the store's choice and find_command; None: no server
lsp_root(editor) the application's folder, else the file's folder
lsp_wants(editor) a file (not untitled) in one of its editor's SMART_LANGUAGES
lsp_trigger(editor, char) char is in LSP_TRIGGERS and the server says it triggers completion
lsp_in_call(editor) True: the server decides whether the cursor is still in the call (a language checks its parentheses)
lsp_quiet_here(editor, line) False: no list opens by itself here (a comment, a string)
lsp_no_server_message(editor) what the user is told, once per language, when no server serves it
lsp_diagnostics_filter(text, items) all of them: drop what your language's idioms make a server misread
lsp_clean(text) turboframe.lsp.clean_hover: a hover's text as the boxes show it
lsp_normalize(name) the name itself: how completion compares names
place_lsp_window(window) insert_window(window): the References and Problems windows

lsp_status(editor=None) says, for your status line, which server serves the active editor, or why none does; your application's update_status(), when it has one, is called when that changes. Before exiting: if await self.close_all(): await self.lsp_shutdown().

The pure parts are exported too: completion_result(items, text, offset, ...) (a server's items as a CompletionResult), signature_layout(found, width), reference_items(root, found, texts), and the ReferencesWindow and ProblemsWindow (LocationsWindows, see Windows and Lists).

API: turboframe.ui.lsp.

Clone this wiki locally