euporie.core.app.app

Contain the main Application class which runs euporie.core.

Functions

abstractmethod(funcobj)

A decorator indicating abstract methods.

build_style(cp[, have_term_colors])

Create an application style based on the given color palette.

cast(typ, val)

Cast a value to a type.

create_app_session([input, output])

Create a separate AppSession.

create_input([stdin, always_prefer_tty])

Create the appropriate Input object for the current os/environment.

create_output([stdout, always_prefer_tty])

Return an Output instance for the command line.

get_style_by_name(name)

Get Pygments style, caching the result.

load_auto_suggest_bindings()

Key bindings for accepting auto suggestion text.

load_cpr_bindings()

load_emacs_bindings()

Some e-macs extensions.

load_emacs_search_bindings()

load_emacs_shift_selection_bindings()

Bindings to select text with shift + cursor movements

load_ptk_basic_bindings()

load_ptk_mouse_bindings()

Key bindings, required for mouse support.

load_registered_bindings(*names[, config])

Assign key-bindings to commands based on a dictionary.

load_vi_search_bindings()

merge_key_bindings(bindings)

Merge multiple Keybinding objects together.

merge_style_transformations(...)

Merge multiple transformations together.

merge_styles(styles)

Merge multiple Style objects.

overload(func)

Decorator for overloaded functions/methods.

register_bindings(bindings)

Update the key-binding registry.

set_app(app)

Context manager that sets the given Application active in an AppSession.

setup_logs([config])

Configure the logger for euporie.

style_from_pygments_cls(pygments_style_cls)

Shortcut to create a Style instance from a Pygments style class and a style dictionary.

to_container(container)

Make sure that the given object is a Container.

to_filter(bool_or_filter)

Accept both booleans and Filters as input and turn it into a Filter.

Classes

ABC()

Helper class that provides a standard way to create an ABC using inheritance.

Application([layout, style, ...])

The main Application class! This glues everything together.

BaseApp([title, set_title, leave_graphics, ...])

All euporie apps.

BaseStyle()

Abstract base class for prompt_toolkit styles.

ChainedList(*lists)

A list-like class which chains multiple lists.

CliFormatter(command[, languages])

Format using an external command.

ColorDepth(*values)

Possible color depth values for the output.

ColorPalette()

Define a collection of colors.

CompletionsMenu([max_height, scroll_offset, ...])

A custom completions menu.

Condition(func)

Turn any callable into a Filter.

ConditionalKeyBindings(key_bindings[, filter])

Wraps around a KeyBindings. Disable/enable all the key bindings according to the given (additional) filter.::.

ConditionalStyleTransformation(...)

Apply the style transformation depending on a condition.

ConfigurableApp()

An application with configuration.

CursorConfig()

Determine which cursor mode to use.

DummyStyle()

A style that doesn't style anything.

EditingMode(*values)

Enum(new_class_name, /, names, *[, module, ...])

Create a collection of name/value pairs.

Event(sender[, handler])

Simple event to which event handlers can be attached. For instance::.

ExtraEditingMode(*values)

Additional editing modes.

Float(content[, top, right, bottom, left, ...])

Float for use in a FloatContainer.

FloatContainer(content, floats[, modal, ...])

A FloatContainer which uses :py`BoundedWritePosition`s.

KeyProcessor(*args, **kwargs)

A subclass of prompt_toolkit's keyprocessor.

Layout(container[, focused_element])

The layout for a prompt_toolkit Application.

LspClient(name, command[, languages, settings])

A client for communicating with LSP servers.

MicroState()

Mutable class to hold Micro specific state.

Point(x, y)

PtkVt100_Output

alias of Vt100_Output

PurePath(*args, **kwargs)

Base class for manipulating paths without I/O.

Renderer(style, output[, full_screen, ...])

Renderer with modifications.

SetDefaultColorStyleTransformation(fg, bg)

Set default foreground/background color for output that doesn't specify anything.

Shadow(body)

Draw a shadow underneath/behind this container.

Style(style_rules)

Create a Style instance from a list of style rules.

SwapLightAndDarkStyleTransformation()

Turn dark colors into light colors and the other way around.

ViState()

Mutable class to hold the state of the Vi navigation.

Vt100Parser(*args, **kwargs)

A Vt100Parser which checks input against additional key patterns.

Vt100_Output(stdout, get_size[, term, ...])

A Vt100 output which enables SGR pixel mouse positioning.

WeakSet([data])

WeakValueDictionary([other])

Mapping class that references values weakly.

Window(*args, **kwargs)

Container that holds a control.

partial(func, /, *args, **keywords)

Create a new function with partial application of the given arguments and keywords.

class euporie.core.app.app.BaseApp(title: str | None = None, set_title: bool = True, leave_graphics: FilterOrBool = True, extend_renderer_height: FilterOrBool = False, extend_renderer_width: FilterOrBool = False, enable_page_navigation_bindings: FilterOrBool | None = True, **kwargs: Any)

Bases: ConfigurableApp, Application, ABC

All euporie apps.

The base euporie application class.

This subclasses the prompt_toolkit.application.Application class, so application wide methods can be easily added.

add_tab(tab: Tab) None

Add a tab to the current tabs list.

base_styles = (<prompt_toolkit.styles.style.Style object>, <prompt_toolkit.styles.style.Style object>, <prompt_toolkit.styles.style.Style object>, <prompt_toolkit.styles.style.Style object>, <prompt_toolkit.styles.style.Style object>)
async cancel_and_wait_for_background_tasks() None

Cancel all background tasks, and wait for the cancellation to complete. If any of the background tasks raised an exception, this will also propagate the exception.

(If we had nurseries like Trio, this would be the __aexit__ of a nursery.)

property cell_size_px: tuple[int, int]

Get the pixel size of a single terminal cell.

cleanup(signum: int, frame: FrameType | None) None

Restore the state of the terminal on unexpected exit.

cleanup_closed_tab(tab: Tab) None

Remove a tab container from the current instance of the app.

Parameters:

tab – The closed instance of the tab container

close_tab(tab: Tab | None = None) None

Close a notebook tab.

Parameters:

tab – The instance of the tab to close. If None, the currently selected tab will be closed.

property color_depth: ColorDepth

The active ColorDepth.

The current value is determined as follows:

  • If a color depth was given explicitly to this application, use that value.

  • Otherwise, fall back to the color depth that is reported by the Output implementation. If the Output class was created using output.defaults.create_output, then this value is coming from the $PROMPT_TOOLKIT_COLOR_DEPTH environment variable.

color_palette: ColorPalette
config: Config
cpr_not_supported_callback() None

Called when we don’t receive the cursor position response in time.

create_background_task(coroutine: Coroutine[Any, Any, None]) Task[None]

Start a background task (coroutine) for the running application. When the Application terminates, unfinished background tasks will be cancelled.

Given that we still support Python versions before 3.11, we can’t use task groups (and exception groups), because of that, these background tasks are not allowed to raise exceptions. If they do, we’ll call the default exception handler from the event loop.

If at some point, we have Python 3.11 as the minimum supported Python version, then we can use a TaskGroup (with the lifetime of Application.run_async(), and run run the background tasks in there.

This is not threadsafe.

create_merged_style() BaseStyle

Generate a new merged style for the application.

Using a dynamic style has serious performance issues, so instead we update the style on the renderer directly when it changes in self.update_style

Returns:

Return a combined style to use for the application

property current_buffer: Buffer

The currently focused Buffer.

(This returns a dummy Buffer when none of the actual buffers has the focus. In this case, it’s really not practical to check for None values or catch exceptions every time.)

property current_search_state: SearchState

Return the current SearchState. (The one for the focused BufferControl.)

do_style_update(caller: Application | None = None) None

Update the application’s style when the syntax theme is changed.

draw(render_as_done: bool = True) None

Draw the app without focus, leaving the cursor below the drawn output.

exit() None
exit(*, result: _AppResult, style: str = '') None
exit(*, exception: BaseException | type[BaseException], style: str = '') None

Shut down any remaining LSP clients at exit.

focus_tab(tab: Tab) None

Make a tab visible and focuses it.

get_dialog(name: str) Dialog | None

Return a dialog instance, creating it if it does not exist.

get_edit_mode() EditingMode

Return the editing mode enum defined in the configuration.

get_file_tab(path: Path) type[Tab] | None

Return the tab to use for a file path.

get_file_tabs(path: Path) list[TabRegistryEntry]

Return the tab to use for a file path.

get_language_lsps(language: str) list[LspClient]

Return the approprrate LSP clients for a given language.

get_used_style_strings() list[str]

Return a list of used style strings. This is helpful for debugging, and for writing a new Style.

async classmethod interact(ssh_session: PromptToolkitSSHSession) None

Run the app asynchronously for the hub SSH server.

invalidate() None

Thread safe way of sending a repaint trigger to the input event loop.

property invalidated: bool

True when a redraw operation has been scheduled.

property is_done: bool
property is_running: bool

True when the application is currently active/running.

key_processor

The InputProcessor instance.

classmethod launch() None

Launch the app.

abstractmethod load_container() AnyContainer

Load the root container for this application.

Returns:

The root container for this app

classmethod load_input() Input

Create the input for this application to use.

Ensures the TUI app always tries to run in a TTY.

Returns:

A prompt-toolkit input instance

load_key_bindings() None

Load the application’s key bindings.

classmethod load_output() Output

Create the output for this application to use.

Ensures the TUI app always tries to run in a TTY.

Returns:

A prompt-toolkit output instance

classmethod load_settings() None

Load all known settings for this class.

mouse_position: Point
name: str | None = None
open_file(path: Path, read_only: bool = False, tab_class: type[Tab] | None = None) None

Create a tab for a file.

Parameters:
  • path – The file path of the notebook file to open

  • read_only – If true, the file should be opened read_only

  • tab_class – The tab type to use to open the file

open_files() None

Open the files defined in the configuration.

pause_rendering() None

Block rendering, but allows input to be processed.

The first line prevents the display being drawn, and the second line means the key processor continues to process keys. We need this as we need to wait for the results of terminal queries which come in as key events.

This is used to prevent flicker when we update the styles based on terminal feedback.

post_load() None

Allow subclasses to define additional loading steps.

pre_run(app: Application | None = None) None

Call during the ‘pre-run’ stage of application loading.

print_text(text: AnyFormattedText, style: BaseStyle | None = None) None

Print a list of (style_str, text) tuples to the output. (When the UI is running, this method has to be called through run_in_terminal, otherwise it will destroy the UI.)

Parameters:
  • text – List of (style_str, text) tuples.

  • style – Style class to use. Defaults to the active style in the CLI.

quoted_insert

Quoted insert. This flag is set if we go into quoted insert mode.

refresh() None

Reset all tabs.

render_counter

Render counter. This one is increased every time the UI is rendered. It can be used as a key for caching certain information during one rendering.

reset() None

Reset everything, for reading the next input.

resume_rendering() None

Reume rendering the app.

run(pre_run: Callable[[], None] | None = None, set_exception_handler: bool = True, handle_sigint: bool = True, in_thread: bool = False, inputhook: Callable[[InputHookContext], None] | None = None) _AppResult

A blocking ‘run’ call that waits until the UI is finished.

This will run the application in a fresh asyncio event loop.

Parameters:
  • pre_run – Optional callable, which is called right after the “reset” of the application.

  • set_exception_handler – When set, in case of an exception, go out of the alternate screen and hide the application, display the exception, and wait for the user to press ENTER.

  • in_thread – When true, run the application in a background thread, and block the current thread until the application terminates. This is useful if we need to be sure the application won’t use the current event loop (asyncio does not support nested event loops). A new event loop will be created in this background thread, and that loop will also be closed when the background thread terminates. When this is used, it’s especially important to make sure that all asyncio background tasks are managed through get_appp().create_background_task(), so that unfinished tasks are properly cancelled before the event loop is closed. This is used for instance in ptpython.

  • handle_sigint – Handle SIGINT signal. Call the key binding for Keys.SIGINT. (This only works in the main thread.)

async run_async(pre_run: Callable[[], None] | None = None, set_exception_handler: bool = True, handle_sigint: bool = True, slow_callback_duration: float = 0.5) _AppResult

Run the application.

async run_system_command(command: str, wait_for_enter: bool = True, display_before_text: AnyFormattedText = '', wait_text: str = 'Press ENTER to continue...') None

Run system command (While hiding the prompt. When finished, all the output will scroll above the prompt.)

Parameters:
  • command – Shell command to be executed.

  • wait_for_enter – FWait for the user to press enter, when the command is finished.

  • display_before_text – If given, text to be displayed before the command executes.

Returns:

A Future object.

shutdown_lsps() None

Shut down all the remaining LSP servers.

suspend_to_background(suspend_group: bool = True) None

(Not thread safe – to be called from inside the key bindings.) Suspend process.

Parameters:

suspend_group – When true, suspend the whole process group. (This is the default, and probably what you want.)

property syntax_theme: str

Calculate the current syntax theme.

property tab: Tab | None

Return the currently selected tab container object.

property tab_idx: int

Get the current tab index.

property tab_registry: list[TabRegistryEntry]

Return the tab registry.

property term_size_px: tuple[int, int]

The dimensions of the terminal in pixels.

timeoutlen

Like Vim’s timeoutlen option. This can be None or a float. For instance, suppose that we have a key binding AB and a second key binding A. If the uses presses A and then waits, we don’t handle this binding yet (unless it was marked ‘eager’), because we don’t know what will follow. This timeout is the maximum amount of time that we wait until we call the handlers anyway. Pass None to disable this timeout.

property title: str

The application’s title.

ttimeoutlen

When to flush the input (For flushing escape keys.) This is important on terminals that use vt100 input. We can’t distinguish the escape key from for instance the left-arrow key, if we don’t know what follows after “x1b”. This little timer will consider “x1b” to be escape if nothing did follow in this time span. This seems to work like the ttimeoutlen option in Vim.

update_edit_mode(setting: Setting | None = None) None

Set the keybindings for editing mode.

update_style(query: Setting | None = None) None

Tell the application the style is out of date.

vi_state

Vi state. (For Vi key bindings.)

class euporie.core.app.app.ExtraEditingMode(*values)

Bases: str, Enum

Additional editing modes.

MICRO = 'MICRO'
capitalize()

Return a capitalized version of the string.

More specifically, make the first character have upper case and the rest lower case.

casefold()

Return a version of the string suitable for caseless comparisons.

center(width, fillchar=' ', /)

Return a centered string of length width.

Padding is done using the specified fill character (default is a space).

count()

Return the number of non-overlapping occurrences of substring sub in string S[start:end].

Optional arguments start and end are interpreted as in slice notation.

encode(encoding='utf-8', errors='strict')

Encode the string using the codec registered for encoding.

encoding

The encoding in which to encode the string.

errors

The error handling scheme to use for encoding errors. The default is ‘strict’ meaning that encoding errors raise a UnicodeEncodeError. Other possible values are ‘ignore’, ‘replace’ and ‘xmlcharrefreplace’ as well as any other name registered with codecs.register_error that can handle UnicodeEncodeErrors.

endswith()

Return True if the string ends with the specified suffix, False otherwise.

suffix

A string or a tuple of strings to try.

start

Optional start position. Default: start of the string.

end

Optional stop position. Default: end of the string.

expandtabs(tabsize=8)

Return a copy where all tab characters are expanded using spaces.

If tabsize is not given, a tab size of 8 characters is assumed.

find()

Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end].

Optional arguments start and end are interpreted as in slice notation. Return -1 on failure.

format(*args, **kwargs)

Return a formatted version of the string, using substitutions from args and kwargs. The substitutions are identified by braces (‘{’ and ‘}’).

format_map(mapping, /)

Return a formatted version of the string, using substitutions from mapping. The substitutions are identified by braces (‘{’ and ‘}’).

index()

Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end].

Optional arguments start and end are interpreted as in slice notation. Raises ValueError when the substring is not found.

isalnum()

Return True if the string is an alpha-numeric string, False otherwise.

A string is alpha-numeric if all characters in the string are alpha-numeric and there is at least one character in the string.

isalpha()

Return True if the string is an alphabetic string, False otherwise.

A string is alphabetic if all characters in the string are alphabetic and there is at least one character in the string.

isascii()

Return True if all characters in the string are ASCII, False otherwise.

ASCII characters have code points in the range U+0000-U+007F. Empty string is ASCII too.

isdecimal()

Return True if the string is a decimal string, False otherwise.

A string is a decimal string if all characters in the string are decimal and there is at least one character in the string.

isdigit()

Return True if the string is a digit string, False otherwise.

A string is a digit string if all characters in the string are digits and there is at least one character in the string.

isidentifier()

Return True if the string is a valid Python identifier, False otherwise.

Call keyword.iskeyword(s) to test whether string s is a reserved identifier, such as “def” or “class”.

islower()

Return True if the string is a lowercase string, False otherwise.

A string is lowercase if all cased characters in the string are lowercase and there is at least one cased character in the string.

isnumeric()

Return True if the string is a numeric string, False otherwise.

A string is numeric if all characters in the string are numeric and there is at least one character in the string.

isprintable()

Return True if all characters in the string are printable, False otherwise.

A character is printable if repr() may use it in its output.

isspace()

Return True if the string is a whitespace string, False otherwise.

A string is whitespace if all characters in the string are whitespace and there is at least one character in the string.

istitle()

Return True if the string is a title-cased string, False otherwise.

In a title-cased string, upper- and title-case characters may only follow uncased characters and lowercase characters only cased ones.

isupper()

Return True if the string is an uppercase string, False otherwise.

A string is uppercase if all cased characters in the string are uppercase and there is at least one cased character in the string.

join(iterable, /)

Concatenate any number of strings.

The string whose method is called is inserted in between each given string. The result is returned as a new string.

Example: ‘.’.join([‘ab’, ‘pq’, ‘rs’]) -> ‘ab.pq.rs’

ljust(width, fillchar=' ', /)

Return a left-justified string of length width.

Padding is done using the specified fill character (default is a space).

lower()

Return a copy of the string converted to lowercase.

lstrip(chars=None, /)

Return a copy of the string with leading whitespace removed.

If chars is given and not None, remove characters in chars instead.

static maketrans()

Return a translation table usable for str.translate().

If there is only one argument, it must be a dictionary mapping Unicode ordinals (integers) or characters to Unicode ordinals, strings or None. Character keys will be then converted to ordinals. If there are two arguments, they must be strings of equal length, and in the resulting dictionary, each character in x will be mapped to the character at the same position in y. If there is a third argument, it must be a string, whose characters will be mapped to None in the result.

partition(sep, /)

Partition the string into three parts using the given separator.

This will search for the separator in the string. If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it.

If the separator is not found, returns a 3-tuple containing the original string and two empty strings.

removeprefix(prefix, /)

Return a str with the given prefix string removed if present.

If the string starts with the prefix string, return string[len(prefix):]. Otherwise, return a copy of the original string.

removesuffix(suffix, /)

Return a str with the given suffix string removed if present.

If the string ends with the suffix string and that suffix is not empty, return string[:-len(suffix)]. Otherwise, return a copy of the original string.

replace(old, new, /, count=-1)

Return a copy with all occurrences of substring old replaced by new.

count

Maximum number of occurrences to replace. -1 (the default value) means replace all occurrences.

If the optional argument count is given, only the first count occurrences are replaced.

rfind()

Return the highest index in S where substring sub is found, such that sub is contained within S[start:end].

Optional arguments start and end are interpreted as in slice notation. Return -1 on failure.

rindex()

Return the highest index in S where substring sub is found, such that sub is contained within S[start:end].

Optional arguments start and end are interpreted as in slice notation. Raises ValueError when the substring is not found.

rjust(width, fillchar=' ', /)

Return a right-justified string of length width.

Padding is done using the specified fill character (default is a space).

rpartition(sep, /)

Partition the string into three parts using the given separator.

This will search for the separator in the string, starting at the end. If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it.

If the separator is not found, returns a 3-tuple containing two empty strings and the original string.

rsplit(sep=None, maxsplit=-1)

Return a list of the substrings in the string, using sep as the separator string.

sep

The separator used to split the string.

When set to None (the default value), will split on any whitespace character (including n r t f and spaces) and will discard empty strings from the result.

maxsplit

Maximum number of splits. -1 (the default value) means no limit.

Splitting starts at the end of the string and works to the front.

rstrip(chars=None, /)

Return a copy of the string with trailing whitespace removed.

If chars is given and not None, remove characters in chars instead.

split(sep=None, maxsplit=-1)

Return a list of the substrings in the string, using sep as the separator string.

sep

The separator used to split the string.

When set to None (the default value), will split on any whitespace character (including n r t f and spaces) and will discard empty strings from the result.

maxsplit

Maximum number of splits. -1 (the default value) means no limit.

Splitting starts at the front of the string and works to the end.

Note, str.split() is mainly useful for data that has been intentionally delimited. With natural text that includes punctuation, consider using the regular expression module.

splitlines(keepends=False)

Return a list of the lines in the string, breaking at line boundaries.

Line breaks are not included in the resulting list unless keepends is given and true.

startswith()

Return True if the string starts with the specified prefix, False otherwise.

prefix

A string or a tuple of strings to try.

start

Optional start position. Default: start of the string.

end

Optional stop position. Default: end of the string.

strip(chars=None, /)

Return a copy of the string with leading and trailing whitespace removed.

If chars is given and not None, remove characters in chars instead.

swapcase()

Convert uppercase characters to lowercase and lowercase characters to uppercase.

title()

Return a version of the string where each word is titlecased.

More specifically, words start with uppercased characters and all remaining cased characters have lower case.

translate(table, /)

Replace each character in the string using the given translation table.

table

Translation table, which must be a mapping of Unicode ordinals to Unicode ordinals, strings, or None.

The table must implement lookup/indexing via __getitem__, for instance a dictionary or list. If this operation raises LookupError, the character is left untouched. Characters mapped to None are deleted.

upper()

Return a copy of the string converted to uppercase.

zfill(width, /)

Pad a numeric string with zeros on the left, to fill a field of the given width.

The string is never truncated.