API Reference#
Source docstrings are the canonical reference, rendered here with Sphinx autodoc. The file-session API owns explicit file persistence and recovery. The embedded text editor retains caller-owned persistence. See Usage and integration for both workflows.
Build this reference with hatch run docs:build from the directory containing
pyproject.toml. Sphinx autodoc imports the Python APIs, and Napoleon renders
their Google-style docstrings. Update canonical comments in src/edital/;
do not edit generated files in docs/_build/. See Installation for setup.
Embedded text API#
Validator is the exported callback type Callable[[str], str | None].
It receives candidate text synchronously and returns None for acceptance
or a diagnostic string to keep editing. The canonical behavior is documented
by edital.edit_text() below; unexpected callback exceptions propagate
after terminal cleanup.
Edital: standalone file editing and transactional embedded text editing.
Textual is imported only when a session starts. Embedded callers retain ownership
of validation and persistence; Edital provides explicit file-session behavior.
- class edital.TuiEditor#
Text-session adapter for applications embedding the default editor.
- edit(initial_text='', *, title='Text editor', validator=None)#
Run a blocking session with the same contract as
edit_text().- Return type:
- Parameters:
initial_text (str)
title (str)
validator (Callable[[str], str | None] | None)
- edital.edit_text(initial_text='', *, title='Text editor', validator=None)#
Block until Save & close or cancellation in an interactive terminal.
A validator returns an error message to keep editing, or
Noneto accept. Unexpected validator exceptions propagate after terminal cleanup. Text uses uniform LF or CRLF separators and is returned without reserialization.- Parameters:
initial_text (
str) – Exact text to preload, including any trailing newline.title (
str) – Display label; this is not a destination file path.validator (
Callable[[str],str|None] |None) – Optional synchronous callback receiving candidate text.
- Return type:
- Returns:
An
EditResultwith outcomeacceptedand the accepted text, or outcomecancelledand no text. Unchanged and empty text can be accepted.- Raises:
ValueError – If initial line endings are mixed or use bare carriage returns.
RuntimeError – If input/output are not interactive terminals or the session terminates without an explicit outcome.
Notes
F2 or F3 validates and accepts text; Ctrl+Q cancels, with discard confirmation when text has changed. Escape dismisses the active interaction and otherwise does nothing. F4 opens Find and F5 opens Find/Replace. The caller is responsible for persisting accepted text; this function does not write files or initialize standalone configuration. There is no implicit external-editor fallback.
- class edital.EditResult(outcome, text=None)#
An explicit outcome; accepted empty text is distinct from cancellation.
- Parameters:
outcome (
Literal['accepted','cancelled']) –acceptedorcancelled.text (
str|None) – Required for acceptance, including an empty string. Must beNonefor cancellation.
- Raises:
ValueError – If outcome and text are inconsistent.
File-session API#
- class edital.Edital(**configuration_overrides)#
Prepare file documents and launch a blocking multi-tab editor with
run.Keyword settings override user YAML. Opening and saving work without a TUI.
auto_restore=Truerestores snapshots atrun, not during preparation.closeremoves one document;exitrequests whole-editor termination. Files are UTF-8 with uniform LF/CRLF. Recovery covers orderly exit, not crashes.- Parameters:
**configuration_overrides (
Any) – Validated instance settings:auto_save(nonnegative milliseconds),cache,prompt,auto_restore(booleans), andfocus_color,draft_color,conflict_color(hexadecimal colors). The two state colors also acceptNone.- Raises:
ValueError – If user YAML or an effective setting is invalid.
OSError – If the user configuration cannot be initialized or read.
Notes
Construction creates a missing user configuration file and its parent directory, but does not import Textual, restore snapshots, or launch a UI.
Examples
>>> editor = Edital(auto_save=0) >>> draft = editor.new() >>> draft.text = "Notes\n" >>> editor.save(draft, path="notes.txt")
- property files: tuple[SessionFile, ...]#
Read-only ordered view of documents in the current session.
- property cache: tuple[CacheFile, ...]#
Available persisted recovery entries; reading does not restore them.
- open(*paths)#
Load existing files or prepare named drafts without launching a UI.
- Parameters:
*paths (
str|Path) – Destinations, expanded and resolved against the working directory. Existing filesystem aliases select the same document.- Return type:
tuple[SessionFile,...]- Returns:
Handles in argument order, with the last selected as active. Reopened paths return existing handles; missing paths do not create files.
- Raises:
OSError – If an existing file cannot be read.
UnicodeError – If file content is not valid UTF-8.
ValueError – If line endings are mixed or contain bare CR separators.
Notes
Opening is sequential; a later failure leaves earlier documents open.
- new()#
Prepare one unnamed draft without creating a destination.
- Return type:
- save(document, *, path=None)#
Write current text and remove its associated recovery snapshot.
- Parameters:
document (
SessionFile|str|Path) – Open handle or destination path identifying a document.path (
str|Path|None) – Optional new destination; required for an unnamed draft. An existing destination’s contents are replaced.
- Return type:
None- Returns:
None.
- Raises:
ValueError – If the document is not open, has an unresolved conflict, lacks a destination, targets another open document, or contains unsupported line endings.
OSError – If writing the file or removing its snapshot fails.
UnicodeError – If text cannot be encoded as UTF-8.
Notes
A successful write updates the destination, saved baseline, and autosave eligibility before snapshot removal. A snapshot-removal failure therefore does not undo the file write.
- save_all()#
Save sequentially; missing draft destinations/errors stop the operation.
- Return type:
None
- close(document, *, cache=False)#
Remove one document; explicit caching overrides instance configuration.
Without caching, dirty headless removal raises
ConfirmationRequiredwhen prompts are enabled. Setprompt=Falsefor deliberate discard. Closing the last document does not exit the application.- Parameters:
document (
SessionFile|str|Path) – Open handle or destination path.cache (
bool) – Preserve unsaved content in recovery before detaching it. Defaults to false regardless of the configured exit policy.
- Raises:
ConfirmationRequired – If uncached removal requires confirmation.
ValueError – If the document is not open.
OSError – If preserving or removing its snapshot fails.
- Return type:
None
- exit(*, cache=None)#
Preserve or discard all documents, then request editor termination.
- Parameters:
cache (
bool|None) – Whether to preserve unsaved content.Noneuses the instance’s configured caching policy.- Raises:
ConfirmationRequired – If uncached discard requires confirmation.
OSError – If recovery persistence fails; documents remain attached.
- Return type:
None
Notes
Snapshots are processed before any documents are detached. A later failure can leave earlier snapshot changes persisted. Successful exit empties the session and sets
exitedto true; it does not revert content already written by explicit save or autosave.
- restore()#
Restore snapshots without consuming them or overwriting destinations.
Conflicting documents remain blocked until
resolve_recoveryis called or the TUI collects a recovery choice. Repeated restoration, including automatic restoration atrun, is idempotent.- Return type:
tuple[SessionFile,...]- Returns:
Restored handles in snapshot order, including handles already associated with those snapshots.
- Raises:
ValueError – If a snapshot or destination has invalid content.
OSError – If reading recovery entries or destination files fails.
UnicodeError – If destination content is not valid UTF-8.
Notes
Restoration is sequential, so earlier restored documents remain if a later entry fails. Inspect each handle’s
conflictbefore saving; automatic saving skips unresolved conflicts.
- resolve_recovery(document, choice)#
Resolve a cached-version conflict without writing destination files.
- Parameters:
document (
SessionFile|str|Path) – Conflicting open document handle or destination.choice (
Literal['recovered','disk','draft']) –recoveredrestores cached text for its original destination;diskdiscards the snapshot and adopts destination text (or an empty named draft when missing);draftkeeps cached text in a separate unnamed draft with its recovery association retained.
- Raises:
ValueError – If the choice is invalid, no conflict exists, or another unsaved document blocks the choice. Rejected choices preserve the snapshot and document state.
OSError – If preparing the destination-version document fails.
- Return type:
None
- clear_cache()#
Purge snapshots without prompting or changing open documents/files.
Confirmation and the force flag belong to CLI purge, not this headless API.
- Return type:
None
- list(cache=False)#
List session documents, optionally followed by all recovery entries.
- Parameters:
cache (
bool) – Include persisted snapshots, even when associated with an already-open document. Reading does not restore or consume them.- Return type:
tuple[SessionFile|CacheFile,...]- Returns:
Open handles in session order, followed by snapshots when requested.
- autosave()#
Perform one autosave tick without scheduling a timer.
Only modified, previously loaded or saved documents without recovery conflicts are eligible. A configured interval of zero disables this call.
- Return type:
tuple[tuple[SessionFile,Exception],...]- Returns:
(document, exception)pairs for caught filesystem or validation failures. Other eligible documents are still attempted; an empty tuple means no caught failures, including when no writes are needed.
- run(*, create_draft=False)#
Restore when configured, then launch the blocking file-editor TUI.
auto_restoreis evaluated at launch, never during construction/open. Existing restoration is idempotent, including earlier explicit calls.create_draftadds a fallback only if no documents remain after restore; the CLI requests this, while API callers default to an empty workspace. Interactive terminal input and output are required.- Parameters:
create_draft (
bool) – Create an unnamed draft if the workspace is empty after any configured restoration.- Raises:
RuntimeError – If stdin or stdout is not an interactive terminal.
ValueError – If automatic recovery encounters invalid content.
OSError – If automatic recovery cannot read persisted content.
- Return type:
None
- class edital.EditalSession#
Ordered documents with active selection and headless save operations.
This lower-level API does not load user configuration, preserve recovery snapshots, or confirm discards. Use
edital.Editalfor those policies.activeis the selected handle, orNonein an empty session.- property files: tuple[SessionFile, ...]#
Read-only ordered view of open documents.
- draft_name()#
Allocate a stable draft label without reusing closed labels.
- Return type:
str
- find_path(path)#
Find an already-open destination using normalized filesystem identity.
- Return type:
SessionFile|None- Parameters:
path (str | Path)
- resolve(document)#
Resolve a current handle or destination; stale handles raise ValueError.
- Return type:
- Parameters:
document (SessionFile | str | Path)
- add(document)#
Attach a prepared document and select it.
- Return type:
- Parameters:
document (SessionFile)
- new()#
Prepare a fresh unnamed draft without writing anything.
- Return type:
- open(*paths)#
Load existing UTF-8 documents or prepare named drafts for missing paths.
- Parameters:
*paths (
str|Path) – Destinations expanded and resolved against the working directory. Existing aliases reuse the same open handle.- Return type:
tuple[SessionFile,...]- Returns:
Handles in argument order; the final handle becomes active.
- Raises:
OSError – If an existing destination cannot be read.
UnicodeError – If its content is not valid UTF-8.
ValueError – If line endings are mixed or contain bare CR separators.
Notes
Missing destinations are not created. Earlier opens remain attached if a later path fails.
- save(document, *, path=None)#
Save to an explicit or existing destination; never open a UI prompt.
- Parameters:
document (
SessionFile|str|Path) – Open handle or destination path.path (
str|Path|None) – Optional replacement destination, required for unnamed drafts.
- Return type:
None- Returns:
None.
- Raises:
ValueError – If the document is not open, has a recovery conflict, lacks a destination, targets another open document, or has unsupported line endings.
OSError – If writing fails.
UnicodeError – If text cannot be encoded as UTF-8.
Notes
Successful writing replaces destination contents, updates the path and baseline, and enables autosave. It does not remove recovery snapshots; the higher-level
Edital.saveowns that cleanup.
- save_all()#
Save sequentially; an error does not undo previously completed saves.
- Return type:
None
- remove(document)#
Detach a document after its caller has handled preservation/confirmation.
- Return type:
None- Parameters:
document (SessionFile | str | Path)
- move(document, index)#
Move an open document to a zero-based position without changing selection.
- Parameters:
document (
SessionFile|str|Path) – An open handle or destination path.index (
int) – Target position in the ordered document view.
- Raises:
ValueError – If the document is not open or the index is out of range.
- Return type:
None
- class edital.SessionFile(path=None, text='', baseline='', autosave_eligible=False, newline='\\n', id=<factory>, draft_name='draft', recovery_id=None, conflict=False, disk_text=None)#
An addressable document whose dirty state compares text to its saved baseline.
pathis an optional destination;autosave_eligiblerecords successful loading or saving, not merely path existence. Text uses exact LF/CRLF strings.- Parameters:
path (Path | None)
text (str)
baseline (str)
autosave_eligible (bool)
newline (str)
id (str)
draft_name (str)
recovery_id (str | None)
conflict (bool)
disk_text (str | None)
- path#
Destination, or
Nonefor an unnamed draft.
- text#
Current editable content; assigning it does not write a file.
- baseline#
Saved or loaded content used to compute
modified.
- autosave_eligible#
Whether a successful load or save established a file.
- newline#
Recorded line-ending convention (LF or CRLF).
- id#
Stable document identifier, independent of its path or tab position.
- draft_name#
Stable display label for an unnamed draft.
- recovery_id#
Associated snapshot identifier, if any.
- conflict#
Whether recovery requires an explicit choice before saving.
- disk_text#
Destination text observed during conflicting recovery, or
Nonewhen unavailable or not needed.
Notes
The handle is mutable even though the session’s
filestuple is not. Use session operations to change destinations, order, or membership; direct construction does not validate text or normalize paths.- property modified: bool#
Whether current text differs from the last successful saved revision.
- property needs_save_as: bool#
Whether an interactive save must first collect a destination.
- property unsaved: bool#
Whether content needs saving, including pristine never-saved drafts.
- class edital.CacheFile(id, path, text, baseline, newline, autosave_eligible, timestamp, version=1)#
Immutable recovery metadata and exact content, separate from open handles.
- Parameters:
id (str)
path (Path | None)
text (str)
baseline (str)
newline (str)
autosave_eligible (bool)
timestamp (str)
version (int)
- id#
Snapshot identifier associated with a session document.
- path#
Original destination, or
Nonefor an unnamed draft.
- text#
Cached unsaved content.
- baseline#
Last loaded or saved content when the snapshot was taken.
- newline#
Recorded LF or CRLF convention.
- autosave_eligible#
Whether the original document had been loaded or saved.
- timestamp#
Snapshot creation time in UTC ISO 8601 form.
- version#
Snapshot format version, currently 1.
Reading a snapshot does not restore it, consume it, or write its destination.
- property size: int#
Content size in UTF-8 bytes, excluding snapshot metadata.
- class edital.EditalConf(**overrides)#
Load defaults, user YAML, and explicit overrides, in that order.
setmodifies this instance only.pathexposes the user configuration.auto_restoreis a boolean evaluated at editing launch, independently of exit caching. Packageddefaults.ymlinitializes the userconf.yml. Invalid settings raiseValueError; filesystem failures raiseOSError.- Parameters:
**overrides (
Any) – Validated settings that take precedence over user YAML. Seeedital.Editalfor supported names and value types.
Notes
Construction creates the configuration parent directory and initializes a missing file, including for headless callers. Existing files are not rewritten to fill in omitted defaults.
- get(key, default=None)#
Read an effective setting, returning
defaultfor unknown keys.- Return type:
Any- Parameters:
key (str)
default (Any)
- set(key, value)#
Validate and update an instance setting without rewriting user YAML.
- Parameters:
key (
str) – Supported configuration name.value (
Any) – Value matching that setting’s type and constraints.
- Raises:
ValueError – If the key or value is invalid; the previous value remains.
- Return type:
None
Notes
After validation, listeners run synchronously, even for an unchanged value. Listener exceptions propagate after the setting is updated.
- subscribe(listener)#
Subscribe to synchronous notifications after a setting changes.
- Parameters:
listener (
Callable[[str],None]) – Callback receiving the name of each setting passed toset. Read the new value withget.- Return type:
Callable[[],None]- Returns:
A zero-argument function removing this subscription. Call it once; repeated removal raises
ValueError.
- exception edital.ConfirmationRequired#
A headless destructive operation requires interactive discard confirmation.