id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
6,831 | from __future__ import annotations
import logging
from colorsys import hls_to_rgb, rgb_to_hls
from functools import partial
from typing import TYPE_CHECKING
from prompt_toolkit.cache import SimpleCache
from prompt_toolkit.styles.defaults import default_ui_style
from prompt_toolkit.styles.style import Style
class ColorPaletteColor:
"""A representation of a color with adjustment methods."""
_cache: SimpleCache[
tuple[str, float, float, float, bool], ColorPaletteColor
] = SimpleCache()
def __init__(self, base: str, _base_override: str = "") -> None:
"""Create a new color.
Args:
base: The base color as a hexadecimal string.
_base_override: An optional base color override.
"""
self.base_hex = DEFAULT_COLORS.get(base, base)
self.base = _base_override or base
color = self.base_hex.lstrip("#")
self.red, self.green, self.blue = (
int(color[0:2], 16) / 255,
int(color[2:4], 16) / 255,
int(color[4:6], 16) / 255,
)
self.hue, self.brightness, self.saturation = rgb_to_hls(
self.red, self.green, self.blue
)
self.is_light = self.brightness > 0.5
def _adjust_abs(
self, hue: float = 0.0, brightness: float = 0.0, saturation: float = 0.0
) -> ColorPaletteColor:
hue = (self.hue + hue) % 1
brightness = max(min(1, self.brightness + brightness), 0)
saturation = max(min(1, self.saturation + saturation), 0)
r, g, b = hls_to_rgb(hue, brightness, saturation)
new_color = f"#{int(r * 255):02x}{int(g * 255):02x}{int(b * 255):02x}"
return ColorPaletteColor(new_color)
def _adjust_rel(
self, hue: float = 0.0, brightness: float = 0.0, saturation: float = 0.0
) -> ColorPaletteColor:
hue = min(max(0, hue), 1)
brightness = min(max(-1, brightness), 1)
saturation = min(max(-1, saturation), 1)
new_hue = self.hue + (self.hue * (hue < 0) + (1 - self.hue) * (hue > 0)) * hue
new_brightness = (
self.brightness
+ (
self.brightness * (brightness < 0)
+ (1 - self.brightness) * (brightness > 0)
)
* brightness
)
new_saturation = (
self.saturation
+ (
self.saturation * (saturation < 0)
+ (1 - self.saturation) * (saturation > 0)
)
* saturation
)
r, g, b = hls_to_rgb(new_hue, new_brightness, new_saturation)
new_color = f"#{int(r * 255):02x}{int(g * 255):02x}{int(b * 255):02x}"
return ColorPaletteColor(new_color)
def _adjust(
self,
hue: float = 0.0,
brightness: float = 0.0,
saturation: float = 0.0,
rel: bool = True,
) -> ColorPaletteColor:
"""Perform a relative of absolute color adjustment.
Args:
hue: The hue adjustment.
brightness: The brightness adjustment.
saturation: The saturation adjustment.
rel: If True, perform a relative adjustment.
Returns:
ColorPaletteColor: The adjusted color.
"""
if rel:
return self._adjust_rel(hue, brightness, saturation)
else:
return self._adjust_abs(hue, brightness, saturation)
def adjust(
self,
hue: float = 0.0,
brightness: float = 0.0,
saturation: float = 0.0,
rel: bool = True,
) -> ColorPaletteColor:
"""Adjust the hue, saturation, or brightness of the color.
Args:
hue: The hue adjustment.
brightness: The brightness adjustment.
saturation: The saturation adjustment.
rel: If True, perform a relative adjustment.
Returns:
ColorPaletteColor: The adjusted color.
"""
key = (self.base_hex, hue, brightness, saturation, rel)
return self._cache.get(
key, partial(self._adjust, hue, brightness, saturation, rel)
)
def lighter(self, amount: float, rel: bool = True) -> ColorPaletteColor:
"""Make the color lighter.
Args:
amount: The amount to lighten the color by.
rel: If True, perform a relative adjustment.
Returns:
ColorPaletteColor: The lighter color.
"""
return self.adjust(brightness=amount, rel=rel)
def darker(self, amount: float, rel: bool = True) -> ColorPaletteColor:
"""Make the color darker.
Args:
amount: The amount to darken the color by.
rel: If True, perform a relative adjustment.
Returns:
ColorPaletteColor: The darker color.
"""
return self.adjust(brightness=-amount, rel=rel)
def more(self, amount: float, rel: bool = True) -> ColorPaletteColor:
"""Make bright colors darker and dark colors brighter.
Args:
amount: The amount to adjust the color by.
rel: If True, perform a relative adjustment.
Returns:
ColorPaletteColor: The adjusted color.
"""
if self.is_light:
amount *= -1
return self.adjust(brightness=amount, rel=rel)
def less(self, amount: float, rel: bool = True) -> ColorPaletteColor:
"""Make bright colors brighter and dark colors darker.
Args:
amount: The amount to adjust the color by.
rel: If True, perform a relative adjustment.
Returns:
ColorPaletteColor: The adjusted color.
"""
if self.is_light:
amount *= -1
return self.adjust(brightness=-amount, rel=rel)
def towards(self, other: ColorPaletteColor, amount: float) -> ColorPaletteColor:
"""Interpolate between two colors."""
amount = min(max(0, amount), 1)
r = (other.red - self.red) * amount + self.red
g = (other.green - self.green) * amount + self.green
b = (other.blue - self.blue) * amount + self.blue
new_color = f"#{int(r * 255):02x}{int(g * 255):02x}{int(b * 255):02x}"
return ColorPaletteColor(new_color)
def __repr__(self) -> str:
"""Return a representation of the color."""
return f"Color({self.base})"
def __str__(self) -> str:
"""Return a string representation of the color."""
return self.base_hex
class ColorPalette:
"""Define a collection of colors."""
def __init__(self) -> None:
"""Create a new color-palette."""
self.colors: dict[str, ColorPaletteColor] = {}
def add_color(self, name: str, base: str, _base_override: str = "") -> ColorPalette:
"""Add a color to the palette."""
self.colors[name] = ColorPaletteColor(base, _base_override)
return self
def __getattr__(self, name: str) -> Any:
"""Enable access of palette colors via dotted attributes.
Args:
name: The name of the attribute to access.
Returns:
The color-palette color.
"""
return self.colors[name]
The provided code snippet includes necessary dependencies for implementing the `build_style` function. Write a Python function `def build_style( cp: ColorPalette, have_term_colors: bool = True, ) -> Style` to solve the following problem:
Create an application style based on the given color palette.
Here is the function:
def build_style(
cp: ColorPalette,
have_term_colors: bool = True,
) -> Style:
"""Create an application style based on the given color palette."""
style_dict = {
# The default style is merged at this point so full styles can be
# overridden. For example, this allows us to switch off the underline
# status of cursor-line.
**dict(default_ui_style().style_rules),
"default": f"fg:{cp.bg.base} bg:{cp.bg.base}",
# Remove non-breaking space style from PTK
"nbsp": "nounderline fg:default",
# Logo
"logo": "fg:#dd0000",
# Pattern
"pattern": f"fg:{cp.bg.more(0.075)}",
# Chrome
"chrome": f"fg:{cp.fg.more(0.05)} bg:{cp.bg.more(0.05)}",
"tab-padding": f"fg:{cp.bg.more(0.2)} bg:{cp.bg.base}",
# Statusbar
# "status": f"fg:{cp.fg.more(0.05)} bg:{cp.bg.less(0.15)}",
"status": f"fg:{cp.fg.more(0.05)} bg:{cp.bg.more(0.05)}",
"status-field": f"fg:{cp.fg.more(0.1)} bg:{cp.bg.more(0.1)}",
"status-sep": f"fg:{cp.bg.more(0.05)} bg:{cp.bg.more(0.1)}",
# Menus & Menu bar
"menu": f"fg:{cp.fg.more(0.05)} bg:{cp.bg.more(0.05)}",
"menu bar": f"bg:{cp.bg.less(0.15)}",
"menu disabled": f"fg:{cp.fg.more(0.05).towards(cp.bg, 0.75)}",
"menu shortcut": f"fg:{cp.fg.more(0.4)}",
"menu shortcut disabled": f"fg:{cp.fg.more(0.4).towards(cp.bg, 0.5)}",
"menu prefix": f"fg:{cp.fg.more(0.2)}",
"menu prefix disabled": f"fg:{cp.fg.more(0.2).towards(cp.bg, 0.5)}",
"menu selection": f"fg:{cp.hl.more(1)} bg:{cp.hl}",
"menu selection shortcut": f"fg:{cp.hl.more(1).more(0.05)} bg:{cp.hl}",
"menu selection prefix": f"fg:{cp.hl.more(1).more(0.05)} bg:{cp.hl}",
"menu border": f"fg:{cp.bg.more(0.15)} bg:{cp.bg.more(0.05)}",
"menu border selection": f"bg:{cp.hl}",
# Tab bar
"app-tab-bar": f"bg:{cp.bg.less(0.15)}",
"app-tab-bar border": f"fg:{cp.bg.more(0.1)}",
"app-tab-bar tab inactive": f"fg:{cp.fg.more(0.5)}",
"app-tab-bar tab inactive border": f"fg:{cp.bg.more(0.15)}",
"app-tab-bar tab active": "bold fg:default bg:default",
"app-tab-bar tab active close": "fg:darkred",
"app-tab-bar tab active border top": f"fg:{cp.hl} bg:{cp.bg.less(0.15)}",
# Tabs
"loading": "fg:#888888",
# Buffer
"line-number": f"fg:{cp.fg.more(0.5)} bg:{cp.bg.more(0.05)}",
"line-number.current": f"bold orange bg:{cp.bg.more(0.1)}",
"line-number edge": f"fg:{cp.bg.darker(0.1)}",
"line-number.current edge": f"fg:{cp.bg.darker(0.1)}",
"cursor-line": f"bg:{cp.bg.more(0.05)}",
"cursor-line search": f"bg:{cp.bg.more(0.02)}",
"cursor-line search.current": f"bg:{cp.bg.more(0.02)}",
"cursor-line incsearch": "bg:ansibrightyellow",
"cursor-line incsearch.current": "bg:ansibrightgreen",
"matching-bracket.cursor": "fg:yellow bold",
"matching-bracket.other": "fg:yellow bold",
"trailing-whitespace": f"fg:{cp.fg.more(0.66)}",
"tab": f"fg:{cp.fg.more(0.66)}",
# Search
"search": f"bg:{cp.bg.more(0.05)}",
"search.current": f"bg:{cp.bg.more(0.05)}",
"incsearch": "bg:ansibrightyellow",
"incsearch.current": "bg:ansibrightgreen",
"search-toolbar": f"fg:{cp.fg.more(0.05)} bg:{cp.bg.more(0.05)}",
"search-toolbar.title": f"fg:{cp.fg.more(0.1)} bg:{cp.bg.more(0.1)}",
# Inputs
"kernel-input": f"fg:default bg:{cp.bg.more(0.02)}",
# Cells
# "cell cell.selection": f"bg:{cp.bg.towards(cp.hl, 0.05)}",
# "cell edit": f"bg:{cp.bg.towards(cp.hl.adjust(hue=-0.3333, rel=False), 0.025)}",
"cell border": f"fg:{cp.bg.more(0.25)}",
"cell border cell.selection": f"fg:{cp.hl.more(0.2)}",
"cell border edit": f"fg:{cp.hl.adjust(hue=-0.3333, rel=False)}",
"cell input prompt": "fg:blue",
"cell output prompt": "fg:red",
"cell show outputs": "bg:#888",
"cell show inputs": "bg:#888",
# Scrollbars
"scrollbar": f"fg:{cp.bg.more(0.75)} bg:{cp.bg.more(0.15)}",
"scrollbar.background": f"fg:{cp.bg.more(0.75)} bg:{cp.bg.more(0.15)}",
"scrollbar.arrow": f"fg:{cp.bg.more(0.75)} bg:{cp.bg.more(0.20)}",
"scrollbar.start": "",
# "scrollbar.start": f"fg:{cp.bg.more(0.75)} bg:{cp.bg.more(0.25)}",
"scrollbar.button": f"fg:{cp.bg.more(0.75)} bg:{cp.bg.more(0.75)}",
"scrollbar.end": f"fg:{cp.bg.more(0.15)} bg:{cp.bg.more(0.75)}",
# Overflow margin
"overflow": f"fg:{cp.fg.more(0.5)}",
# Dialogs
"dialog dialog-title": f"fg:white bg:{cp.hl.darker(0.25)} bold",
"dialog": f"fg:{cp.fg.base} bg:{cp.bg.darker(0.1)}",
"dialog text-area": f"bg:{cp.bg.lighter(0.05)}",
"dialog input text text-area": f"fg:default bg:{cp.bg.less(0.1)}",
"dialog text-area last-line": "nounderline",
"dialog border": f"fg:{cp.bg.darker(0.1).more(0.1)}",
# Horizontals rule
"hr": "fg:ansired",
# Completions menu
"menu completion-keyword": "fg:#d700af",
"menu completion-function": "fg:#005faf",
"menu completion-class": "fg:#008700",
"menu completion-statement": "fg:#5f0000",
"menu completion-instance": "fg:#d75f00",
"menu completion-module": "fg:#d70000",
"menu completion-magic": "fg:#9841bb",
"menu completion-path": "fg:#aa8800",
"menu completion-dict-key": "fg:#ddbb00",
"menu selection completion-keyword": (
f"fg:{ColorPaletteColor('#d700af').lighter(0.75)}"
),
"menu selection completion-function": (
f"fg:{ColorPaletteColor('#005faf').lighter(0.75)}"
),
"menu selection completion-class": (
f"fg:{ColorPaletteColor('#008700').lighter(0.75)}"
),
"menu selection completion-statement": (
f"fg:{ColorPaletteColor('#5f0000').lighter(0.75)}"
),
"menu selection completion-instance": (
f"fg:{ColorPaletteColor('#d75f00').lighter(0.75)}"
),
"menu selection completion-module": (
f"fg:{ColorPaletteColor('#d70000').lighter(0.75)}"
),
"menu selection completion-magic": (
f"fg:{ColorPaletteColor('#888888').lighter(0.75)}"
),
"menu selection completion-path": (
f"fg:{ColorPaletteColor('#aa8800').lighter(0.75)}"
),
# Log
"log.level.nonset": "fg:grey",
"log.level.debug": "fg:green",
"log.level.info": "fg:blue",
"log.level.warning": "fg:yellow",
"log.level.error": "fg:red",
"log.level.critical": "fg:red bold",
"log.ref": "fg:grey",
"log.date": "fg:#00875f",
# File browser
"file-browser border": f"fg:{cp.bg.more(0.5)}",
"file-browser face": f"bg:{cp.bg.lighter(0.1)}",
"file-browser face row alt-row": f"bg:{cp.bg.lighter(0.1).more(0.01)}",
"file-browser face row hovered": f"bg:{cp.bg.more(0.2)}",
"file-browser face row selection": f"bg:{cp.hl}",
# Shortcuts
"shortcuts.group": f"bg:{cp.bg.more(0.4)} bold underline",
# "shortcuts.row": f"bg:{cp.bg.base} nobold",
"shortcuts.row alt": f"bg:{cp.bg.more(0.1)}",
"shortcuts.row key": "bold",
# Palette
"palette.item": f"fg:{cp.fg.more(0.05)} bg:{cp.bg.more(0.05)}",
"palette.item.alt": f"bg:{cp.bg.more(0.15)}",
"palette.item.selected": f"fg:{cp.hl.more(1)} bg:{cp.hl}",
# Pager
"pager": f"bg:{cp.bg.more(0.05)}",
"pager.border": f"fg:{cp.bg.towards(cp.ansiblack, 0.15)} reverse",
# Markdown
"markdown code": f"bg:{cp.bg.more(0.15)}",
"markdown code block": f"bg:{cp.bg.less(0.2)}",
"markdown code block border": f"fg:{cp.bg.more(0.25)}",
"markdown table border": f"fg:{cp.bg.more(0.75)}",
# Drop-shadow
"drop-shadow inner": f"fg:{cp.bg.towards(cp.ansiblack, 0.3)}",
"drop-shadow outer": f"fg:{cp.bg.towards(cp.ansiblack, 0.2)} bg:{cp.bg.towards(cp.ansiblack, 0.05)}",
# Side-bar
"side_bar": f"bg:{cp.bg.less(0.15)}",
"side_bar title": f"fg:{cp.hl}",
"side_bar title text": f"fg:default bg:{cp.bg.less(0.15).more(0.01)}",
"side_bar border": f"fg:{cp.bg.towards(cp.ansiblack, 0.3)}",
"side_bar border outer": f"bg:{cp.bg}",
"side_bar buttons": f"bg:{cp.bg.less(0.15)}",
"side_bar buttons hovered": f"fg:{cp.hl}",
"side_bar buttons selection": f"fg:{cp.fg} bg:{cp.hl}",
"side_bar buttons separator": f"fg:{cp.bg.less(0.15)} bg:{cp.bg.less(0.15)}",
"side_bar buttons separator selection before": (
f"fg:{cp.bg.less(0.15)} bg:{cp.hl}"
),
"side_bar buttons separator selection after": (
f"fg:{cp.hl} bg:{cp.bg.less(0.15)}"
),
# Tabbed split
"tabbed-split border": f"fg:{cp.bg.more(0.2)}",
"tabbed-split border left": f"bg:{cp.bg.more(0.025)}",
"tabbed-split border right": f"bg:{cp.bg.more(0.025)}",
"tabbed-split border bottom left": f"bg:{cp.bg}",
"tabbed-split border bottom right": f"bg:{cp.bg}",
"tabbed-split page": f"bg:{cp.bg.more(0.025)}",
"dialog tabbed-split border bottom right": f"bg:{cp.bg.darker(0.1)}",
"dialog tabbed-split border bottom left": f"bg:{cp.bg.darker(0.1)}",
"tabbed-split tab-bar tab inactive": f"fg:{cp.bg.more(0.3)}",
"tabbed-split tab-bar tab inactive title": f"bg:{cp.bg.darker(0.05)}",
"tabbed-split tab-bar tab inactive border left": f"bg:{cp.bg.darker(0.05)}",
"tabbed-split tab-bar tab inactive border right": f"bg:{cp.bg.darker(0.05)}",
"tabbed-split tab-bar tab active": f"bold fg:{cp.fg}",
"tabbed-split tab-bar tab active title": f"bg:{cp.bg.more(0.025)}",
"tabbed-split tab-bar tab active close": "fg:darkred",
# Ipywidgets
"ipywidget focused": f"bg:{cp.bg.more(0.05)}",
"ipywidget slider track": f"fg:{cp.fg.darker(0.5)}",
"ipywidget slider arrow": f"fg:{cp.fg.darker(0.25)}",
"ipywidget slider handle": f"fg:{cp.fg.darker(0.25)}",
"ipywidget accordion border default": f"fg:{cp.bg.more(0.2)}",
## Styled borders
"success border top": "fg:ansibrightgreen",
"success border left": "fg:ansibrightgreen",
"success border bottom": f"fg:{cp.ansigreen.darker(0.5)}",
"success border right": f"fg:{cp.ansigreen.darker(0.5)}",
"info border top": "fg:ansibrightcyan",
"info border left": "fg:ansibrightcyan",
"info border bottom": f"fg:{cp.ansicyan.darker(0.5)}",
"info border right": f"fg:{cp.ansicyan.darker(0.5)}",
"warning border top": "fg:ansibrightyellow",
"warning border left": "fg:ansibrightyellow",
"warning border bottom": f"fg:{cp.ansiyellow.darker(0.5)}",
"warning border right": f"fg:{cp.ansiyellow.darker(0.5)}",
"danger border top": "fg:ansibrightred",
"danger border left": "fg:ansibrightred",
"danger border bottom": f"fg:{cp.ansired.darker(0.5)}",
"danger border right": f"fg:{cp.ansired.darker(0.5)}",
## Selected styled borders
"selection success border top": f"fg:{cp.ansigreen.darker(0.5)}",
"selection success border left": f"fg:{cp.ansigreen.darker(0.5)}",
"selection success border bottom": "fg:ansibrightgreen",
"selection success border right": "fg:ansibrightgreen",
"selection info border left": f"fg:{cp.ansicyan.darker(0.5)}",
"selection info border top": f"fg:{cp.ansicyan.darker(0.5)}",
"selection info border right": "fg:ansibrightcyan",
"selection info border bottom": "fg:ansibrightcyan",
"selection warning border top": f"fg:{cp.ansiyellow.darker(0.5)}",
"selection warning border left": f"fg:{cp.ansiyellow.darker(0.5)}",
"selection warning border bottom": "fg:ansibrightyellow",
"selection warning border right": "fg:ansibrightyellow",
"selection danger border top": f"fg:{cp.ansired.darker(0.5)}",
"selection danger border left": f"fg:{cp.ansired.darker(0.5)}",
"selection danger border bottom": "fg:ansibrightred",
"selection danger border right": "fg:ansibrightred",
# Selected faces
"selection success face": f"bg:{cp.ansigreen.darker(0.05)}",
"selection info face": f"bg:{cp.ansicyan.darker(0.05)}",
"selection warning face": f"bg:{cp.ansiyellow.darker(0.05)}",
"selection danger face": f"bg:{cp.ansired.darker(0.05)}",
# Hovered faces
"input hovered face": f"fg:default bg:{cp.bg.more(0.2)}",
"focused hovered success face": f"bg:{cp.ansigreen.lighter(0.05)}",
"focused hovered info face": f"bg:{cp.ansicyan.lighter(0.05)}",
"focused hovered warning face": f"bg:{cp.ansiyellow.lighter(0.05)}",
"focused hovered danger face": f"bg:{cp.ansired.lighter(0.05)}",
# Text areas
"text-area focused": "noreverse",
"text-area selected": "noreverse",
"text-area focused selected": "reverse",
# Buttons
"input button face": f"fg:default bg:{cp.bg.more(0.05)}",
"input button face hovered": f"fg:default bg:{cp.bg.more(0.2)}",
"input button face selection": f"bg:{cp.bg.more(0.05)}",
"input button face focused": f"fg:default bg:{cp.bg.towards(cp.hl, 0.1)}",
# Input widgets
"input border top": f"fg:{cp.bg.lighter(0.5)}",
"input border left": f"fg:{cp.bg.lighter(0.5)}",
"input border bottom": f"fg:{cp.bg.darker(0.25)}",
"input border right": f"fg:{cp.bg.darker(0.25)}",
"input border top focused": f"fg:{cp.hl.lighter(0.5)}",
"input border left focused": f"fg:{cp.hl.lighter(0.5)}",
"input border bottom focused": f"fg:{cp.hl.darker(0.5)}",
"input border right focused": f"fg:{cp.hl.darker(0.5)}",
"input border top selection": f"fg:{cp.bg.darker(0.5)}",
"input border left selection": f"fg:{cp.bg.darker(0.5)}",
"input border bottom selection": f"fg:{cp.bg.lighter(0.5)}",
"input border right selection": f"fg:{cp.bg.lighter(0.5)}",
"input border top selection focused": f"fg:{cp.hl.darker(0.5)}",
"input border left selection focused": f"fg:{cp.hl.darker(0.5)}",
"input border bottom selection focused": f"fg:{cp.hl.lighter(0.5)}",
"input border right selection focused": f"fg:{cp.hl.lighter(0.5)}",
"input inset border bottom": f"fg:{cp.bg.lighter(0.5)}",
"input inset border right": f"fg:{cp.bg.lighter(0.5)}",
"input inset border top": f"fg:{cp.bg.darker(0.25)}",
"input inset border left": f"fg:{cp.bg.darker(0.25)}",
"input inset border bottom focused": f"fg:{cp.hl.lighter(0.5)}",
"input inset border right focused": f"fg:{cp.hl.lighter(0.5)}",
"input inset border top focused": f"fg:{cp.hl.darker(0.5)}",
"input inset border left focused": f"fg:{cp.hl.darker(0.5)}",
"input inset border bottom selection": f"fg:{cp.bg.darker(0.5)}",
"input inset border right selection": f"fg:{cp.bg.darker(0.5)}",
"input inset border top selection": f"fg:{cp.bg.lighter(0.5)}",
"input inset border left selection": f"fg:{cp.bg.lighter(0.5)}",
"input inset border bottom selection focused": f"fg:{cp.hl.darker(0.5)}",
"input inset border right selection focused": f"fg:{cp.hl.darker(0.5)}",
"input inset border top selection focused": f"fg:{cp.hl.lighter(0.5)}",
"input inset border left selection focused": f"fg:{cp.hl.lighter(0.5)}",
"input text placeholder": f"fg:{cp.fg.more(0.6)}",
"input text text-area": f"fg:default bg:{cp.bg.lighter(0.1)}",
"input text border top": f"fg:{cp.bg.darker(0.5)}",
"input text border right": f"fg:{cp.bg.lighter(0.25)}",
"input text border bottom": f"fg:{cp.bg.lighter(0.25)}",
"input text border left": f"fg:{cp.bg.darker(0.5)}",
"input text border top focused": f"fg:{cp.hl.darker(0.5)}",
"input text border right focused": f"fg:{cp.hl.lighter(0.5)}",
"input text border bottom focused": f"fg:{cp.hl.lighter(0.5)}",
"input text border left focused": f"fg:{cp.hl.darker(0.5)}",
"input text border top invalid": "fg:ansidarkred",
"input text border right invalid": "fg:ansired",
"input text border bottom invalid": "fg:ansired",
"input text border left invalid": "fg:ansidarkred",
"input radio-buttons prefix selection focused": f"fg:{cp.hl}",
"input slider arrow": f"fg:{cp.fg.darker(0.25)}",
"input slider track": f"fg:{cp.fg.darker(0.5)}",
"input slider track selection": f"fg:{cp.hl}",
"input slider handle": f"fg:{cp.fg.darker(0.25)}",
"input slider handle focused": f"fg:{cp.fg}",
"input slider handle selection focused": f"fg:{cp.hl}",
"input dropdown dropdown.menu": f"bg:{cp.bg.more(0.05)}",
"input dropdown dropdown.menu hovered": f"bg:{cp.hl}",
"input select face": f"bg:{cp.bg.lighter(0.1)}",
"input select face selection": f"fg:white bg:{cp.hl}",
"input select face hovered": f"bg:{cp.bg.more(0.2)}",
"input select face hovered selection": f"fg:white bg:{cp.hl}",
# Dataframes
"dataframe th": f"bg:{cp.bg.more(0.1)}",
"dataframe row-odd td": f"bg:{cp.bg.more(0.05)}",
# Diagnostic flags
"diagnostic-0": "fg:ansigray",
"diagnostic-1": "fg:ansigreen",
"diagnostic-2": "fg:ansiblue",
"diagnostic-3": "fg:ansiyellow",
"diagnostic-4": "fg:ansired",
"diagnostic-5": "fg:ansiwhite bg:ansired bold",
}
return Style.from_dict(style_dict) | Create an application style based on the given color palette. |
6,832 | from __future__ import annotations
import logging
from typing import TYPE_CHECKING
from prompt_toolkit.data_structures import Point, Size
from prompt_toolkit.filters import to_filter
from prompt_toolkit.layout.mouse_handlers import MouseHandlers
from prompt_toolkit.renderer import Renderer as PtkRenderer
from prompt_toolkit.renderer import _StyleStringHasStyleCache, _StyleStringToAttrsCache
from euporie.core.io import Vt100_Output
from euporie.core.layout.screen import BoundedWritePosition, Screen
class Screen(screen.Screen):
"""Screen class which uses :py:`BoundedWritePosition`s."""
def fill_area(
self, write_position: screen.WritePosition, style: str = "", after: bool = False
) -> None:
"""Fill the content of this area, using the given `style`."""
if not style.strip():
return
if isinstance(write_position, BoundedWritePosition):
bbox = write_position.bbox
else:
bbox = DiInt(0, 0, 0, 0)
xmin = write_position.xpos + bbox.left
xmax = write_position.xpos + write_position.width - bbox.right
char_cache = screen._CHAR_CACHE
data_buffer = self.data_buffer
if after:
append_style = " " + style
prepend_style = ""
else:
append_style = ""
prepend_style = style + " "
for y in range(
write_position.ypos + bbox.top,
write_position.ypos + write_position.height - bbox.bottom,
):
row = data_buffer[y]
for x in range(xmin, xmax):
cell = row[x]
row[x] = char_cache[
cell.char, prepend_style + cell.style + append_style
]
The provided code snippet includes necessary dependencies for implementing the `_output_screen_diff` function. Write a Python function `def _output_screen_diff( app: Application[Any], output: Output, screen: PtkScreen, current_pos: Point, color_depth: ColorDepth, previous_screen: PtkScreen | None, last_style: str | None, is_done: bool, # XXX: drop is_done full_screen: bool, attrs_for_style_string: _StyleStringToAttrsCache, style_string_has_style: _StyleStringHasStyleCache, size: Size, previous_width: int, ) -> tuple[Point, str | None]` to solve the following problem:
Render the diff between this screen and the previous screen.
Here is the function:
def _output_screen_diff(
app: Application[Any],
output: Output,
screen: PtkScreen,
current_pos: Point,
color_depth: ColorDepth,
previous_screen: PtkScreen | None,
last_style: str | None,
is_done: bool, # XXX: drop is_done
full_screen: bool,
attrs_for_style_string: _StyleStringToAttrsCache,
style_string_has_style: _StyleStringHasStyleCache,
size: Size,
previous_width: int,
) -> tuple[Point, str | None]:
"""Render the diff between this screen and the previous screen."""
width, height = size.columns, size.rows
#: Variable for capturing the output.
write = output.write
write_raw = output.write_raw
# Create locals for the most used output methods.
# (Save expensive attribute lookups.)
_output_set_attributes = output.set_attributes
_output_reset_attributes = output.reset_attributes
_output_cursor_forward = output.cursor_forward
_output_cursor_up = output.cursor_up
_output_cursor_backward = output.cursor_backward
# Hide cursor before rendering. (Avoid flickering.)
output.hide_cursor()
def reset_attributes() -> None:
"""Wrap Output.reset_attributes."""
nonlocal last_style
_output_reset_attributes()
last_style = None # Forget last char after resetting attributes.
def move_cursor(new: Point) -> Point:
"""Move cursor to this `new` point & return the given Point."""
current_x, current_y = current_pos.x, current_pos.y
if new.y > current_y:
# Use newlines instead of CURSOR_DOWN, because this might add new lines.
# CURSOR_DOWN will never create new lines at the bottom.
# Also reset attributes, otherwise the newline could draw a
# background color.
reset_attributes()
write("\r\n" * (new.y - current_y))
current_x = 0
_output_cursor_forward(new.x)
return new
elif new.y < current_y:
_output_cursor_up(current_y - new.y)
if current_x >= width - 1:
write("\r")
_output_cursor_forward(new.x)
elif new.x < current_x or current_x >= width - 1:
_output_cursor_backward(current_x - new.x)
elif new.x > current_x:
_output_cursor_forward(new.x - current_x)
return new
def output_char(char: Char) -> None:
"""Write the output of this character."""
nonlocal last_style
# If the last printed character has the same style, don't output the
# style again.
if last_style == char.style:
write(char.char)
else:
# Look up `Attr` for this style string. Only set attributes if different.
# (Two style strings can still have the same formatting.)
# Note that an empty style string can have formatting that needs to
# be applied, because of style transformations.
new_attrs = attrs_for_style_string[char.style]
if not last_style or new_attrs != attrs_for_style_string[last_style]:
_output_set_attributes(new_attrs, color_depth)
write(char.char)
last_style = char.style
def get_max_column_index(row: dict[int, Char], zwe_row: dict[int, str]) -> int:
"""Return max used column index, ignoring trailing unstyled whitespace."""
return max(
{
index
for index, cell in row.items()
if cell.char != " " or style_string_has_style[cell.style]
}
# Lag ZWE indices by one, as one could exist after the last line character
# but we don't want that to count towards the line width
| {x - 1 for x in zwe_row}
| {0}
)
# Render for the first time: reset styling.
if not previous_screen:
reset_attributes()
# Disable autowrap. (When entering a the alternate screen, or anytime when
# we have a prompt. - In the case of a REPL, like IPython, people can have
# background threads, and it's hard for debugging if their output is not
# wrapped.)
if not previous_screen or not full_screen:
output.disable_autowrap()
# When the previous screen has a different size, redraw everything anyway.
# Also when we are done. (We might take up less rows, so clearing is important.)
if (
is_done or not previous_screen or previous_width != width
): # XXX: also consider height??
current_pos = move_cursor(Point(x=0, y=0))
reset_attributes()
output.erase_down()
previous_screen = Screen()
assert previous_screen is not None
# Get height of the screen.
# (height changes as we loop over data_buffer, so remember the current value.)
# (Also make sure to clip the height to the size of the output.)
current_height = min(screen.height, height)
# Loop over the rows.
row_count = min(max(screen.height, previous_screen.height), height)
c = 0 # Column counter.
for y in range(row_count):
new_row = screen.data_buffer[y]
previous_row = previous_screen.data_buffer[y]
zwe_row = screen.zero_width_escapes[y]
previous_zwe_row = previous_screen.zero_width_escapes[y]
new_max_line_len = min(width - 1, get_max_column_index(new_row, zwe_row))
previous_max_line_len = min(
width - 1, get_max_column_index(previous_row, previous_zwe_row)
)
# Loop over the columns.
c = 0
prev_diff_char = False
# Loop just beyond the line length to check for ZWE sequences right at the end
# of the line
while c <= new_max_line_len + 1:
new_char = new_row[c]
old_char = previous_row[c]
new_zwe = zwe_row[c]
char_width = new_char.width or 1
# When the old and new character at this position are different,
# draw the output. (Because of the performance, we don't call
# `Char.__ne__`, but inline the same expression.)
diff_char = (
new_char.char != old_char.char or new_char.style != old_char.style
)
# Redraw escape sequences if the escape sequence at this position changed,
# or if the current or previous character changed
if new_zwe != previous_zwe_row[c] or diff_char or prev_diff_char:
# Send injected escape sequences to output.
write_raw(new_zwe)
if diff_char:
# Don't move the cursor if it is already in the correct position
if c != current_pos.x or y != current_pos.y:
current_pos = move_cursor(Point(x=c, y=y))
output_char(new_char)
current_pos = Point(x=current_pos.x + char_width, y=current_pos.y)
prev_diff_char = diff_char
c += char_width
# If the new line is shorter, trim it.
if previous_screen and new_max_line_len < previous_max_line_len:
# Don't move the cursor if it is already in the correct position
if current_pos.x != new_max_line_len or current_pos.y != current_pos.y:
current_pos = move_cursor(Point(x=new_max_line_len + 1, y=y))
reset_attributes()
output.erase_end_of_line()
# Correctly reserve vertical space as required by the layout.
# When this is a new screen (drawn for the first time), or for some reason
# higher than the previous one. Move the cursor once to the bottom of the
# output. That way, we're sure that the terminal scrolls up, even when the
# lower lines of the canvas just contain whitespace.
# The most obvious reason that we actually want this behaviour is the avoid
# the artifact of the input scrolling when the completion menu is shown.
# (If the scrolling is actually wanted, the layout can still be build in a
# way to behave that way by setting a dynamic height.)
if current_height > previous_screen.height:
current_pos = move_cursor(Point(x=0, y=current_height - 1))
# Move cursor:
if is_done:
current_pos = move_cursor(Point(x=0, y=current_height))
output.erase_down()
else:
current_pos = move_cursor(screen.get_cursor_position(app.layout.current_window))
if is_done or not full_screen:
output.enable_autowrap()
# Always reset the color attributes. This is important because a background
# thread could print data to stdout and we want that to be displayed in the
# default colors. (Also, if a background color has been set, many terminals
# give weird artifacts on resize events.)
reset_attributes()
if screen.show_cursor or is_done:
output.show_cursor()
return current_pos, last_style | Render the diff between this screen and the previous screen. |
6,833 | from __future__ import annotations
import logging
import weakref
from inspect import isawaitable, iscoroutinefunction, signature
from typing import TYPE_CHECKING, cast
from prompt_toolkit.application import get_app
from prompt_toolkit.filters import to_filter
from prompt_toolkit.key_binding.key_bindings import Binding
from prompt_toolkit.key_binding.key_processor import KeyPressEvent
from euporie.core.key_binding.utils import parse_keys
class Command:
"""Wrap a function so it can be used as a key-binding or a menu item."""
def __init__(
self,
handler: CommandHandler,
*,
filter: FilterOrBool = True,
hidden: FilterOrBool = False,
name: str | None = None,
title: str | None = None,
menu_title: str | None = None,
description: str | None = None,
toggled: Filter | None = None,
eager: FilterOrBool = False,
is_global: FilterOrBool = False,
save_before: Callable[[KeyPressEvent], bool] = (lambda event: True),
record_in_macro: FilterOrBool = True,
) -> None:
"""Create a new instance of a command.
Args:
handler: The callable to run when the command is triggers
filter: The condition under which the command is allowed to run
hidden: The condition under the command is visible to the user
name: The name of the command, for accessing the command from the registry
title: The title of the command for display
menu_title: The title to display in menus if different
description: The description of the command to explain it's function
toggled: The toggle state of this command If this command toggles something
eager: When True, ignore potential longer matches for this key binding
is_global: Make this a global (always active) binding
save_before: Determines if the buffer should be saved before running
record_in_macro: Whether these key bindings should be recorded in macros
"""
self.handler = handler
self.filter = to_filter(filter)
self.hidden = to_filter(hidden)
if name is None:
name = handler.__name__.strip("_").replace("_", "-")
self.name = name
if title is None:
title = name.capitalize().replace("-", " ")
self.title = title
self.menu_title = menu_title or title
if description is None:
# Use the first line of the docstring as the command description
if handler.__doc__:
description = (
"".join(handler.__doc__.strip().split("\n")).split(".")[0] + "."
)
else:
description = title or name.capitalize()
self.description = description
self.toggled = toggled
self._menu: MenuItem | None = None
self.eager = to_filter(eager)
self.is_global = to_filter(is_global)
self.save_before = save_before
self.record_in_macro = to_filter(record_in_macro)
self.keys: list[tuple[str | Keys, ...]] = []
def run(self) -> None:
"""Run the command's handler."""
if self.filter():
app = get_app()
result = self.key_handler(
KeyPressEvent(
key_processor_ref=weakref.ref(app.key_processor),
arg=None,
key_sequence=[],
previous_key_sequence=[],
is_repeat=False,
)
)
if isawaitable(result):
async def _wait_and_invalidate() -> None:
assert isawaitable(result)
output = await result
if output is None:
app.invalidate()
app.create_background_task(_wait_and_invalidate())
elif result is None:
app.invalidate()
def key_handler(self) -> KeyHandlerCallable:
"""Return a key handler for the command."""
handler = self.handler
sig = signature(handler)
if sig.parameters:
# The handler already accepts a `KeyPressEvent` argument
return cast("KeyHandlerCallable", handler)
if iscoroutinefunction(handler):
async def _key_handler_async(event: KeyPressEvent) -> NotImplementedOrNone:
result = cast("CommandHandlerNoArgs", handler)()
assert isawaitable(result)
return await result
return _key_handler_async
else:
def _key_handler(event: KeyPressEvent) -> NotImplementedOrNone:
return cast("CommandHandlerNoArgs", handler)()
return _key_handler
def bind(self, key_bindings: KeyBindingsBase, keys: AnyKeys) -> None:
"""Add the current commands to a set of key bindings.
Args:
key_bindings: The set of key bindings to bind to
keys: Additional keys to bind to the command
"""
for key in parse_keys(keys):
self.keys.append(key)
key_bindings.bindings.append(
Binding(
key,
handler=self.key_handler,
filter=self.filter,
eager=self.eager,
is_global=self.is_global,
save_before=self.save_before,
record_in_macro=self.record_in_macro,
)
)
def key_str(self) -> str:
"""Return a string representing the first registered key-binding."""
from euporie.core.key_binding.utils import format_keys
if self.keys:
return format_keys([self.keys[0]])[0]
return ""
def menu_handler(self) -> Callable[[], None]:
"""Return a menu handler for the command."""
handler = self.handler
if isawaitable(handler):
def _menu_handler() -> None:
task = cast("CommandHandlerNoArgs", handler)()
task = cast("Coroutine[Any, Any, None]", task)
if task is not None:
get_app().create_background_task(task)
return _menu_handler
else:
return cast("Callable[[], None]", handler)
def menu(self) -> MenuItem:
"""Return a menu item for the command."""
from euporie.core.widgets.menu import MenuItem
if self._menu is None:
self._menu = MenuItem.from_command(self)
return self._menu
commands: dict[str, Command] = {}
The provided code snippet includes necessary dependencies for implementing the `add_cmd` function. Write a Python function `def add_cmd(**kwargs: Any) -> Callable` to solve the following problem:
Add a command to the centralized command system.
Here is the function:
def add_cmd(**kwargs: Any) -> Callable:
"""Add a command to the centralized command system."""
def decorator(handler: Callable) -> Callable:
cmd = Command(handler, **kwargs)
commands[cmd.name] = cmd
return handler
return decorator | Add a command to the centralized command system. |
6,834 | from __future__ import annotations
import asyncio
import json
import logging
import os
import threading
from pathlib import Path
from typing import TYPE_CHECKING, NamedTuple
from prompt_toolkit.utils import Event
The provided code snippet includes necessary dependencies for implementing the `_setup_loop` function. Write a Python function `def _setup_loop(loop: asyncio.AbstractEventLoop) -> None` to solve the following problem:
Run a new event loop (intended to start a loop running in a thread.
Here is the function:
def _setup_loop(loop: asyncio.AbstractEventLoop) -> None:
"""Run a new event loop (intended to start a loop running in a thread."""
asyncio.set_event_loop(loop)
loop.run_forever() | Run a new event loop (intended to start a loop running in a thread. |
6,835 | from __future__ import annotations
import asyncio
import json
import logging
import os
import threading
from pathlib import Path
from typing import TYPE_CHECKING, NamedTuple
from prompt_toolkit.utils import Event
The provided code snippet includes necessary dependencies for implementing the `range_to_slice` function. Write a Python function `def range_to_slice( start_line: int, start_char: int, end_line: int, end_char: int, text: str ) -> slice` to solve the following problem:
Convert a line/character ranger to a slice.
Here is the function:
def range_to_slice(
start_line: int, start_char: int, end_line: int, end_char: int, text: str
) -> slice:
"""Convert a line/character ranger to a slice."""
start_pos = start_char
end_pos = end_char
lines = text.splitlines(keepends=True)
for i, line in enumerate(lines):
len_line = len(line)
if i < start_line:
start_pos += len_line
if i < end_line:
end_pos += len_line
else:
break
return slice(start_pos, end_pos) | Convert a line/character ranger to a slice. |
6,836 | from __future__ import annotations
import logging
from pathlib import Path
from typing import TYPE_CHECKING
import upath
from aiohttp.client_reqrep import ClientResponse
from fsspec.implementations.http import HTTPFileSystem as FsHTTPFileSystem
from fsspec.registry import register_implementation as fs_register_implementation
from upath import UPath
The provided code snippet includes necessary dependencies for implementing the `_raise_for_status` function. Write a Python function `def _raise_for_status(self: ClientResponse) -> None` to solve the following problem:
Monkey-patch :py:class:`aiohttp.ClientResponse` not to raise for any status.
Here is the function:
def _raise_for_status(self: ClientResponse) -> None:
"""Monkey-patch :py:class:`aiohttp.ClientResponse` not to raise for any status.""" | Monkey-patch :py:class:`aiohttp.ClientResponse` not to raise for any status. |
6,837 | from __future__ import annotations
import logging
from pathlib import Path
from typing import TYPE_CHECKING
import upath
from aiohttp.client_reqrep import ClientResponse
from fsspec.implementations.http import HTTPFileSystem as FsHTTPFileSystem
from fsspec.registry import register_implementation as fs_register_implementation
from upath import UPath
log = logging.getLogger(__name__)
The provided code snippet includes necessary dependencies for implementing the `parse_path` function. Write a Python function `def parse_path(path: str | PathLike, resolve: bool = True) -> Path` to solve the following problem:
Parse and resolve a path.
Here is the function:
def parse_path(path: str | PathLike, resolve: bool = True) -> Path:
"""Parse and resolve a path."""
if not isinstance(path, Path):
path = UPath(path)
try:
path = path.expanduser()
except NotImplementedError:
pass
if resolve:
try:
path = path.resolve()
except (AttributeError, NotImplementedError, Exception):
log.info("Path %s not resolvable", path)
return path | Parse and resolve a path. |
6,838 | from __future__ import annotations
import logging
from typing import TYPE_CHECKING
from weakref import WeakKeyDictionary
from prompt_toolkit.cache import FastDictCache
from prompt_toolkit.filters.utils import to_filter
from prompt_toolkit.formatted_text import to_formatted_text
from prompt_toolkit.layout import containers
from prompt_toolkit.layout.containers import ConditionalContainer, WindowAlign
from prompt_toolkit.layout.containers import (
to_container as ptk_to_container,
)
from prompt_toolkit.layout.controls import FormattedTextControl
from euporie.core.config import add_setting
from euporie.core.current import get_app
from euporie.core.filters import is_searching
from euporie.core.layout.containers import VSplit, Window
_CONTAINER_STATUSES: WeakKeyDictionary[
Container, Callable[[], StatusBarFields | None]
] = WeakKeyDictionary()
The provided code snippet includes necessary dependencies for implementing the `to_container` function. Write a Python function `def to_container(container: AnyContainer) -> Container` to solve the following problem:
Monkey-patch `to_container` to collect container status functions.
Here is the function:
def to_container(container: AnyContainer) -> Container:
"""Monkey-patch `to_container` to collect container status functions."""
result = ptk_to_container(container)
if hasattr(container, "__pt_status__"):
_CONTAINER_STATUSES[result] = container.__pt_status__
return result | Monkey-patch `to_container` to collect container status functions. |
6,839 | from __future__ import annotations
import asyncio
import logging
import os
import weakref
from functools import partial
from pathlib import Path
from typing import TYPE_CHECKING, cast
from weakref import WeakKeyDictionary
import nbformat
from prompt_toolkit.completion.base import (
DynamicCompleter,
_MergedCompleter,
)
from prompt_toolkit.document import Document
from prompt_toolkit.filters.base import Condition
from prompt_toolkit.layout.containers import (
ConditionalContainer,
Container,
)
from prompt_toolkit.layout.controls import FormattedTextControl
from prompt_toolkit.layout.dimension import Dimension
from prompt_toolkit.utils import Event
from euporie.core.border import NoLine, ThickLine, ThinLine
from euporie.core.completion import DeduplicateCompleter, LspCompleter
from euporie.core.config import add_setting
from euporie.core.current import get_app
from euporie.core.diagnostics import Report
from euporie.core.filters import multiple_cells_selected
from euporie.core.format import LspFormatter
from euporie.core.inspection import (
FirstInspector,
LspInspector,
)
from euporie.core.layout.containers import HSplit, VSplit, Window
from euporie.core.lsp import LspCell
from euporie.core.utils import on_click
from euporie.core.widgets.cell_outputs import CellOutputArea
from euporie.core.widgets.inputs import KernelInput, StdInput
The provided code snippet includes necessary dependencies for implementing the `get_cell_id` function. Write a Python function `def get_cell_id(cell_json: dict) -> str` to solve the following problem:
Return the cell ID field defined in a cell JSON object. If no cell ID is defined (as per ```:mod:`nbformat`<4.5``), then one is generated and added to the cell. Args: cell_json: The cell's JSON object as a python dictionary Returns: The ID string
Here is the function:
def get_cell_id(cell_json: dict) -> str:
"""Return the cell ID field defined in a cell JSON object.
If no cell ID is defined (as per ```:mod:`nbformat`<4.5``), then one is generated
and added to the cell.
Args:
cell_json: The cell's JSON object as a python dictionary
Returns:
The ID string
"""
cell_id = cell_json.get("id", "")
# Assign a cell id if missing
if not cell_id:
cell_json["id"] = cell_id = nbformat.v4.new_code_cell().get("id")
return cell_id | Return the cell ID field defined in a cell JSON object. If no cell ID is defined (as per ```:mod:`nbformat`<4.5``), then one is generated and added to the cell. Args: cell_json: The cell's JSON object as a python dictionary Returns: The ID string |
6,840 | from __future__ import annotations
import logging
from typing import TYPE_CHECKING
from prompt_toolkit.filters.app import is_searching
from prompt_toolkit.key_binding.vi_state import InputMode
from prompt_toolkit.layout.controls import BufferControl, SearchBufferControl
from prompt_toolkit.search import SearchDirection
from prompt_toolkit.selection import SelectionState
from prompt_toolkit.widgets import SearchToolbar as PtkSearchToolbar
from euporie.core.commands import add_cmd
from euporie.core.current import get_app
from euporie.core.key_binding.registry import (
load_registered_bindings,
register_bindings,
)
def start_global_search(
buffer_control: BufferControl | None = None,
direction: SearchDirection = SearchDirection.FORWARD,
) -> None:
"""Start a search through all searchable `buffer_controls` in the layout."""
app = get_app()
layout = app.layout
current_control = layout.current_control
# Find the search buffer control
if app.search_bar is not None:
search_buffer_control = app.search_bar.control
elif (
isinstance(current_control, BufferControl)
and current_control.search_buffer_control is not None
):
search_buffer_control = current_control.search_buffer_control
else:
return
# Find all searchable controls
searchable_controls: list[BufferControl] = []
next_control_index = 0
for control in layout.find_all_controls():
# Find the index of the next searchable control so we can link the search
# control to it if the currently focused control is not searchable. This is so
# that the next searchable control can be focused when search is completed.
if control == current_control:
next_control_index = len(searchable_controls)
# Only save the control if it is searchable
if (
isinstance(control, BufferControl)
and control.search_buffer_control == search_buffer_control
):
# Set its search direction
control.search_state.direction = direction
# Add it to our list
searchable_controls.append(control)
# Stop the search if we did not find any searchable controls
if not searchable_controls:
return
# If the current control is searchable, link it
if current_control in searchable_controls:
assert isinstance(current_control, BufferControl)
layout.search_links[search_buffer_control] = current_control
else:
# otherwise use the next after the currently selected control
layout.search_links[search_buffer_control] = searchable_controls[
next_control_index % len(searchable_controls)
]
# Make sure to focus the search BufferControl
layout.focus(search_buffer_control)
# If we're in Vi mode, make sure to go into insert mode.
app.vi_state.input_mode = InputMode.INSERT
The provided code snippet includes necessary dependencies for implementing the `find` function. Write a Python function `def find() -> None` to solve the following problem:
Enter search mode.
Here is the function:
def find() -> None:
"""Enter search mode."""
start_global_search(direction=SearchDirection.FORWARD) | Enter search mode. |
6,841 | from __future__ import annotations
import logging
from typing import TYPE_CHECKING
from prompt_toolkit.filters.app import is_searching
from prompt_toolkit.key_binding.vi_state import InputMode
from prompt_toolkit.layout.controls import BufferControl, SearchBufferControl
from prompt_toolkit.search import SearchDirection
from prompt_toolkit.selection import SelectionState
from prompt_toolkit.widgets import SearchToolbar as PtkSearchToolbar
from euporie.core.commands import add_cmd
from euporie.core.current import get_app
from euporie.core.key_binding.registry import (
load_registered_bindings,
register_bindings,
)
def find_prev_next(direction: SearchDirection) -> None:
"""Find the previous or next search match."""
app = get_app()
layout = app.layout
control = app.layout.current_control
# Determine search buffer and searched buffer
search_buffer_control = None
if isinstance(control, SearchBufferControl):
search_buffer_control = control
control = layout.search_links[search_buffer_control]
elif isinstance(control, BufferControl):
if control.search_buffer_control is not None:
search_buffer_control = control.search_buffer_control
elif app.search_bar is not None:
search_buffer_control = app.search_bar.control
if isinstance(control, BufferControl) and search_buffer_control is not None:
# Update search_state.
search_state = control.search_state
search_state.direction = direction
# Apply search to buffer
buffer = control.buffer
buffer.apply_search(search_state, include_current_position=False, count=1)
# Set selection
buffer.selection_state = SelectionState(
buffer.cursor_position + len(search_state.text)
)
buffer.selection_state.enter_shift_mode()
The provided code snippet includes necessary dependencies for implementing the `find_next` function. Write a Python function `def find_next() -> None` to solve the following problem:
Find the next search match.
Here is the function:
def find_next() -> None:
"""Find the next search match."""
find_prev_next(SearchDirection.FORWARD) | Find the next search match. |
6,842 | from __future__ import annotations
import logging
from typing import TYPE_CHECKING
from prompt_toolkit.filters.app import is_searching
from prompt_toolkit.key_binding.vi_state import InputMode
from prompt_toolkit.layout.controls import BufferControl, SearchBufferControl
from prompt_toolkit.search import SearchDirection
from prompt_toolkit.selection import SelectionState
from prompt_toolkit.widgets import SearchToolbar as PtkSearchToolbar
from euporie.core.commands import add_cmd
from euporie.core.current import get_app
from euporie.core.key_binding.registry import (
load_registered_bindings,
register_bindings,
)
def find_prev_next(direction: SearchDirection) -> None:
"""Find the previous or next search match."""
app = get_app()
layout = app.layout
control = app.layout.current_control
# Determine search buffer and searched buffer
search_buffer_control = None
if isinstance(control, SearchBufferControl):
search_buffer_control = control
control = layout.search_links[search_buffer_control]
elif isinstance(control, BufferControl):
if control.search_buffer_control is not None:
search_buffer_control = control.search_buffer_control
elif app.search_bar is not None:
search_buffer_control = app.search_bar.control
if isinstance(control, BufferControl) and search_buffer_control is not None:
# Update search_state.
search_state = control.search_state
search_state.direction = direction
# Apply search to buffer
buffer = control.buffer
buffer.apply_search(search_state, include_current_position=False, count=1)
# Set selection
buffer.selection_state = SelectionState(
buffer.cursor_position + len(search_state.text)
)
buffer.selection_state.enter_shift_mode()
The provided code snippet includes necessary dependencies for implementing the `find_previous` function. Write a Python function `def find_previous() -> None` to solve the following problem:
Find the previous search match.
Here is the function:
def find_previous() -> None:
"""Find the previous search match."""
find_prev_next(SearchDirection.BACKWARD) | Find the previous search match. |
6,843 | from __future__ import annotations
import logging
from typing import TYPE_CHECKING
from prompt_toolkit.filters.app import is_searching
from prompt_toolkit.key_binding.vi_state import InputMode
from prompt_toolkit.layout.controls import BufferControl, SearchBufferControl
from prompt_toolkit.search import SearchDirection
from prompt_toolkit.selection import SelectionState
from prompt_toolkit.widgets import SearchToolbar as PtkSearchToolbar
from euporie.core.commands import add_cmd
from euporie.core.current import get_app
from euporie.core.key_binding.registry import (
load_registered_bindings,
register_bindings,
)
log = logging.getLogger(__name__)
def stop_search() -> None:
"""Abort the search."""
layout = get_app().layout
buffer_control = layout.search_target_buffer_control
if buffer_control is None:
return
search_buffer_control = buffer_control.search_buffer_control
# Focus the previous control
layout.focus(layout.previous_control)
# Close the search toolbar
if search_buffer_control is not None:
del layout.search_links[search_buffer_control]
# Reset content of search control.
search_buffer_control.buffer.reset()
# Redraw everything
get_app().refresh()
name="accept-search",
filter=is_searching,
def get_app() -> BaseApp:
"""Get the current active (running) Application."""
from euporie.core.app import BaseApp
session = _current_app_session.get()
if isinstance(session.app, BaseApp):
return session.app
# Use a baseapp as our "DummyApplication"
return BaseApp()
The provided code snippet includes necessary dependencies for implementing the `accept_search` function. Write a Python function `def accept_search() -> None` to solve the following problem:
Accept the search input.
Here is the function:
def accept_search() -> None:
"""Accept the search input."""
layout = get_app().layout
search_buffer_control = layout.current_control
if not isinstance(search_buffer_control, BufferControl):
log.debug("Current control not a buffer control")
return
for control in layout.find_all_controls():
if (
isinstance(control, BufferControl)
and control.search_buffer_control == search_buffer_control
):
search_state = control.search_state
# Update search state.
if search_buffer_control.buffer.text:
search_state.text = search_buffer_control.buffer.text
# Apply search.
control.buffer.apply_search(
search_state, include_current_position=True, count=1
)
# Set selection on target control
buffer_control = layout.search_target_buffer_control
if buffer_control and control.is_focusable():
buffer = buffer_control.buffer
buffer.selection_state = SelectionState(
buffer.cursor_position + len(search_state.text)
)
buffer.selection_state.enter_shift_mode()
# Add query to history of search line.
search_buffer_control.buffer.append_to_history()
# Stop the search
stop_search() | Accept the search input. |
6,844 | from __future__ import annotations
import logging
from pathlib import Path
from typing import TYPE_CHECKING
from prompt_toolkit.cache import FastDictCache
from prompt_toolkit.completion import PathCompleter
from prompt_toolkit.data_structures import Point
from prompt_toolkit.filters.utils import to_filter
from prompt_toolkit.key_binding.key_bindings import KeyBindings, KeyBindingsBase
from prompt_toolkit.layout.containers import (
ConditionalContainer,
)
from prompt_toolkit.layout.controls import UIContent, UIControl
from prompt_toolkit.layout.screen import WritePosition
from prompt_toolkit.mouse_events import MouseButton, MouseEvent, MouseEventType
from prompt_toolkit.utils import Event
from upath import UPath
from euporie.core.app import get_app
from euporie.core.border import InsetGrid
from euporie.core.config import add_setting
from euporie.core.layout.containers import HSplit, VSplit, Window
from euporie.core.layout.decor import FocusedStyle
from euporie.core.margins import MarginContainer, ScrollbarMargin
from euporie.core.widgets.decor import Border
from euporie.core.widgets.forms import Button, Text
The provided code snippet includes necessary dependencies for implementing the `is_dir` function. Write a Python function `def is_dir(path: str | Path) -> bool | None` to solve the following problem:
Check if a path is a directory.
Here is the function:
def is_dir(path: str | Path) -> bool | None:
"""Check if a path is a directory."""
test_path = UPath(path)
try:
return test_path.is_dir()
except (ValueError, PermissionError, TypeError):
return None | Check if a path is a directory. |
6,845 | from __future__ import annotations
import logging
from abc import ABCMeta, abstractmethod
from pathlib import PurePath
from typing import TYPE_CHECKING
from prompt_toolkit.cache import SimpleCache
from prompt_toolkit.filters import buffer_has_focus
from prompt_toolkit.layout.containers import (
DynamicContainer,
to_container,
)
from euporie.core.config import add_setting
from euporie.core.convert.datum import Datum
from euporie.core.convert.formats import BASE64_FORMATS
from euporie.core.convert.mime import MIME_FORMATS
from euporie.core.convert.registry import find_route
from euporie.core.current import get_app
from euporie.core.layout.containers import HSplit
from euporie.core.widgets.display import Display
from euporie.core.widgets.layout import Box
from euporie.core.widgets.tree import JsonView
MIME_ORDER = [
"application/vnd.jupyter.widget-view+json",
"application/json",
"image/*",
"text/html",
"text/markdown",
"text/x-markdown",
"application/pdf",
"text/latex",
"text/x-python-traceback",
"text/stderr",
"text/*",
"*",
]
The provided code snippet includes necessary dependencies for implementing the `_calculate_mime_rank` function. Write a Python function `def _calculate_mime_rank(mime_data: tuple[str, Any]) -> int` to solve the following problem:
Score the richness of mime output types.
Here is the function:
def _calculate_mime_rank(mime_data: tuple[str, Any]) -> int:
"""Score the richness of mime output types."""
mime, data = mime_data
for i, ranked_mime in enumerate(MIME_ORDER):
# Uprank plain text with escape sequences
if mime == "text/plain" and "\x1b[" in data:
i -= 7
if PurePath(mime).match(ranked_mime):
return i
else:
return 999 | Score the richness of mime output types. |
6,846 | from __future__ import annotations
import logging
import os
import re
import shlex
import subprocess
import time
from base64 import b64decode
from datetime import datetime as dt
from functools import lru_cache
from typing import TYPE_CHECKING, ClassVar
from aenum import extend_enum
from prompt_toolkit.application.run_in_terminal import run_in_terminal
from prompt_toolkit.key_binding.key_processor import KeyProcessor, _Flush
from prompt_toolkit.keys import Keys
from prompt_toolkit.output import ColorDepth
from prompt_toolkit.utils import Event
from euporie.core.commands import add_cmd
from euporie.core.current import get_app
from euporie.core.filters import in_screen, in_tmux
from euporie.core.key_binding.registry import register_bindings
from euporie.core.style import DEFAULT_COLORS
def _have_termios_tty_fcntl() -> bool:
try:
import fcntl # noqa F401
import termios # noqa F401
import tty # noqa F401
except ModuleNotFoundError:
return False
else:
return True | null |
6,847 | from __future__ import annotations
import logging
import os
import re
import shlex
import subprocess
import time
from base64 import b64decode
from datetime import datetime as dt
from functools import lru_cache
from typing import TYPE_CHECKING, ClassVar
from aenum import extend_enum
from prompt_toolkit.application.run_in_terminal import run_in_terminal
from prompt_toolkit.key_binding.key_processor import KeyProcessor, _Flush
from prompt_toolkit.keys import Keys
from prompt_toolkit.output import ColorDepth
from prompt_toolkit.utils import Event
from euporie.core.commands import add_cmd
from euporie.core.current import get_app
from euporie.core.filters import in_screen, in_tmux
from euporie.core.key_binding.registry import register_bindings
from euporie.core.style import DEFAULT_COLORS
def get_app() -> BaseApp:
"""Get the current active (running) Application."""
from euporie.core.app import BaseApp
session = _current_app_session.get()
if isinstance(session.app, BaseApp):
return session.app
# Use a baseapp as our "DummyApplication"
return BaseApp()
in_screen = to_filter(os.environ.get("TERM", "").startswith("screen"))
in_tmux = to_filter(os.environ.get("TMUX") is not None)
The provided code snippet includes necessary dependencies for implementing the `passthrough` function. Write a Python function `def passthrough(cmd: str) -> str` to solve the following problem:
Wrap an escape sequence for terminal passthrough.
Here is the function:
def passthrough(cmd: str) -> str:
"""Wrap an escape sequence for terminal passthrough."""
if get_app().config.multiplexer_passthrough:
if in_tmux():
cmd = cmd.replace("\x1b", "\x1b\x1b")
cmd = f"\x1bPtmux;{cmd}\x1b\\"
elif in_screen():
# Screen limits escape sequences to 768 bytes, so we have to chunk it
cmd = "".join(
f"\x1bP{cmd[i: i+764]}\x1b\\" for i in range(0, len(cmd), 764)
)
return cmd | Wrap an escape sequence for terminal passthrough. |
6,848 | from __future__ import annotations
import logging
import os
import re
import shlex
import subprocess
import time
from base64 import b64decode
from datetime import datetime as dt
from functools import lru_cache
from typing import TYPE_CHECKING, ClassVar
from aenum import extend_enum
from prompt_toolkit.application.run_in_terminal import run_in_terminal
from prompt_toolkit.key_binding.key_processor import KeyProcessor, _Flush
from prompt_toolkit.keys import Keys
from prompt_toolkit.output import ColorDepth
from prompt_toolkit.utils import Event
from euporie.core.commands import add_cmd
from euporie.core.current import get_app
from euporie.core.filters import in_screen, in_tmux
from euporie.core.key_binding.registry import register_bindings
from euporie.core.style import DEFAULT_COLORS
def get_app() -> BaseApp:
"""Get the current active (running) Application."""
from euporie.core.app import BaseApp
session = _current_app_session.get()
if isinstance(session.app, BaseApp):
return session.app
# Use a baseapp as our "DummyApplication"
return BaseApp()
The provided code snippet includes necessary dependencies for implementing the `edit_in_editor` function. Write a Python function `def edit_in_editor(filename: str, line_number: int = 0) -> None` to solve the following problem:
Suspend the current app and edit a file in an external editor.
Here is the function:
def edit_in_editor(filename: str, line_number: int = 0) -> None:
"""Suspend the current app and edit a file in an external editor."""
def _open_file_in_editor(filename: str) -> None:
"""Call editor executable."""
# If the 'VISUAL' or 'EDITOR' environment variable has been set, use that.
# Otherwise, fall back to the first available editor that we can find.
for editor in [
os.environ.get("VISUAL"),
os.environ.get("EDITOR"),
"editor",
"micro",
"nano",
"pico",
"vi",
"emacs",
]:
if editor:
try:
# Use 'shlex.split()' because $VISUAL can contain spaces and quotes
subprocess.call([*shlex.split(editor), filename])
return
except OSError:
# Executable does not exist, try the next one.
pass
async def run() -> None:
# Open in editor
# (We need to use `run_in_terminal`, because not all editors go to
# the alternate screen buffer, and some could influence the cursor
# position)
await run_in_terminal(lambda: _open_file_in_editor(filename), in_executor=True)
get_app().create_background_task(run()) | Suspend the current app and edit a file in an external editor. |
6,849 | from __future__ import annotations
import bisect
import logging
import re
from abc import ABCMeta, abstractmethod
from base64 import standard_b64encode
from copy import copy
from datetime import date, datetime
from decimal import Decimal
from functools import partial
from typing import TYPE_CHECKING
from prompt_toolkit.filters.base import Condition
from prompt_toolkit.layout.containers import HSplit, VSplit
from prompt_toolkit.layout.processors import BeforeInput
from euporie.core.comm.base import Comm, CommView
from euporie.core.convert.datum import Datum
from euporie.core.data_structures import DiBool
from euporie.core.kernel import MsgCallbacks
from euporie.core.layout.decor import FocusedStyle
from euporie.core.widgets.cell_outputs import CellOutputArea
from euporie.core.widgets.display import Display
from euporie.core.widgets.forms import (
Button,
Checkbox,
Dropdown,
Label,
LabelledWidget,
Progress,
Select,
Slider,
Swatch,
Text,
ToggleButton,
ToggleButtons,
)
from euporie.core.widgets.layout import (
AccordionSplit,
Box,
ReferencedSplit,
TabbedSplit,
)
_binary_types = (memoryview, bytearray, bytes)
The provided code snippet includes necessary dependencies for implementing the `_separate_buffers` function. Write a Python function `def _separate_buffers( substate: dict | list | tuple, path: list[str | int], buffer_paths: list[list[str | int]], buffers: MutableSequence[memoryview | bytearray | bytes], ) -> dict | list | tuple` to solve the following problem:
Remove binary types from dicts and lists, but keep track of their paths. Any part of the dict/list that needs modification will be cloned, so the original stays untouched. Args: substate: A dictionary or list like containing binary data path: A list of dictionary/list keys describing the path root to the substate buffer_paths: A list to which binary buffer paths will be added buffers: A list to which binary buffers will be added Raises: ValueError: Raised when the substate is not a list, tuple or dictionary Returns: The updated substrate without buffers
Here is the function:
def _separate_buffers(
substate: dict | list | tuple,
path: list[str | int],
buffer_paths: list[list[str | int]],
buffers: MutableSequence[memoryview | bytearray | bytes],
) -> dict | list | tuple:
"""Remove binary types from dicts and lists, but keep track of their paths.
Any part of the dict/list that needs modification will be cloned, so the original
stays untouched.
Args:
substate: A dictionary or list like containing binary data
path: A list of dictionary/list keys describing the path root to the substate
buffer_paths: A list to which binary buffer paths will be added
buffers: A list to which binary buffers will be added
Raises:
ValueError: Raised when the substate is not a list, tuple or dictionary
Returns:
The updated substrate without buffers
"""
cloned_substrate: list | dict | None = None
if isinstance(substate, (list, tuple)):
for i, v in enumerate(substate):
if isinstance(v, _binary_types):
if cloned_substrate is None:
cloned_substrate = list(substate) # shallow clone list/tuple
assert isinstance(cloned_substrate, list)
cloned_substrate[i] = None
buffers.append(v)
buffer_paths.append([*path, i])
elif isinstance(v, (dict, list, tuple)):
vnew = _separate_buffers(v, [*path, i], buffer_paths, buffers)
if v is not vnew: # only assign when value changed
if cloned_substrate is None:
cloned_substrate = list(substate) # shallow clone list/tuple
assert isinstance(cloned_substrate, list)
cloned_substrate[i] = vnew
elif isinstance(substate, dict):
for k, v in substate.items():
if isinstance(v, _binary_types):
if cloned_substrate is None:
cloned_substrate = dict(substate) # shallow clone dict
del cloned_substrate[k]
buffers.append(v)
buffer_paths.append([*path, k])
elif isinstance(v, (dict, list, tuple)):
vnew = _separate_buffers(v, [*path, k], buffer_paths, buffers)
if v is not vnew: # only assign when value changed
if cloned_substrate is None:
cloned_substrate = dict(substate) # clone list/tuple
cloned_substrate[k] = vnew
else:
raise ValueError("expected state to be a list or dict, not %r" % substate)
return cloned_substrate if cloned_substrate is not None else substate | Remove binary types from dicts and lists, but keep track of their paths. Any part of the dict/list that needs modification will be cloned, so the original stays untouched. Args: substate: A dictionary or list like containing binary data path: A list of dictionary/list keys describing the path root to the substate buffer_paths: A list to which binary buffer paths will be added buffers: A list to which binary buffers will be added Raises: ValueError: Raised when the substate is not a list, tuple or dictionary Returns: The updated substrate without buffers |
6,850 | from __future__ import annotations
import bisect
import logging
import re
from abc import ABCMeta, abstractmethod
from base64 import standard_b64encode
from copy import copy
from datetime import date, datetime
from decimal import Decimal
from functools import partial
from typing import TYPE_CHECKING
from prompt_toolkit.filters.base import Condition
from prompt_toolkit.layout.containers import HSplit, VSplit
from prompt_toolkit.layout.processors import BeforeInput
from euporie.core.comm.base import Comm, CommView
from euporie.core.convert.datum import Datum
from euporie.core.data_structures import DiBool
from euporie.core.kernel import MsgCallbacks
from euporie.core.layout.decor import FocusedStyle
from euporie.core.widgets.cell_outputs import CellOutputArea
from euporie.core.widgets.display import Display
from euporie.core.widgets.forms import (
Button,
Checkbox,
Dropdown,
Label,
LabelledWidget,
Progress,
Select,
Slider,
Swatch,
Text,
ToggleButton,
ToggleButtons,
)
from euporie.core.widgets.layout import (
AccordionSplit,
Box,
ReferencedSplit,
TabbedSplit,
)
WIDGET_MODELS: dict[str, type[IpyWidgetComm]] = {}
class IpyWidgetComm(Comm, metaclass=ABCMeta):
"""A Comm object which represents ipython widgets."""
target_name = "jupyter.widget"
def __init__(
self,
comm_container: KernelTab,
comm_id: str,
data: dict,
buffers: Sequence[bytes],
) -> None:
"""Create a new instance of the ipywidget."""
super().__init__(comm_container, comm_id, data, buffers)
self.sync = True
def __init_subclass__(cls, **kwargs: Any) -> None:
"""Add ipywidget model classes to a registry when they are created."""
super().__init_subclass__(**kwargs)
if cls.__name__.endswith("Model"):
WIDGET_MODELS[cls.__name__] = cls
def set_state(self, key: str, value: JSONType) -> None:
"""Send a ``comm_msg`` to the kernel with local state changes."""
if self.sync:
self.data.setdefault("state", {})[key] = value
if self.comm_container.kernel:
self.comm_container.kernel.kc_comm(
comm_id=self.comm_id,
data={"method": "update", "state": {key: value}},
)
self.update_views({key: value})
def process_data(self, data: dict, buffers: Sequence[bytes]) -> None:
"""Handle incoming Comm update messages, updating the state and views."""
# Add buffers to data based on buffer paths
self.buffers = list(buffers)
for buffer_path, buffer in zip(
data.get("buffer_paths", []),
buffers,
):
parent = data["state"]
for key in buffer_path[:-1]:
parent = parent[key]
parent[buffer_path[-1]] = buffer
method = data.get("method")
if method is None:
self.data = data
elif method == "update":
changes = data.get("state", {})
self.data["state"].update(changes)
self.update_views(changes)
def create_view(self, parent: OutputParent) -> CommView:
"""Abstract method for creating a view of the ipywidget."""
def _get_embed_state(self) -> dict[str, Any]:
"""Convert the ipywidgets state to embeddable json."""
buffer_paths: list[list[str | int]] = []
buffers: list[bytes] = []
state = _separate_buffers(self.data["state"], [], buffer_paths, buffers)
assert isinstance(state, dict)
return {
"model_name": state.get("_model_name"),
"model_module": state.get("_model_module"),
"model_module_version": state.get("_model_module_version"),
"state": {
**dict(state.items()),
"buffers": [
{
"encoding": "base64",
"path": p,
"data": standard_b64encode(d).decode("ascii"),
}
for p, d in zip(buffer_paths, buffers)
],
},
}
class UnimplementedModel(IpyWidgetComm):
"""An ipywidget used to represent unimplemented widgets."""
def create_view(self, parent: OutputParent) -> CommView:
"""Create a new view."""
return CommView(Display(Datum("[Widget not implemented]", format="ansi")))
The provided code snippet includes necessary dependencies for implementing the `open_comm_ipywidgets` function. Write a Python function `def open_comm_ipywidgets( comm_container: KernelTab, comm_id: str, data: dict, buffers: Sequence[bytes], ) -> IpyWidgetComm` to solve the following problem:
Create a new Comm for an :py:mod:`ipywidgets` widget. The relevant widget model is selected based on the model name given in the ``comm_open`` message data. Args: comm_container: The notebook this Comm belongs to comm_id: The ID of the Comm data: The data field from the ``comm_open`` message buffers: The buffers field from the ``comm_open`` message Returns: The initialized widget Comm object.
Here is the function:
def open_comm_ipywidgets(
comm_container: KernelTab,
comm_id: str,
data: dict,
buffers: Sequence[bytes],
) -> IpyWidgetComm:
"""Create a new Comm for an :py:mod:`ipywidgets` widget.
The relevant widget model is selected based on the model name given in the
``comm_open`` message data.
Args:
comm_container: The notebook this Comm belongs to
comm_id: The ID of the Comm
data: The data field from the ``comm_open`` message
buffers: The buffers field from the ``comm_open`` message
Returns:
The initialized widget Comm object.
"""
model_name = data.get("state", {}).get("_model_name")
# Skip type checking due to https://github.com/python/mypy/issues/3115
return WIDGET_MODELS.get(model_name, UnimplementedModel)(
comm_container, comm_id, data, buffers
) # type: ignore | Create a new Comm for an :py:mod:`ipywidgets` widget. The relevant widget model is selected based on the model name given in the ``comm_open`` message data. Args: comm_container: The notebook this Comm belongs to comm_id: The ID of the Comm data: The data field from the ``comm_open`` message buffers: The buffers field from the ``comm_open`` message Returns: The initialized widget Comm object. |
6,851 | from __future__ import annotations
from typing import TYPE_CHECKING
from euporie.core.comm.base import UnimplementedComm
from euporie.core.comm.ipywidgets import open_comm_ipywidgets
TARGET_CLASSES: dict[str, Callable[[KernelTab, str, dict, Sequence[bytes]], Comm]] = {
"jupyter.widget": open_comm_ipywidgets
}
class Comm(metaclass=ABCMeta):
"""A base-class for all comm objects, which support syncing traits with the kernel."""
def __init__(
self,
comm_container: KernelTab,
comm_id: str,
data: dict,
buffers: Sequence[bytes],
) -> None:
"""Create a new instance of the Comm.
Args:
comm_container: The container this Comm belongs to
comm_id: The ID of the Comm
data: The data field from the ``comm_open`` message
buffers: The buffers field from the ``comm_open`` message
"""
self.comm_container = comm_container
self.comm_id = comm_id
self.data: dict[str, Any] = {}
self.buffers: Sequence[bytes] = []
self.views: WeakKeyDictionary[CommView, OutputParent] = WeakKeyDictionary()
self.process_data(data, buffers)
def process_data(self, data: dict, buffers: Sequence[bytes]) -> None:
"""Process a comm_msg data / buffers."""
def _get_embed_state(self) -> dict:
return {}
def create_view(self, parent: OutputParent) -> CommView:
"""Create a new :class:`CommView` for this Comm."""
return CommView(Display(Datum("[Object cannot be rendered]", format="ansi")))
def new_view(self, parent: OutputParent) -> CommView:
"""Create and register a new :class:`CommView` for this Comm."""
view = self.create_view(parent)
self.views[view] = parent
return view
def update_views(self, changes: dict) -> None:
"""Update all the active views of this Comm."""
for view, parent in self.views.items():
view.update(changes)
parent.refresh(now=False)
get_app().invalidate()
class UnimplementedComm(Comm):
"""Represent a Comm object which is not implemented in euporie.core."""
def process_data(self, data: dict, buffers: Sequence[bytes]) -> None:
"""Doe nothing when data is received."""
self.data = data
self.buffers = buffers
The provided code snippet includes necessary dependencies for implementing the `open_comm` function. Write a Python function `def open_comm( comm_container: KernelTab, content: dict[str, Any], buffers: Sequence[bytes], ) -> Comm` to solve the following problem:
Create a new object respsenting a Comm. The class used to represent the Comm is determined by the "target_class" given in the ``comm_open`` message. Args: comm_container: The notebook this comm belongs to content: The content of the ``comm_open`` message buffers: A list of binary data buffers sent with the ``comm_open`` message Returns: A class representing the comm
Here is the function:
def open_comm(
comm_container: KernelTab,
content: dict[str, Any],
buffers: Sequence[bytes],
) -> Comm:
"""Create a new object respsenting a Comm.
The class used to represent the Comm is determined by the "target_class" given in
the ``comm_open`` message.
Args:
comm_container: The notebook this comm belongs to
content: The content of the ``comm_open`` message
buffers: A list of binary data buffers sent with the ``comm_open`` message
Returns:
A class representing the comm
"""
target_name = content.get("target_name", "")
return TARGET_CLASSES.get(target_name, UnimplementedComm)(
# comm_container=
comm_container,
# comm_id=
str(content.get("comm_id")),
# data=
content.get("data", {}),
# buffers=
buffers,
) | Create a new object respsenting a Comm. The class used to represent the Comm is determined by the "target_class" given in the ``comm_open`` message. Args: comm_container: The notebook this comm belongs to content: The content of the ``comm_open`` message buffers: A list of binary data buffers sent with the ``comm_open`` message Returns: A class representing the comm |
6,852 | from __future__ import annotations
import argparse
import json
import logging
import os
import sys
from ast import literal_eval
from collections import ChainMap
from functools import partial
from pathlib import Path
from typing import TYPE_CHECKING, Protocol, TextIO, cast
import fastjsonschema
from platformdirs import user_config_dir
from prompt_toolkit.filters.base import Condition
from prompt_toolkit.filters.utils import to_filter
from prompt_toolkit.utils import Event
from upath import UPath
from euporie.core import __app_name__, __copyright__, __version__
from euporie.core.commands import add_cmd, get_cmd
class Setting:
"""A single configuration item."""
def __init__(
self,
name: str,
default: Any,
help_: str,
description: str,
type_: Callable[[Any], Any] | None = None,
title: str | None = None,
choices: list[Any] | None = None,
action: argparse.Action | str | None = None,
flags: list[str] | None = None,
schema: dict[str, Any] | None = None,
nargs: str | int | None = None,
hidden: FilterOrBool = False,
hooks: list[Callable[[Setting], None]] | None = None,
cmd_filter: FilterOrBool = True,
**kwargs: Any,
) -> None:
"""Create a new configuration item."""
self.name = name
self.default = default
self._value = default
self.title = title or self.name.replace("_", " ")
self.help = help_
self.description = description
self.choices = choices
self.type = type_ or type(default)
self.action = action or TYPE_ACTIONS.get(self.type)
self.flags = flags or [f"--{name.replace('_','-')}"]
self._schema: dict[str, Any] = {
"type": _SCHEMA_TYPES.get(self.type),
**(schema or {}),
}
self.nargs = nargs
self.hidden = to_filter(hidden)
self.kwargs = kwargs
self.cmd_filter = cmd_filter
self.event = Event(self)
for hook in hooks or []:
self.event += hook
self.register_commands()
def register_commands(self) -> None:
"""Register commands to set this setting."""
name = self.name.replace("_", "-")
schema = self.schema
if schema.get("type") == "array":
for choice in self.choices or schema.get("items", {}).get("enum") or []:
add_cmd(
name=f"toggle-{name}-{choice}",
hidden=self.hidden,
toggled=Condition(partial(lambda x: x in self.value, choice)),
title=f"Add {choice} to {self.title} setting",
menu_title=str(choice).replace("_", " ").capitalize(),
description=f'Add or remove "{choice}" to or from the list of "{self.name}"',
filter=self.cmd_filter,
)(
partial(
lambda choice: (
self.value.remove
if choice in self.value
else self.value.append
)(choice),
choice,
)
)
elif self.type == bool:
def _toggled() -> bool:
from euporie.core.current import get_app
app = get_app()
value = app.config.get(self.name)
return bool(getattr(app.config, self.name, not value))
toggled_filter = Condition(_toggled)
add_cmd(
name=f"toggle-{name}",
toggled=toggled_filter,
hidden=self.hidden,
title=f"Toggle {self.title}",
menu_title=self.kwargs.get("menu_title", self.title.capitalize()),
description=self.help,
filter=self.cmd_filter,
)(self.toggle)
elif self.type == int or self.choices is not None:
add_cmd(
name=f"switch-{name}",
hidden=self.hidden,
title=f"Switch {self.title}",
menu_title=self.kwargs.get("menu_title"),
description=f'Switch the value of the "{self.name}" configuration option.',
filter=self.cmd_filter,
)(self.toggle)
for choice in self.choices or schema.get("enum", []) or []:
add_cmd(
name=f"set-{name}-{choice}",
hidden=self.hidden,
toggled=Condition(partial(lambda x: self.value == x, choice)),
title=f"Set {self.title} to {choice}",
menu_title=str(choice).replace("_", " ").capitalize(),
description=f'Set the value of the "{self.name}" '
f'configuration option to "{choice}"',
filter=self.cmd_filter,
)(partial(setattr, self, "value", choice))
def toggle(self) -> None:
"""Toggle the setting's value."""
if self.type == bool:
new = not self.value
elif (
self.type == int
and "minimum" in (schema := self.schema)
and "maximum" in schema
):
new = schema["minimum"] + (self.value - schema["minimum"] + 1) % (
schema["maximum"] + 1
)
elif self.choices is not None:
new = self.choices[(self.choices.index(self.value) + 1) % len(self.choices)]
else:
raise NotImplementedError
self.value = new
def value(self) -> Any:
"""Return the current value."""
return self._value
def value(self, new: Any) -> None:
"""Set the current value."""
self._value = new
self.event.fire()
def schema(self) -> dict[str, Any]:
"""Return a json schema property for the config item."""
schema = {
"description": self.help,
**({"default": self.default} if self.default is not None else {}),
**self._schema,
}
if self.choices:
if self.nargs == "*" or "items" in schema:
schema["items"]["enum"] = self.choices
else:
schema["enum"] = self.choices
return schema
def menu(self) -> MenuItem:
"""Return a menu item for the setting."""
from euporie.core.widgets.menu import MenuItem
choices = (self.choices or self.schema.get("enum", [])) or []
if choices:
return MenuItem(
self.title.capitalize(),
children=[
cmd.menu
for cmd in sorted(
(
get_cmd(f"set-{self.name.replace('_', '-')}-{choice}")
for choice in choices
),
key=lambda x: x.menu_title,
)
],
description=self.help,
)
elif self.type in (bool, int):
return get_cmd(f"toggle-{self.name.replace('_', '-')}").menu
else:
raise NotImplementedError
def parser_args(self) -> tuple[list[str], dict[str, Any]]:
"""Return arguments for construction of an :class:`argparse.ArgumentParser`."""
# Do not set defaults for command line arguments, as default values
# would override values set in the configuration file
args = self.flags or [self.name]
kwargs: dict[str, Any] = {
"action": self.action,
"help": self.help,
}
if self.nargs:
kwargs["nargs"] = self.nargs
if self.type is not None and self.name != "version":
kwargs["type"] = self.type
if self.choices:
kwargs["choices"] = self.choices
if "version" in self.kwargs:
kwargs["version"] = self.kwargs["version"]
if "const" in self.kwargs:
kwargs["const"] = self.kwargs["const"]
return args, kwargs
def __repr__(self) -> str:
"""Represent a :py:class`Setting` instance as a string."""
return f"<Setting {self.name}={self.value.__repr__()}>"
class Config:
"""A configuration store."""
settings: ClassVar[dict[str, Setting]] = {}
conf_file_name = "config.json"
def __init__(self) -> None:
"""Create a new configuration object instance."""
self.app_name: str = "base"
self.app_cls: type[ConfigurableApp] | None = None
def _save(self, setting: Setting) -> None:
"""Save settings to user's configuration file."""
json_data = self.load_config_file()
json_data.setdefault(self.app_name, {})[setting.name] = setting.value
if self.valid_user:
log.debug("Saving setting `%s`", setting)
with self.config_file_path.open("w") as f:
json.dump(json_data, f, indent=2)
def load(self, cls: type[ConfigurableApp]) -> None:
"""Load the command line, environment, and user configuration."""
from euporie.core.log import setup_logs
self.app_cls = cls
self.app_name = cls.name
log.debug("Loading config for %s", self.app_name)
user_conf_dir = Path(user_config_dir(__app_name__, appauthor=None))
user_conf_dir.mkdir(exist_ok=True, parents=True)
self.config_file_path = (user_conf_dir / self.conf_file_name).with_suffix(
".json"
)
self.valid_user = True
config_maps = {
# Load command line arguments
"command line arguments": self.load_args(),
# Load app specific env vars
"app-specific environment variable": self.load_env(app_name=self.app_name),
# Load global env vars
"global environment variable": self.load_env(),
# Load app specific user config
"app-specific user configuration": self.load_user(app_name=self.app_name),
# Load global user config
"user configuration": self.load_user(),
}
set_values = ChainMap(*config_maps.values())
for name, setting in Config.settings.items():
if setting.name in set_values:
# Set value without triggering hooks
setting._value = set_values[name]
setting.event += self._save
# Set-up logs
setup_logs(self)
# Save a list of unknown configuration options so we can warn about them once
# the logs are configured
for map_name, map_values in config_maps.items():
for option_name in map_values.keys() - Config.settings.keys():
if not isinstance(set_values[option_name], dict):
log.warning(
"Configuration option '%s' not recognised in %s",
option_name,
map_name,
)
def schema(self) -> dict[str, Any]:
"""Return a JSON schema for the config."""
return {
"title": "Euporie Configuration",
"description": "A configuration for euporie",
"type": "object",
"properties": {name: item.schema for name, item in self.settings.items()},
}
def load_parser(self) -> argparse.ArgumentParser:
"""Construct an :py:class:`ArgumentParser`."""
parser = ArgumentParser(
description=self.app_cls.__doc__,
epilog=__copyright__,
allow_abbrev=True,
formatter_class=argparse.MetavarTypeHelpFormatter,
)
# Add options to the relevant subparsers
for setting in self.settings.values():
args, kwargs = setting.parser_args
parser.add_argument(*args, **kwargs)
return parser
def load_args(self) -> dict[str, Any]:
"""Attempt to load configuration settings from commandline flags."""
result = {}
# Parse known arguments
namespace, remainder = self.load_parser().parse_known_intermixed_args()
# Update argv to leave the remaining arguments for subsequent apps
sys.argv[1:] = remainder
# Validate arguments
for name, value in vars(namespace).items():
if value is not None:
# Convert to json and back to attain json types
json_data = json.loads(_json_encoder.encode({name: value}))
try:
fastjsonschema.validate(self.schema, json_data)
except fastjsonschema.JsonSchemaValueException as error:
log.warning("Error in command line parameter `%s`: %s", name, error)
log.warning("%s: %s", name, value)
else:
result[name] = value
return result
def load_env(self, app_name: str = "") -> dict[str, Any]:
"""Attempt to load configuration settings from environment variables."""
result = {}
for name, setting in self.settings.items():
if app_name:
env = f"{__app_name__.upper()}_{self.app_name.upper()}_{setting.name.upper()}"
else:
env = f"{__app_name__.upper()}_{setting.name.upper()}"
if env in os.environ:
value = os.environ.get(env)
parsed_value: Any = value
# Attempt to parse the value as a literal
if value:
try:
parsed_value = literal_eval(value)
except (
ValueError,
TypeError,
SyntaxError,
MemoryError,
RecursionError,
):
pass
# Attempt to cast the value to the desired type
try:
parsed_value = setting.type(value)
except (ValueError, TypeError):
log.warning(
"Environment variable `%s` not understood" " - `%s` expected",
env,
setting.type.__name__,
)
else:
json_data = json.loads(_json_encoder.encode({name: parsed_value}))
try:
fastjsonschema.validate(self.schema, json_data)
except fastjsonschema.JsonSchemaValueException as error:
log.error("Error in environment variable: `%s`\n%s", env, error)
else:
result[name] = parsed_value
return result
def load_config_file(self) -> dict[str, Any]:
"""Attempt to load JSON configuration file."""
results = {}
assert isinstance(self.config_file_path, Path)
if self.valid_user and self.config_file_path.exists():
with self.config_file_path.open() as f:
try:
json_data = json.load(f)
except json.decoder.JSONDecodeError:
log.error(
"Could not parse the configuration file: %s\nIs it valid json?",
self.config_file_path,
)
self.valid_user = False
else:
results.update(json_data)
return results
def load_user(self, app_name: str = "") -> dict[str, Any]:
"""Attempt to load JSON configuration file."""
results = {}
# Load config file
json_data = self.load_config_file()
# Load section for the current app
if app_name:
json_data = json_data.get(self.app_name, {})
# Validate the configuration file
try:
# Validate a copy so the original data is not modified
fastjsonschema.validate(self.schema, dict(json_data))
except fastjsonschema.JsonSchemaValueException as error:
log.warning("Error in config file: `%s`: %s", self.config_file_pathi, error)
self.valid_user = False
else:
results.update(json_data)
return results
def get(self, name: str, default: Any = None) -> Any:
"""Access a configuration value, falling back to the default value if unset.
Args:
name: The name of the attribute to access.
default: The value to return if the name is not found
Returns:
The configuration variable value.
"""
if name in self.settings:
return self.settings[name].value
else:
return default
def get_item(self, name: str) -> Any:
"""Access a configuration item.
Args:
name: The name of the attribute to access.
Returns:
The configuration item.
"""
return self.settings.get(name)
def filter(self, name: str) -> Filter:
"""Return a :py:class:`Filter` for a configuration item."""
return Condition(partial(self.get, name))
def __getattr__(self, name: str) -> Any:
"""Enable access of config elements via dotted attributes.
Args:
name: The name of the attribute to access.
Returns:
The configuration variable value.
"""
return self.get(name)
def __setitem__(self, name: str, value: Any) -> None:
"""Set a configuration attribute.
Args:
name: The name of the attribute to set.
value: The value to give the attribute.
"""
setting = self.settings[name]
setting.value = value
The provided code snippet includes necessary dependencies for implementing the `add_setting` function. Write a Python function `def add_setting( name: str, default: Any, help_: str, description: str, type_: Callable[[Any], Any] | None = None, action: argparse.Action | str | None = None, flags: list[str] | None = None, schema: dict[str, Any] | None = None, nargs: str | int | None = None, hidden: FilterOrBool = False, hooks: list[Callable[[Setting], None]] | None = None, cmd_filter: FilterOrBool = True, **kwargs: Any, ) -> None` to solve the following problem:
Register a new config item.
Here is the function:
def add_setting(
name: str,
default: Any,
help_: str,
description: str,
type_: Callable[[Any], Any] | None = None,
action: argparse.Action | str | None = None,
flags: list[str] | None = None,
schema: dict[str, Any] | None = None,
nargs: str | int | None = None,
hidden: FilterOrBool = False,
hooks: list[Callable[[Setting], None]] | None = None,
cmd_filter: FilterOrBool = True,
**kwargs: Any,
) -> None:
"""Register a new config item."""
Config.settings[name] = Setting(
name=name,
default=default,
help_=help_,
description=description,
type_=type_,
action=action,
flags=flags,
schema=schema,
nargs=nargs,
hidden=hidden,
hooks=hooks,
cmd_filter=cmd_filter,
**kwargs,
) | Register a new config item. |
6,853 | from __future__ import annotations
import os
from functools import lru_cache, partial, reduce
from importlib import import_module
from shutil import which
from typing import TYPE_CHECKING
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.filters import (
Condition,
emacs_insert_mode,
emacs_mode,
to_filter,
vi_insert_mode,
vi_mode,
vi_replace_mode,
)
from euporie.core.key_binding.micro_state import MicroInputMode
The provided code snippet includes necessary dependencies for implementing the `command_exists` function. Write a Python function `def command_exists(*cmds: str) -> Filter` to solve the following problem:
Verify a list of external commands exist on the system.
Here is the function:
def command_exists(*cmds: str) -> Filter:
"""Verify a list of external commands exist on the system."""
filters = [
Condition(partial(lambda x: bool(which(cmd)), cmd)) # noqa: B023
for cmd in cmds
]
return reduce(lambda a, b: a & b, filters, to_filter(True)) | Verify a list of external commands exist on the system. |
6,854 | from __future__ import annotations
import os
from functools import lru_cache, partial, reduce
from importlib import import_module
from shutil import which
from typing import TYPE_CHECKING
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.filters import (
Condition,
emacs_insert_mode,
emacs_mode,
to_filter,
vi_insert_mode,
vi_mode,
vi_replace_mode,
)
from euporie.core.key_binding.micro_state import MicroInputMode
The provided code snippet includes necessary dependencies for implementing the `have_modules` function. Write a Python function `def have_modules(*modules: str) -> Filter` to solve the following problem:
Verify a list of python modules are importable.
Here is the function:
def have_modules(*modules: str) -> Filter:
"""Verify a list of python modules are importable."""
def try_import(module: str) -> bool:
try:
import_module(module)
except ModuleNotFoundError:
return False
else:
return True
filters = [Condition(partial(try_import, module)) for module in modules]
return reduce(lambda a, b: a & b, filters, to_filter(True)) | Verify a list of python modules are importable. |
6,855 | from __future__ import annotations
import os
from functools import lru_cache, partial, reduce
from importlib import import_module
from shutil import which
from typing import TYPE_CHECKING
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.filters import (
Condition,
emacs_insert_mode,
emacs_mode,
to_filter,
vi_insert_mode,
vi_mode,
vi_replace_mode,
)
from euporie.core.key_binding.micro_state import MicroInputMode
The provided code snippet includes necessary dependencies for implementing the `have_ruff` function. Write a Python function `def have_ruff() -> bool` to solve the following problem:
Determine if ruff is available.
Here is the function:
def have_ruff() -> bool:
"""Determine if ruff is available."""
try:
import ruff # noqa F401
except ModuleNotFoundError:
return False
else:
return True | Determine if ruff is available. |
6,856 | from __future__ import annotations
import os
from functools import lru_cache, partial, reduce
from importlib import import_module
from shutil import which
from typing import TYPE_CHECKING
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.filters import (
Condition,
emacs_insert_mode,
emacs_mode,
to_filter,
vi_insert_mode,
vi_mode,
vi_replace_mode,
)
from euporie.core.key_binding.micro_state import MicroInputMode
The provided code snippet includes necessary dependencies for implementing the `have_black` function. Write a Python function `def have_black() -> bool` to solve the following problem:
Determine if black is available.
Here is the function:
def have_black() -> bool:
"""Determine if black is available."""
try:
import black.const # noqa F401
except ModuleNotFoundError:
return False
else:
return True | Determine if black is available. |
6,857 | from __future__ import annotations
import os
from functools import lru_cache, partial, reduce
from importlib import import_module
from shutil import which
from typing import TYPE_CHECKING
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.filters import (
Condition,
emacs_insert_mode,
emacs_mode,
to_filter,
vi_insert_mode,
vi_mode,
vi_replace_mode,
)
from euporie.core.key_binding.micro_state import MicroInputMode
The provided code snippet includes necessary dependencies for implementing the `have_isort` function. Write a Python function `def have_isort() -> bool` to solve the following problem:
Determine if isort is available.
Here is the function:
def have_isort() -> bool:
"""Determine if isort is available."""
try:
import isort # noqa F401
except ModuleNotFoundError:
return False
else:
return True | Determine if isort is available. |
6,858 | from __future__ import annotations
import os
from functools import lru_cache, partial, reduce
from importlib import import_module
from shutil import which
from typing import TYPE_CHECKING
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.filters import (
Condition,
emacs_insert_mode,
emacs_mode,
to_filter,
vi_insert_mode,
vi_mode,
vi_replace_mode,
)
from euporie.core.key_binding.micro_state import MicroInputMode
The provided code snippet includes necessary dependencies for implementing the `have_ssort` function. Write a Python function `def have_ssort() -> bool` to solve the following problem:
Determine if ssort is available.
Here is the function:
def have_ssort() -> bool:
"""Determine if ssort is available."""
try:
import ssort # noqa F401
except ModuleNotFoundError:
return False
else:
return True | Determine if ssort is available. |
6,859 | from __future__ import annotations
import os
from functools import lru_cache, partial, reduce
from importlib import import_module
from shutil import which
from typing import TYPE_CHECKING
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.filters import (
Condition,
emacs_insert_mode,
emacs_mode,
to_filter,
vi_insert_mode,
vi_mode,
vi_replace_mode,
)
from euporie.core.key_binding.micro_state import MicroInputMode
def get_app() -> BaseApp:
"""Get the current active (running) Application."""
from euporie.core.app import BaseApp
session = _current_app_session.get()
if isinstance(session.app, BaseApp):
return session.app
# Use a baseapp as our "DummyApplication"
return BaseApp()
def get_app() -> NotebookApp:
"""Get the current application."""
return cast("NotebookApp", ptk_get_app())
The provided code snippet includes necessary dependencies for implementing the `has_suggestion` function. Write a Python function `def has_suggestion() -> bool` to solve the following problem:
Determine if the current buffer can display a suggestion.
Here is the function:
def has_suggestion() -> bool:
"""Determine if the current buffer can display a suggestion."""
from prompt_toolkit.application.current import get_app
app = get_app()
return (
app.current_buffer.suggestion is not None
and len(app.current_buffer.suggestion.text) > 0
and app.current_buffer.document.is_cursor_at_the_end_of_line
) | Determine if the current buffer can display a suggestion. |
6,860 | from __future__ import annotations
import os
from functools import lru_cache, partial, reduce
from importlib import import_module
from shutil import which
from typing import TYPE_CHECKING
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.filters import (
Condition,
emacs_insert_mode,
emacs_mode,
to_filter,
vi_insert_mode,
vi_mode,
vi_replace_mode,
)
from euporie.core.key_binding.micro_state import MicroInputMode
def get_app() -> BaseApp:
"""Get the current active (running) Application."""
from euporie.core.app import BaseApp
session = _current_app_session.get()
if isinstance(session.app, BaseApp):
return session.app
# Use a baseapp as our "DummyApplication"
return BaseApp()
def get_app() -> NotebookApp:
"""Get the current application."""
return cast("NotebookApp", ptk_get_app())
The provided code snippet includes necessary dependencies for implementing the `has_dialog` function. Write a Python function `def has_dialog() -> bool` to solve the following problem:
Determine if a dialog is being displayed.
Here is the function:
def has_dialog() -> bool:
"""Determine if a dialog is being displayed."""
from prompt_toolkit.layout.containers import ConditionalContainer
from euporie.core.current import get_app
app = get_app()
for dialog in app.dialogs.values():
if isinstance(dialog.content, ConditionalContainer) and dialog.content.filter():
return True
return False | Determine if a dialog is being displayed. |
6,861 | from __future__ import annotations
import os
from functools import lru_cache, partial, reduce
from importlib import import_module
from shutil import which
from typing import TYPE_CHECKING
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.filters import (
Condition,
emacs_insert_mode,
emacs_mode,
to_filter,
vi_insert_mode,
vi_mode,
vi_replace_mode,
)
from euporie.core.key_binding.micro_state import MicroInputMode
def get_app() -> BaseApp:
"""Get the current active (running) Application."""
from euporie.core.app import BaseApp
session = _current_app_session.get()
if isinstance(session.app, BaseApp):
return session.app
# Use a baseapp as our "DummyApplication"
return BaseApp()
def get_app() -> NotebookApp:
"""Get the current application."""
return cast("NotebookApp", ptk_get_app())
The provided code snippet includes necessary dependencies for implementing the `has_menus` function. Write a Python function `def has_menus() -> bool` to solve the following problem:
Determine if a menu is being displayed.
Here is the function:
def has_menus() -> bool:
"""Determine if a menu is being displayed."""
from prompt_toolkit.layout.containers import ConditionalContainer
from euporie.notebook.current import get_app
app = get_app()
for menu in app.menus.values():
if isinstance(menu.content, ConditionalContainer) and menu.content.filter():
return True
return False | Determine if a menu is being displayed. |
6,862 | from __future__ import annotations
import os
from functools import lru_cache, partial, reduce
from importlib import import_module
from shutil import which
from typing import TYPE_CHECKING
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.filters import (
Condition,
emacs_insert_mode,
emacs_mode,
to_filter,
vi_insert_mode,
vi_mode,
vi_replace_mode,
)
from euporie.core.key_binding.micro_state import MicroInputMode
def get_app() -> BaseApp:
"""Get the current active (running) Application."""
from euporie.core.app import BaseApp
session = _current_app_session.get()
if isinstance(session.app, BaseApp):
return session.app
# Use a baseapp as our "DummyApplication"
return BaseApp()
def get_app() -> NotebookApp:
"""Get the current application."""
return cast("NotebookApp", ptk_get_app())
The provided code snippet includes necessary dependencies for implementing the `tab_has_focus` function. Write a Python function `def tab_has_focus() -> bool` to solve the following problem:
Determine if there is a currently focused tab.
Here is the function:
def tab_has_focus() -> bool:
"""Determine if there is a currently focused tab."""
from euporie.core.current import get_app
return get_app().tab is not None | Determine if there is a currently focused tab. |
6,863 | from __future__ import annotations
import os
from functools import lru_cache, partial, reduce
from importlib import import_module
from shutil import which
from typing import TYPE_CHECKING
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.filters import (
Condition,
emacs_insert_mode,
emacs_mode,
to_filter,
vi_insert_mode,
vi_mode,
vi_replace_mode,
)
from euporie.core.key_binding.micro_state import MicroInputMode
def get_app() -> BaseApp:
"""Get the current active (running) Application."""
from euporie.core.app import BaseApp
session = _current_app_session.get()
if isinstance(session.app, BaseApp):
return session.app
# Use a baseapp as our "DummyApplication"
return BaseApp()
def get_app() -> NotebookApp:
"""Get the current application."""
return cast("NotebookApp", ptk_get_app())
The provided code snippet includes necessary dependencies for implementing the `pager_has_focus` function. Write a Python function `def pager_has_focus() -> bool` to solve the following problem:
Determine if there is a currently focused notebook.
Here is the function:
def pager_has_focus() -> bool:
"""Determine if there is a currently focused notebook."""
from euporie.core.current import get_app
app = get_app()
pager = app.pager
if pager is not None:
return app.layout.has_focus(pager)
return False | Determine if there is a currently focused notebook. |
6,864 | from __future__ import annotations
import os
from functools import lru_cache, partial, reduce
from importlib import import_module
from shutil import which
from typing import TYPE_CHECKING
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.filters import (
Condition,
emacs_insert_mode,
emacs_mode,
to_filter,
vi_insert_mode,
vi_mode,
vi_replace_mode,
)
from euporie.core.key_binding.micro_state import MicroInputMode
def get_app() -> BaseApp:
"""Get the current active (running) Application."""
from euporie.core.app import BaseApp
session = _current_app_session.get()
if isinstance(session.app, BaseApp):
return session.app
# Use a baseapp as our "DummyApplication"
return BaseApp()
def get_app() -> NotebookApp:
"""Get the current application."""
return cast("NotebookApp", ptk_get_app())
class DisplayControl(UIControl):
"""Web view displays.
A control which displays rendered HTML content.
"""
_window: Window
def __init__(
self,
datum: Datum,
focusable: FilterOrBool = False,
focus_on_click: FilterOrBool = False,
wrap_lines: FilterOrBool = False,
dont_extend_width: FilterOrBool = False,
threaded: bool = False,
) -> None:
"""Create a new web-view control instance."""
self._datum = datum
self.focusable = to_filter(focusable)
self.focus_on_click = to_filter(focus_on_click)
self.wrap_lines = to_filter(wrap_lines)
self.dont_extend_width = to_filter(dont_extend_width)
self.threaded = threaded
self._cursor_position = Point(0, 0)
self.loading = False
self.resizing = False
self.rendering = False
self.color_palette = get_app().color_palette
self.lines: list[StyleAndTextTuples] = []
self.graphic_processor = GraphicProcessor(control=self)
self.width = 0
self.height = 0
self.key_bindings = load_registered_bindings(
"euporie.core.widgets.display.DisplayControl"
)
self.rendered = Event(self)
self.on_cursor_position_changed = Event(self)
self.invalidate_events: list[Event[object]] = [
self.rendered,
self.on_cursor_position_changed,
]
# Caches
self._content_cache: FastDictCache = FastDictCache(self.get_content, size=1000)
self._line_cache: FastDictCache[
tuple[Datum, int | None, int | None, str, str, bool],
list[StyleAndTextTuples],
] = FastDictCache(get_value=self.get_lines, size=1000)
self._line_width_cache: SimpleCache[
tuple[Datum, int | None, int | None, bool, int], int
] = SimpleCache(maxsize=10_000)
self._max_line_width_cache: FastDictCache[
tuple[Datum, int | None, int | None, bool], int
] = FastDictCache(get_value=self.get_max_line_width, size=1000)
def datum(self) -> Any:
"""Return the control's display data."""
return self._datum
def datum(self, value: Any) -> None:
"""Set the control's data."""
self._datum = value
# Trigger "loading" view
self.loading = True
# Signal that the control has updated
self.rendered.fire()
self.reset()
def cursor_position(self) -> Point:
"""Get the cursor position."""
return self._cursor_position
def cursor_position(self, value: Point) -> None:
"""Set the cursor position."""
changed = self._cursor_position != value
self._cursor_position = value
if changed:
self.on_cursor_position_changed.fire()
def get_lines(
self,
datum: Datum,
width: int | None,
height: int | None,
fg: str,
bg: str,
wrap_lines: bool = False,
) -> list[StyleAndTextTuples]:
"""Render the lines to display in the control."""
ft = datum.convert(
to="ft",
cols=width,
rows=height,
fg=fg,
bg=bg,
extend=not self.dont_extend_width(),
)
if width and height:
key = Datum.add_size(datum, Size(height, self.width))
ft = [(f"[Graphic_{key}]", ""), *ft]
lines = list(split_lines(ft))
if wrap_lines and width:
lines = [
wrapped_line
for line in lines
for wrapped_line in split_lines(
wrap(line, width, truncate_long_words=False)
)
]
# Ensure we have enough lines to fill the requested height
if height is not None:
lines.extend([[]] * max(0, height - len(lines)))
return lines
def get_max_line_width(
self,
datum: Datum,
width: int | None,
height: int | None,
wrap_lines: bool = False,
) -> int:
"""Get the maximum lines width for a given rendering."""
cp = self.color_palette
lines = self._line_cache[
datum, width, height, cp.fg.base_hex, cp.bg.base_hex, wrap_lines
]
return max(
self._line_width_cache.get(
(datum, width, height, wrap_lines, i),
partial(fragment_list_width, line),
)
for i, line in enumerate(lines)
)
def render(self) -> None:
"""Render the HTML DOM in a thread."""
datum = self.datum
wrap_lines = self.wrap_lines()
max_cols, aspect = self.datum.cell_size()
cols = min(max_cols, self.width) if max_cols else self.width
rows = ceil(cols * aspect) if aspect else self.height
def _render() -> None:
cp = self.color_palette
self.lines = self._line_cache[
datum, cols, rows, cp.fg.base_hex, cp.bg.base_hex, wrap_lines
]
self.loading = False
self.resizing = False
self.rendering = False
self.rendered.fire()
if not self.rendering:
self.rendering = True
if self.threaded:
run_in_thread_with_context(_render)
else:
_render()
def reset(self) -> None:
"""Reset the state of the control."""
def preferred_width(self, max_available_width: int) -> int | None:
"""Calculate and return the preferred width of the control."""
max_cols, aspect = self.datum.cell_size()
if max_cols:
return min(max_cols, max_available_width)
return self._max_line_width_cache[
self.datum, max_available_width, None, self.wrap_lines()
]
def preferred_height(
self,
width: int,
max_available_height: int,
wrap_lines: bool,
get_line_prefix: GetLinePrefixCallable | None,
) -> int | None:
"""Calculate and return the preferred height of the control."""
max_cols, aspect = self.datum.cell_size()
if aspect:
return ceil(min(width, max_cols) * aspect)
cp = self.color_palette
self.lines = self._line_cache[
self.datum, width, None, cp.fg.base_hex, cp.bg.base_hex, self.wrap_lines()
]
return len(self.lines)
def is_focusable(self) -> bool:
"""Tell whether this user control is focusable."""
return self.focusable()
def get_content(
self,
datum: Datum,
width: int,
height: int,
loading: bool,
cursor_position: Point,
color_palette: ColorPalette,
) -> UIContent:
"""Create a cacheable UIContent."""
if self.loading:
lines = [
cast("StyleAndTextTuples", []),
cast(
"StyleAndTextTuples",
[
("", " " * ((self.width - 8) // 2)),
("class:loading", "Loading…"),
],
),
]
else:
lines = self.lines
def get_line(i: int) -> StyleAndTextTuples:
try:
line = lines[i]
except IndexError:
return []
return line
return UIContent(
get_line=get_line,
line_count=len(lines),
cursor_position=self.cursor_position,
show_cursor=False,
)
def create_content(self, width: int, height: int) -> UIContent:
"""Generate the content for this user control.
Returns:
A :py:class:`UIContent` instance.
"""
# Trigger a re-render in the future if things have changed
if self.loading:
self.render()
if width != self.width:
self.resizing = True
self.width = width
self.height = height
self.render()
if (cp := get_app().color_palette) != self.color_palette:
self.color_palette = cp
self.render()
content = self._content_cache[
self.datum, width, height, self.loading, self.cursor_position, cp
]
# Check for graphics in content
self.graphic_processor.load(content)
return content
def mouse_handler(self, mouse_event: MouseEvent) -> NotImplementedOrNone:
"""Mouse handler for this control."""
if self.focus_on_click() and mouse_event.event_type == MouseEventType.MOUSE_UP:
get_app().layout.current_control = self
return None
return NotImplemented
def content_width(self) -> int:
"""Return the width of the content."""
return max(fragment_list_width(line) for line in self.lines)
def move_cursor_down(self) -> None:
"""Move the cursor down one line."""
x, y = self.cursor_position
self.cursor_position = Point(x=x, y=y + 1)
def move_cursor_up(self) -> None:
"""Move the cursor up one line."""
x, y = self.cursor_position
self.cursor_position = Point(x=x, y=max(0, y - 1))
def move_cursor_left(self) -> None:
"""Move the cursor down one line."""
x, y = self.cursor_position
self.cursor_position = Point(x=max(0, x - 1), y=y)
def move_cursor_right(self) -> None:
"""Move the cursor up one line."""
x, y = self.cursor_position
self.cursor_position = Point(x=x + 1, y=y)
def get_key_bindings(self) -> KeyBindingsBase | None:
"""Return key bindings that are specific for this user control.
Returns:
A :class:`.KeyBindings` object if some key bindings are specified, or
`None` otherwise.
"""
return self.key_bindings
def get_invalidate_events(self) -> Iterable[Event[object]]:
"""Return the Window invalidate events."""
yield from self.invalidate_events
The provided code snippet includes necessary dependencies for implementing the `display_has_focus` function. Write a Python function `def display_has_focus() -> bool` to solve the following problem:
Determine if there is a currently focused cell.
Here is the function:
def display_has_focus() -> bool:
"""Determine if there is a currently focused cell."""
from euporie.core.current import get_app
from euporie.core.widgets.display import DisplayControl
return isinstance(get_app().layout.current_control, DisplayControl) | Determine if there is a currently focused cell. |
6,865 | from __future__ import annotations
import os
from functools import lru_cache, partial, reduce
from importlib import import_module
from shutil import which
from typing import TYPE_CHECKING
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.filters import (
Condition,
emacs_insert_mode,
emacs_mode,
to_filter,
vi_insert_mode,
vi_mode,
vi_replace_mode,
)
from euporie.core.key_binding.micro_state import MicroInputMode
def get_app() -> BaseApp:
"""Get the current active (running) Application."""
from euporie.core.app import BaseApp
session = _current_app_session.get()
if isinstance(session.app, BaseApp):
return session.app
# Use a baseapp as our "DummyApplication"
return BaseApp()
def get_app() -> NotebookApp:
"""Get the current application."""
return cast("NotebookApp", ptk_get_app())
The provided code snippet includes necessary dependencies for implementing the `buffer_is_empty` function. Write a Python function `def buffer_is_empty() -> bool` to solve the following problem:
Determine if the current buffer contains nothing.
Here is the function:
def buffer_is_empty() -> bool:
"""Determine if the current buffer contains nothing."""
from euporie.core.current import get_app
return not get_app().current_buffer.text | Determine if the current buffer contains nothing. |
6,866 | from __future__ import annotations
import os
from functools import lru_cache, partial, reduce
from importlib import import_module
from shutil import which
from typing import TYPE_CHECKING
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.filters import (
Condition,
emacs_insert_mode,
emacs_mode,
to_filter,
vi_insert_mode,
vi_mode,
vi_replace_mode,
)
from euporie.core.key_binding.micro_state import MicroInputMode
def get_app() -> BaseApp:
"""Get the current active (running) Application."""
from euporie.core.app import BaseApp
session = _current_app_session.get()
if isinstance(session.app, BaseApp):
return session.app
# Use a baseapp as our "DummyApplication"
return BaseApp()
def get_app() -> NotebookApp:
"""Get the current application."""
return cast("NotebookApp", ptk_get_app())
The provided code snippet includes necessary dependencies for implementing the `buffer_is_markdown` function. Write a Python function `def buffer_is_markdown() -> bool` to solve the following problem:
Determine if the current buffer contains markdown.
Here is the function:
def buffer_is_markdown() -> bool:
"""Determine if the current buffer contains markdown."""
from euporie.core.current import get_app
return get_app().current_buffer.name == "markdown" | Determine if the current buffer contains markdown. |
6,867 | from __future__ import annotations
import os
from functools import lru_cache, partial, reduce
from importlib import import_module
from shutil import which
from typing import TYPE_CHECKING
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.filters import (
Condition,
emacs_insert_mode,
emacs_mode,
to_filter,
vi_insert_mode,
vi_mode,
vi_replace_mode,
)
from euporie.core.key_binding.micro_state import MicroInputMode
def get_app() -> BaseApp:
"""Get the current active (running) Application."""
from euporie.core.app import BaseApp
session = _current_app_session.get()
if isinstance(session.app, BaseApp):
return session.app
# Use a baseapp as our "DummyApplication"
return BaseApp()
def get_app() -> NotebookApp:
"""Get the current application."""
return cast("NotebookApp", ptk_get_app())
The provided code snippet includes necessary dependencies for implementing the `micro_recording_macro` function. Write a Python function `def micro_recording_macro() -> bool` to solve the following problem:
Determine if a micro macro is being recorded.
Here is the function:
def micro_recording_macro() -> bool:
"""Determine if a micro macro is being recorded."""
from euporie.core.current import get_app
return get_app().micro_state.current_recording is not None | Determine if a micro macro is being recorded. |
6,868 | from __future__ import annotations
import os
from functools import lru_cache, partial, reduce
from importlib import import_module
from shutil import which
from typing import TYPE_CHECKING
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.filters import (
Condition,
emacs_insert_mode,
emacs_mode,
to_filter,
vi_insert_mode,
vi_mode,
vi_replace_mode,
)
from euporie.core.key_binding.micro_state import MicroInputMode
def get_app() -> BaseApp:
"""Get the current active (running) Application."""
from euporie.core.app import BaseApp
session = _current_app_session.get()
if isinstance(session.app, BaseApp):
return session.app
# Use a baseapp as our "DummyApplication"
return BaseApp()
def get_app() -> NotebookApp:
"""Get the current application."""
return cast("NotebookApp", ptk_get_app())
The provided code snippet includes necessary dependencies for implementing the `is_returnable` function. Write a Python function `def is_returnable() -> bool` to solve the following problem:
Determine if the current buffer has an accept handler.
Here is the function:
def is_returnable() -> bool:
"""Determine if the current buffer has an accept handler."""
from euporie.core.current import get_app
return get_app().current_buffer.is_returnable | Determine if the current buffer has an accept handler. |
6,869 | from __future__ import annotations
import os
from functools import lru_cache, partial, reduce
from importlib import import_module
from shutil import which
from typing import TYPE_CHECKING
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.filters import (
Condition,
emacs_insert_mode,
emacs_mode,
to_filter,
vi_insert_mode,
vi_mode,
vi_replace_mode,
)
from euporie.core.key_binding.micro_state import MicroInputMode
def get_app() -> BaseApp:
"""Get the current active (running) Application."""
from euporie.core.app import BaseApp
session = _current_app_session.get()
if isinstance(session.app, BaseApp):
return session.app
# Use a baseapp as our "DummyApplication"
return BaseApp()
def get_app() -> NotebookApp:
"""Get the current application."""
return cast("NotebookApp", ptk_get_app())
The provided code snippet includes necessary dependencies for implementing the `cursor_at_start_of_line` function. Write a Python function `def cursor_at_start_of_line() -> bool` to solve the following problem:
Determine if the cursor is at the start of a line.
Here is the function:
def cursor_at_start_of_line() -> bool:
"""Determine if the cursor is at the start of a line."""
from euporie.core.current import get_app
return get_app().current_buffer.document.cursor_position_col == 0 | Determine if the cursor is at the start of a line. |
6,870 | from __future__ import annotations
import os
from functools import lru_cache, partial, reduce
from importlib import import_module
from shutil import which
from typing import TYPE_CHECKING
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.filters import (
Condition,
emacs_insert_mode,
emacs_mode,
to_filter,
vi_insert_mode,
vi_mode,
vi_replace_mode,
)
from euporie.core.key_binding.micro_state import MicroInputMode
def get_app() -> BaseApp:
"""Get the current active (running) Application."""
from euporie.core.app import BaseApp
session = _current_app_session.get()
if isinstance(session.app, BaseApp):
return session.app
# Use a baseapp as our "DummyApplication"
return BaseApp()
def get_app() -> NotebookApp:
"""Get the current application."""
return cast("NotebookApp", ptk_get_app())
The provided code snippet includes necessary dependencies for implementing the `cursor_on_first_line` function. Write a Python function `def cursor_on_first_line() -> bool` to solve the following problem:
Determine if the cursor is on the first line of a buffer.
Here is the function:
def cursor_on_first_line() -> bool:
"""Determine if the cursor is on the first line of a buffer."""
from euporie.core.current import get_app
return get_app().current_buffer.document.on_first_line | Determine if the cursor is on the first line of a buffer. |
6,871 | from __future__ import annotations
import os
from functools import lru_cache, partial, reduce
from importlib import import_module
from shutil import which
from typing import TYPE_CHECKING
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.filters import (
Condition,
emacs_insert_mode,
emacs_mode,
to_filter,
vi_insert_mode,
vi_mode,
vi_replace_mode,
)
from euporie.core.key_binding.micro_state import MicroInputMode
def get_app() -> BaseApp:
"""Get the current active (running) Application."""
from euporie.core.app import BaseApp
session = _current_app_session.get()
if isinstance(session.app, BaseApp):
return session.app
# Use a baseapp as our "DummyApplication"
return BaseApp()
def get_app() -> NotebookApp:
"""Get the current application."""
return cast("NotebookApp", ptk_get_app())
The provided code snippet includes necessary dependencies for implementing the `cursor_on_last_line` function. Write a Python function `def cursor_on_last_line() -> bool` to solve the following problem:
Determine if the cursor is on the last line of a buffer.
Here is the function:
def cursor_on_last_line() -> bool:
"""Determine if the cursor is on the last line of a buffer."""
from euporie.core.current import get_app
return get_app().current_buffer.document.on_last_line | Determine if the cursor is on the last line of a buffer. |
6,872 | from __future__ import annotations
import os
from functools import lru_cache, partial, reduce
from importlib import import_module
from shutil import which
from typing import TYPE_CHECKING
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.filters import (
Condition,
emacs_insert_mode,
emacs_mode,
to_filter,
vi_insert_mode,
vi_mode,
vi_replace_mode,
)
from euporie.core.key_binding.micro_state import MicroInputMode
def get_app() -> BaseApp:
"""Get the current active (running) Application."""
from euporie.core.app import BaseApp
session = _current_app_session.get()
if isinstance(session.app, BaseApp):
return session.app
# Use a baseapp as our "DummyApplication"
return BaseApp()
def get_app() -> NotebookApp:
"""Get the current application."""
return cast("NotebookApp", ptk_get_app())
The provided code snippet includes necessary dependencies for implementing the `is_searching` function. Write a Python function `def is_searching() -> bool` to solve the following problem:
Determine if the app is in search mode.
Here is the function:
def is_searching() -> bool:
"""Determine if the app is in search mode."""
from euporie.core.current import get_app
app = get_app()
return (
app.search_bar is not None and app.search_bar.control in app.layout.search_links
) | Determine if the app is in search mode. |
6,873 | from __future__ import annotations
import os
from functools import lru_cache, partial, reduce
from importlib import import_module
from shutil import which
from typing import TYPE_CHECKING
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.filters import (
Condition,
emacs_insert_mode,
emacs_mode,
to_filter,
vi_insert_mode,
vi_mode,
vi_replace_mode,
)
from euporie.core.key_binding.micro_state import MicroInputMode
def get_app() -> BaseApp:
"""Get the current active (running) Application."""
from euporie.core.app import BaseApp
session = _current_app_session.get()
if isinstance(session.app, BaseApp):
return session.app
# Use a baseapp as our "DummyApplication"
return BaseApp()
def get_app() -> NotebookApp:
"""Get the current application."""
return cast("NotebookApp", ptk_get_app())
The provided code snippet includes necessary dependencies for implementing the `at_end_of_buffer` function. Write a Python function `def at_end_of_buffer() -> bool` to solve the following problem:
Determine if the cursor is at the end of the current buffer.
Here is the function:
def at_end_of_buffer() -> bool:
"""Determine if the cursor is at the end of the current buffer."""
from prompt_toolkit.application.current import get_app
buffer = get_app().current_buffer
return buffer.cursor_position == len(buffer.text) | Determine if the cursor is at the end of the current buffer. |
6,874 | from __future__ import annotations
import os
from functools import lru_cache, partial, reduce
from importlib import import_module
from shutil import which
from typing import TYPE_CHECKING
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.filters import (
Condition,
emacs_insert_mode,
emacs_mode,
to_filter,
vi_insert_mode,
vi_mode,
vi_replace_mode,
)
from euporie.core.key_binding.micro_state import MicroInputMode
def get_app() -> BaseApp:
"""Get the current active (running) Application."""
from euporie.core.app import BaseApp
session = _current_app_session.get()
if isinstance(session.app, BaseApp):
return session.app
# Use a baseapp as our "DummyApplication"
return BaseApp()
def get_app() -> NotebookApp:
"""Get the current application."""
return cast("NotebookApp", ptk_get_app())
class KernelTab(Tab, metaclass=ABCMeta):
"""A Tab which connects to a kernel."""
kernel: Kernel
kernel_language: str
_metadata: dict[str, Any]
bg_init = True
default_callbacks: MsgCallbacks
allow_stdin: bool
def __init__(
self,
app: BaseApp,
path: Path | None = None,
kernel: Kernel | None = None,
comms: dict[str, Comm] | None = None,
use_kernel_history: bool = False,
connection_file: Path | None = None,
) -> None:
"""Create a new instance of a tab with a kernel."""
# Init tab
super().__init__(app, path)
self.lsps: list[LspClient] = []
self.history: History = DummyHistory()
self.inspectors: list[Inspector] = []
self.inspector = FirstInspector(lambda: self.inspectors)
self.suggester: AutoSuggest = DummyAutoSuggest()
self.completers: list[Completer] = []
self.completer = DeduplicateCompleter(
DynamicCompleter(lambda: _MergedCompleter(self.completers))
)
self.formatters: list[Formatter] = self.app.formatters
self.reports: WeakKeyDictionary[LspClient, Report] = WeakKeyDictionary()
# The client-side comm states
self.comms: dict[str, Comm] = {}
# The current kernel input
self._current_input: KernelInput | None = None
if self.bg_init:
# Load kernel in a background thread
run_in_thread_with_context(
partial(
self.init_kernel, kernel, comms, use_kernel_history, connection_file
)
)
else:
self.init_kernel(kernel, comms, use_kernel_history, connection_file)
async def load_lsps(self) -> None:
"""Load the LSP clients."""
path = self.path
# Load list of LSP clients for the tab's language
self.lsps.extend(self.app.get_language_lsps(self.language))
# Wait for all lsps to be initialized, and setup hooks as they become ready
async def _await_load(lsp: LspClient) -> LspClient:
await lsp.initialized.wait()
return lsp
for ready in asyncio.as_completed([_await_load(lsp) for lsp in self.lsps]):
lsp = await ready
# Apply open, save, and close hooks to the tab
change_handler = partial(lambda lsp, tab: self.lsp_change_handler(lsp), lsp)
close_handler = partial(lambda lsp, tab: self.lsp_close_handler(lsp), lsp)
before_save_handler = partial(
lambda lsp, tab: self.lsp_before_save_handler(lsp), lsp
)
after_save_handler = partial(
lambda lsp, tab: self.lsp_after_save_handler(lsp), lsp
)
self.on_close += close_handler
self.on_change += change_handler
self.before_save += before_save_handler
self.after_save += after_save_handler
# Listen for LSP diagnostics
lsp.on_diagnostics += self.lsp_update_diagnostics
# Add completer
completer = LspCompleter(lsp=lsp, path=path)
self.completers.append(completer)
# Add inspector
inspector = LspInspector(lsp, path)
self.inspectors.append(inspector)
# Add formatter
formatter = LspFormatter(lsp, path)
self.formatters.append(formatter)
# Remove hooks if the LSP exits
def lsp_unload(lsp: LspClient) -> None:
self.on_change -= change_handler # noqa: B023
self.before_save -= before_save_handler # noqa: B023
self.after_save -= after_save_handler # noqa: B023
self.on_close -= close_handler # noqa: B023
if completer in self.completers: # noqa: B023
self.completers.remove(completer) # noqa: B023
if inspector in self.completers: # noqa: B023
self.inspectors.remove(inspector) # noqa: B023
if formatter in self.completers: # noqa: B023
self.formatters.remove(formatter) # noqa: B023
if completer in self.completers: # noqa: B023
self.completers.remove(completer) # noqa: B023
if inspector in self.inspectors: # noqa: B023
self.inspectors.remove(inspector) # noqa: B023
if formatter in self.formatters: # noqa: B023
self.formatters.remove(formatter) # noqa: B023
lsp.on_exit += lsp_unload
# Remove the lsp exit handler if this tab closes
self.on_close += lambda tab: (
(lsp.on_exit.__isub__(lsp_unload) and None) or None # noqa: B023
) # Magical typing
# Tell the LSP we have an open file
self.lsp_open_handler(lsp)
def pre_init_kernel(self) -> None:
"""Run stuff before the kernel is loaded."""
def post_init_kernel(self) -> None:
"""Run stuff after the kernel is loaded."""
def init_kernel(
self,
kernel: Kernel | None = None,
comms: dict[str, Comm] | None = None,
use_kernel_history: bool = False,
connection_file: Path | None = None,
) -> None:
"""Set up the tab's kernel and related components."""
self.pre_init_kernel()
self.kernel_queue: deque[Callable] = deque()
if kernel:
self.kernel = kernel
self.kernel.default_callbacks = self.default_callbacks
else:
self.kernel = Kernel(
kernel_tab=self,
allow_stdin=self.allow_stdin,
default_callbacks=self.default_callbacks,
connection_file=connection_file,
)
self.comms = comms or {} # The client-side comm states
self.completers.append(KernelCompleter(self.kernel))
self.inspectors.append(KernelInspector(self.kernel))
self.use_kernel_history = use_kernel_history
self.history = (
KernelHistory(self.kernel) if use_kernel_history else InMemoryHistory()
)
self.suggester = HistoryAutoSuggest(self.history)
self.app.create_background_task(self.load_lsps())
self.post_init_kernel()
def close(self, cb: Callable | None = None) -> None:
"""Shut down kernel when tab is closed."""
if hasattr(self, "kernel"):
self.kernel.shutdown()
super().close(cb)
def interrupt_kernel(self) -> None:
"""Interrupt the current `Notebook`'s kernel."""
self.kernel.interrupt()
def restart_kernel(self, cb: Callable | None = None) -> None:
"""Restart the current `Notebook`'s kernel."""
def _cb(result: dict[str, Any]) -> None:
if callable(cb):
cb()
if confirm := self.app.dialogs.get("confirm"):
confirm.show(
message="Are you sure you want to restart the kernel?",
cb=partial(self.kernel.restart, cb=_cb),
)
else:
self.kernel.restart(cb=_cb)
def kernel_started(self, result: dict[str, Any] | None = None) -> None:
"""Task to run when the kernel has started."""
# Check kernel has not failed
if not self.kernel_name or self.kernel.missing:
if not self.kernel_name:
msg = "No kernel selected"
else:
msg = f"Kernel '{self.kernel_display_name}' not installed"
self.change_kernel(
msg=msg,
startup=True,
)
elif self.kernel.status == "error":
self.report_kernel_error(self.kernel.error)
else:
# Wait for an idle kernel
if self.kernel.status != "idle":
self.kernel.wait_for_status("idle")
# Load widget comm info
# self.kernel.comm_info(target_name="jupyter.widget")
# Load kernel info
self.kernel.info(set_kernel_info=self.set_kernel_info)
# Load kernel history
if self.use_kernel_history:
self.app.create_background_task(self.load_history())
# Run queued kernel tasks when the kernel is idle
log.debug("Running %d kernel tasks", len(self.kernel_queue))
while self.kernel_queue:
self.kernel_queue.popleft()()
self.app.invalidate()
def report_kernel_error(self, error: Exception | None) -> None:
"""Report a kernel error to the user."""
log.debug("Kernel error", exc_info=error)
async def load_history(self) -> None:
"""Load kernel history."""
try:
await self.history.load().__anext__()
except StopAsyncIteration:
pass
def metadata(self) -> dict[str, Any]:
"""Return a dictionary to hold notebook / kernel metadata."""
return self._metadata
def kernel_name(self) -> str:
"""Return the name of the kernel defined in the notebook JSON."""
return self.metadata.get("kernelspec", {}).get(
"name", self.app.config.kernel_name
)
def kernel_name(self, value: str) -> None:
"""Return the name of the kernel defined in the notebook JSON."""
self.metadata.setdefault("kernelspec", {})["name"] = value
def language(self) -> str:
"""Return the name of the kernel defined in the notebook JSON."""
return self.metadata.get("kernelspec", {}).get("language")
def kernel_display_name(self) -> str:
"""Return the display name of the kernel defined in the notebook JSON."""
return self.metadata.get("kernelspec", {}).get("display_name", self.kernel_name)
def kernel_lang_file_ext(self) -> str:
"""Return the display name of the kernel defined in the notebook JSON."""
return self.metadata.get("language_info", {}).get("file_extension", ".py")
def current_input(self) -> KernelInput:
"""Return the currently active kernel input, if any."""
return self._current_input or KernelInput(self)
def set_kernel_info(self, info: dict) -> None:
"""Handle kernel info requests."""
self.metadata["language_info"] = info.get("language_info", {})
def change_kernel(self, msg: str | None = None, startup: bool = False) -> None:
"""Prompt the user to select a new kernel."""
kernel_specs = self.kernel.specs
# Warn the user if no kernels are installed
if not kernel_specs:
if startup and "no-kernels" in self.app.dialogs:
self.app.dialogs["no-kernels"].show()
return
# Automatically select the only kernel if there is only one
if startup and len(kernel_specs) == 1:
self.kernel.change(next(iter(kernel_specs)))
return
self.app.dialogs["change-kernel"].show(
tab=self, message=msg, kernel_specs=kernel_specs
)
def comm_open(self, content: dict, buffers: Sequence[bytes]) -> None:
"""Register a new kernel Comm object in the notebook."""
comm_id = str(content.get("comm_id"))
self.comms[comm_id] = open_comm(
comm_container=self, content=content, buffers=buffers
)
def comm_msg(self, content: dict, buffers: Sequence[bytes]) -> None:
"""Respond to a Comm message from the kernel."""
comm_id = str(content.get("comm_id"))
if comm := self.comms.get(comm_id):
comm.process_data(content.get("data", {}), buffers)
def comm_close(self, content: dict, buffers: Sequence[bytes]) -> None:
"""Close a notebook Comm."""
comm_id = content.get("comm_id")
if comm_id in self.comms:
del self.comms[comm_id]
def lsp_open_handler(self, lsp: LspClient) -> None:
"""Tell the LSP we opened a file."""
lsp.open_doc(
path=self.path, language=self.language, text=self.current_input.buffer.text
)
def lsp_change_handler(self, lsp: LspClient) -> None:
"""Tell the LSP server a file has changed."""
lsp.change_doc(
path=self.path,
language=self.language,
text=self.current_input.buffer.text,
)
def lsp_before_save_handler(self, lsp: LspClient) -> None:
"""Tell the the LSP we are about to save a document."""
lsp.will_save_doc(self.path)
def lsp_after_save_handler(self, lsp: LspClient) -> None:
"""Tell the the LSP we saved a document."""
lsp.save_doc(self.path, text=self.current_input.buffer.text)
def lsp_close_handler(self, lsp: LspClient) -> None:
"""Tell the LSP we opened a file."""
lsp.close_doc(path=self.path)
def lsp_update_diagnostics(self, lsp: LspClient) -> None:
"""Process a new diagnostic report from the LSP."""
if (diagnostics := lsp.reports.pop(self.path.as_uri(), None)) is not None:
self.reports[lsp] = Report.from_lsp(self.current_input.text, diagnostics)
self.app.invalidate()
def report(self) -> Report:
"""Return the current diagnostic reports."""
return Report.from_reports(*self.reports.values())
# ################################### Commands ####################################
def _change_kernel() -> None:
"""Change the notebook's kernel."""
if isinstance(kt := get_app().tab, KernelTab):
kt.change_kernel()
# ################################### Settings ####################################
add_setting(
name="kernel_name",
flags=["--kernel-name", "--kernel"],
type_=str,
help_="The name of the kernel to start by default",
default="python3",
description="""
The name of the kernel selected automatically by the console app or in new
notebooks. If set to an empty string, the user will be asked which kernel
to launch.
""",
)
add_setting(
name="record_cell_timing",
title="cell timing recording",
flags=["--record-cell-timing"],
type_=bool,
help_="Should timing data be recorded in cell metadata.",
default=False,
schema={
"type": "boolean",
},
description="""
When set, execution timing data will be recorded in cell metadata.
""",
)
The provided code snippet includes necessary dependencies for implementing the `kernel_is_python` function. Write a Python function `def kernel_is_python() -> bool` to solve the following problem:
Determine if the current notebook has a python kernel.
Here is the function:
def kernel_is_python() -> bool:
"""Determine if the current notebook has a python kernel."""
from euporie.core.current import get_app
from euporie.core.tabs.base import KernelTab
kernel_tab = get_app().tab
if isinstance(kernel_tab, KernelTab):
return kernel_tab.language == "python"
return False | Determine if the current notebook has a python kernel. |
6,875 | from __future__ import annotations
import os
from functools import lru_cache, partial, reduce
from importlib import import_module
from shutil import which
from typing import TYPE_CHECKING
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.filters import (
Condition,
emacs_insert_mode,
emacs_mode,
to_filter,
vi_insert_mode,
vi_mode,
vi_replace_mode,
)
from euporie.core.key_binding.micro_state import MicroInputMode
def get_app() -> BaseApp:
"""Get the current active (running) Application."""
from euporie.core.app import BaseApp
session = _current_app_session.get()
if isinstance(session.app, BaseApp):
return session.app
# Use a baseapp as our "DummyApplication"
return BaseApp()
def get_app() -> NotebookApp:
"""Get the current application."""
return cast("NotebookApp", ptk_get_app())
class BaseNotebook(KernelTab, metaclass=ABCMeta):
"""The main notebook container class."""
allow_stdin = False
edit_mode = False
def __init__(
self,
app: BaseApp,
path: Path | None = None,
kernel: Kernel | None = None,
comms: dict[str, Comm] | None = None,
use_kernel_history: bool = False,
json: dict[str, Any] | None = None,
) -> None:
"""Instantiate a Notebook container, using a notebook at a given path.
Args:
path: The file path of the notebook
app: The euporie application the notebook tab belongs to
kernel: An existing kernel instance to use
comms: Existing kernel comm object to use
use_kernel_history: If True, load history from the kernel
json: JSON contents of notebook, used if path not given
"""
self.default_callbacks = MsgCallbacks(
{
"get_input": lambda prompt, password: self.cell.get_input(
prompt, password
),
"set_execution_count": lambda n: self.cell.set_execution_count(n),
"add_output": lambda output_json: self.cell.add_output(output_json),
"clear_output": lambda wait: self.cell.clear_output(wait),
"set_metadata": lambda path, data: self.cell.set_metadata(path, data),
"set_status": self.set_status,
"set_kernel_info": self.set_kernel_info,
"dead": self.kernel_died,
"edit_magic": edit_in_editor,
}
)
self.json = json or {}
self._rendered_cells: dict[str, Cell] = {}
self.multiple_cells_selected: Filter = Never()
self.loaded = False
super().__init__(
app, path, kernel=kernel, comms=comms, use_kernel_history=use_kernel_history
)
# Tab stuff
def reset(self) -> None:
"""Reload the notebook file from the disk and re-render."""
# Restore selection after reset
if self.path is not None:
self._rendered_cells = {}
self.load()
self.refresh()
# KernelTab stuff
def pre_init_kernel(self) -> None:
"""Run stuff before the kernel is loaded."""
# Load notebook file
self.load()
def post_init_kernel(self) -> None:
"""Load the notebook container after the kernel has been loaded."""
# Replace the tab's container
prev = self.container
self.container = self.load_container()
self.loaded = True
# Update the focus if the old container had focus
if self.app.layout.has_focus(prev):
self.focus()
self.app.invalidate()
# Load widgets
self.load_widgets_from_metadata()
def metadata(self) -> dict[str, Any]:
"""Return a dictionary to hold notebook / kernel metadata."""
return self.json.setdefault("metadata", {})
async def load_history(self) -> None:
"""Load kernel history."""
await super().load_history()
# Re-run history load for cell input-boxes
for cell in self._rendered_cells.values():
cell.input_box.buffer._load_history_task = None
cell.input_box.buffer.load_history_if_not_yet_loaded()
def kernel_started(self, result: dict[str, Any] | None = None) -> None:
"""Task to run when the kernel has started."""
super().kernel_started(result)
def kernel_died(self) -> None:
"""Call if the kernel dies."""
if confirm := self.app.dialogs.get("confirm"):
confirm.show(
title="Kernel connection lost",
message="The kernel appears to have died\n"
"as it can no longer be reached.\n\n"
"Do you want to restart the kernel?",
cb=self.kernel.restart,
)
# Notebook stuff
def load(self) -> None:
"""Load the notebook file from the file-system."""
# Open json file, or load from passed json object
if self.path is not None and self.path.exists():
with self.path.open() as f:
self.json = read_nb(f, as_version=4)
else:
self.json = self.json or nbformat.v4.new_notebook()
# Ensure there is always at least one cell
if not self.json.setdefault("cells", []):
self.json["cells"] = [nbformat.v4.new_code_cell()]
def set_status(self, status: str) -> None:
"""Call when kernel status changes."""
self.cell.set_status(status)
self.app.invalidate()
def selected_indices(self) -> list[int]:
"""Return a list of the currently selected cell indices."""
return []
def load_container(self) -> AnyContainer:
"""Abcract method for loading the notebook's main container."""
...
def cell(self) -> Cell:
"""Return the current cell."""
...
def current_input(self) -> KernelInput:
"""Return the currently active kernel input, if any."""
return self.cell.input_box
def path_name(self) -> str:
"""Return the path name."""
if self.path is not None:
return self.path.name
else:
return "(New file)"
def title(self) -> str:
"""Return the tab title."""
return ("* " if self.dirty else "") + self.path_name
def lang_file_ext(self) -> str:
"""Return the file extension for scripts in the notebook's language."""
return (
self.json.get("metadata", {})
.get("language_info", {})
.get("file_extension", ".py")
)
def rendered_cells(self) -> list[Cell]:
"""Return a list of rendered notebooks' cells."""
cells = {}
for i, cell_json in enumerate(self.json.get("cells", [])):
cell_id = get_cell_id(cell_json)
if cell_id in self._rendered_cells:
cells[cell_id] = self._rendered_cells[cell_id]
else:
cells[cell_id] = Cell(
i, cell_json, self, is_new=bool(self._rendered_cells)
)
cells[cell_id].index = i
# These cells will be removed
for cell in set(self._rendered_cells.values()) - set(cells.values()):
cell.close()
del cell
self._rendered_cells = cells
return list(self._rendered_cells.values())
def get_cell_by_id(self, cell_id: str) -> Cell | None:
"""Return a reference to the `Cell` container with a given cell id."""
# Re-render the cells as the one we want might be new
for cell in self._rendered_cells.values():
if cell.id == cell_id:
break
else:
return None
return cell
def select(
self,
cell_index: int,
extend: bool = False,
position: int | None = None,
scroll: bool = False,
) -> None:
"""Select a cell."""
def scroll_to(self, index: int) -> None:
"""Scroll to a cell by index."""
def refresh(self, slice_: slice | None = None, scroll: bool = False) -> None:
"""Refresh the notebook."""
def refresh_cell(self, cell: Cell) -> None:
"""Trigger the refresh of a notebook cell."""
def close(self, cb: Callable | None = None) -> None:
"""Check if the user want to save an unsaved notebook, then close the file.
Args:
cb: A callback to run if after closing the notebook.
"""
if self.dirty and (unsaved := self.app.dialogs.get("unsaved")):
unsaved.show(
tab=self,
cb=cb,
)
else:
super().close(cb)
def save(self, path: Path | None = None, cb: Callable | None = None) -> None:
"""Write the notebook's JSON to the current notebook's file.
Additionally save the widget state to the notebook metadata.
Args:
path: An optional new path at which to save the tab
cb: A callback to run if after saving the notebook.
"""
if path is not None:
self.path = path
if self.app.config.save_widget_state:
self.json.setdefault("metadata", {})["widgets"] = {
"application/vnd.jupyter.widget-state+json": {
"version_major": 2,
"version_minor": 0,
"state": {
comm_id: comm._get_embed_state()
for comm_id, comm in self.comms.items()
if comm.data.get("state", {}).get("__unlinked__") is not True
},
}
}
if self.path is None or isinstance(self.path, UntitledPath):
if dialog := self.app.dialogs.get("save-as"):
dialog.show(tab=self, cb=cb)
else:
log.debug("Saving notebook..")
self.saving = True
self.app.invalidate()
# Save to a temp file, then replace the original
temp_path = self.path.parent / f".{self.path.stem}.tmp{self.path.suffix}"
log.debug("Using temporary file %s", temp_path.name)
try:
open_file = temp_path.open("w")
except NotImplementedError:
get_cmd("save-as").run()
else:
try:
try:
write_nb(nb=nbformat.from_dict(self.json), fp=open_file)
except AssertionError:
try:
# Jupytext requires a filename if we don't give it a format
write_nb(nb=nbformat.from_dict(self.json), fp=temp_path)
except Exception:
# Jupytext requires a format if the path has no extension
# We just use ipynb as the default format
write_nb(
nb=nbformat.from_dict(self.json),
fp=open_file,
fmt="ipynb",
)
except Exception:
log.exception("An error occurred while saving the file")
if dialog := self.app.dialogs.get("save-as"):
dialog.show(tab=self, cb=cb)
else:
open_file.close()
try:
temp_path.rename(self.path)
except Exception:
if dialog := self.app.dialogs.get("save-as"):
dialog.show(tab=self, cb=cb)
else:
self.dirty = False
self.saving = False
self.app.invalidate()
log.debug("Notebook saved")
# Run the callback
if callable(cb):
cb()
def run_cell(
self,
cell: Cell,
wait: bool = False,
callback: Callable[..., None] | None = None,
) -> None:
"""Run a cell.
Args:
cell: The rendered cell to run. If ``None``, runs the currently
selected cell.
wait: If :py:const:`True`, blocks until cell execution is finished
callback: Function to run after completion
"""
cell.remove_outputs()
self.dirty = True
# Queue cell if kernel not yet started
if self.kernel.status == "starting":
log.debug("Queuing running of cell %s", cell.index)
self.kernel_queue.append(partial(self.run_cell, cell, wait, callback))
else:
self.kernel.run(
str(cell.json.get("source")),
wait=wait,
callback=callback,
get_input=cell.get_input,
set_execution_count=cell.set_execution_count,
add_output=cell.add_output,
clear_output=cell.clear_output,
set_metadata=cell.set_metadata,
set_status=cell.set_status,
done=cell.ran,
)
def load_widgets_from_metadata(self) -> None:
"""Load widgets from state saved in notebook metadata."""
for comm_id, comm_data in (
self.json.get("metadata", {})
.get("widgets", {})
.get("application/vnd.jupyter.widget-state+json", {})
.get("state", {})
).items():
state = comm_data.get("state", {})
# Add _model_* keys to the state
for key, value in comm_data.items():
if key not in ("state", "buffers"):
state[f"_{key}"] = value
# Flag this widget as not linked to a widget in the kernel, so its state
# will not be persisted on the next save
state["__unlinked__"] = True
# Decode base64 encoded buffers and add buffer paths to data
buffers = []
buffer_paths = []
if "buffers" in state:
for buffer_data in state.pop("buffers", []):
buffer_paths.append(buffer_data["path"])
buffers.append(standard_b64decode(buffer_data["data"]))
# Add this comm to the notebook's current Comm map
self.comms[comm_id] = open_comm(
comm_container=self,
content={
"data": {
"state": state,
"buffer_paths": buffer_paths,
},
"comm_id": comm_id,
"target_name": "jupyter.widget",
},
buffers=buffers,
)
def lsp_open_handler(self, lsp: LspClient) -> None:
"""Tell the LSP we opened a file."""
lsp.open_nb(
path=self.path,
cells=[cell.lsp_cell for cell in self.rendered_cells()],
metadata=self.metadata,
)
def lsp_change_handler(self, lsp: LspClient) -> None:
"""Tell the LSP server a file metadata has changed."""
lsp.change_nb_meta(path=self.path, metadata=self.metadata)
def lsp_before_save_handler(self, lsp: LspClient) -> None:
"""Tell the the LSP we are about to save a document."""
# Do nothing for notebooks
def lsp_after_save_handler(self, lsp: LspClient) -> None:
"""Tell the the LSP we saved a document."""
lsp.save_nb(self.path)
def lsp_close_handler(self, lsp: LspClient) -> None:
"""Tell the LSP we opened a file."""
if lsp.can_close_nb:
lsp.close_nb(
path=self.path, cells=[cell.lsp_cell for cell in self.rendered_cells()]
)
else:
for cell in self.rendered_cells():
lsp.close_doc(cell.path)
def lsp_update_diagnostics(self, lsp: LspClient) -> None:
"""Process a new diagnostic report from the LSP."""
# Do nothing, these are handled by cells
# ################################### Settings ####################################
add_setting(
name="save_widget_state",
flags=["--save-widget-state"],
type_=bool,
help_="Save a notebook's widget state in the notebook metadata",
default=True,
description="""
When set to ``True``, the state of any widgets in the current notebook will
be saves in the notebook's metadata. This enables widgets to be displayed
when the notebook is re-opened without having to re-run the notebook.
""",
)
add_setting(
name="max_notebook_width",
flags=["--max-notebook-width"],
type_=int,
help_="Maximum width of notebooks",
default=120,
schema={
"minimum": 1,
},
description="""
The maximum width at which to display a notebook.
""",
)
add_setting(
name="expand",
flags=["--expand"],
type_=bool,
help_="Use the full width to display notebooks",
default=False,
description="""
Whether the notebook page should expand to fill the available width
""",
cmd_filter=~buffer_has_focus,
)
The provided code snippet includes necessary dependencies for implementing the `multiple_cells_selected` function. Write a Python function `def multiple_cells_selected() -> bool` to solve the following problem:
Determine if there is more than one selected cell.
Here is the function:
def multiple_cells_selected() -> bool:
"""Determine if there is more than one selected cell."""
from euporie.core.current import get_app
from euporie.core.tabs.notebook import BaseNotebook
nb = get_app().tab
if isinstance(nb, BaseNotebook):
return len(nb.selected_indices) > 1
return False | Determine if there is more than one selected cell. |
6,876 | from __future__ import annotations
import os
from functools import lru_cache, partial, reduce
from importlib import import_module
from shutil import which
from typing import TYPE_CHECKING
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.filters import (
Condition,
emacs_insert_mode,
emacs_mode,
to_filter,
vi_insert_mode,
vi_mode,
vi_replace_mode,
)
from euporie.core.key_binding.micro_state import MicroInputMode
def get_app() -> BaseApp:
"""Get the current active (running) Application."""
from euporie.core.app import BaseApp
session = _current_app_session.get()
if isinstance(session.app, BaseApp):
return session.app
# Use a baseapp as our "DummyApplication"
return BaseApp()
def get_app() -> NotebookApp:
"""Get the current application."""
return cast("NotebookApp", ptk_get_app())
class KernelTab(Tab, metaclass=ABCMeta):
"""A Tab which connects to a kernel."""
kernel: Kernel
kernel_language: str
_metadata: dict[str, Any]
bg_init = True
default_callbacks: MsgCallbacks
allow_stdin: bool
def __init__(
self,
app: BaseApp,
path: Path | None = None,
kernel: Kernel | None = None,
comms: dict[str, Comm] | None = None,
use_kernel_history: bool = False,
connection_file: Path | None = None,
) -> None:
"""Create a new instance of a tab with a kernel."""
# Init tab
super().__init__(app, path)
self.lsps: list[LspClient] = []
self.history: History = DummyHistory()
self.inspectors: list[Inspector] = []
self.inspector = FirstInspector(lambda: self.inspectors)
self.suggester: AutoSuggest = DummyAutoSuggest()
self.completers: list[Completer] = []
self.completer = DeduplicateCompleter(
DynamicCompleter(lambda: _MergedCompleter(self.completers))
)
self.formatters: list[Formatter] = self.app.formatters
self.reports: WeakKeyDictionary[LspClient, Report] = WeakKeyDictionary()
# The client-side comm states
self.comms: dict[str, Comm] = {}
# The current kernel input
self._current_input: KernelInput | None = None
if self.bg_init:
# Load kernel in a background thread
run_in_thread_with_context(
partial(
self.init_kernel, kernel, comms, use_kernel_history, connection_file
)
)
else:
self.init_kernel(kernel, comms, use_kernel_history, connection_file)
async def load_lsps(self) -> None:
"""Load the LSP clients."""
path = self.path
# Load list of LSP clients for the tab's language
self.lsps.extend(self.app.get_language_lsps(self.language))
# Wait for all lsps to be initialized, and setup hooks as they become ready
async def _await_load(lsp: LspClient) -> LspClient:
await lsp.initialized.wait()
return lsp
for ready in asyncio.as_completed([_await_load(lsp) for lsp in self.lsps]):
lsp = await ready
# Apply open, save, and close hooks to the tab
change_handler = partial(lambda lsp, tab: self.lsp_change_handler(lsp), lsp)
close_handler = partial(lambda lsp, tab: self.lsp_close_handler(lsp), lsp)
before_save_handler = partial(
lambda lsp, tab: self.lsp_before_save_handler(lsp), lsp
)
after_save_handler = partial(
lambda lsp, tab: self.lsp_after_save_handler(lsp), lsp
)
self.on_close += close_handler
self.on_change += change_handler
self.before_save += before_save_handler
self.after_save += after_save_handler
# Listen for LSP diagnostics
lsp.on_diagnostics += self.lsp_update_diagnostics
# Add completer
completer = LspCompleter(lsp=lsp, path=path)
self.completers.append(completer)
# Add inspector
inspector = LspInspector(lsp, path)
self.inspectors.append(inspector)
# Add formatter
formatter = LspFormatter(lsp, path)
self.formatters.append(formatter)
# Remove hooks if the LSP exits
def lsp_unload(lsp: LspClient) -> None:
self.on_change -= change_handler # noqa: B023
self.before_save -= before_save_handler # noqa: B023
self.after_save -= after_save_handler # noqa: B023
self.on_close -= close_handler # noqa: B023
if completer in self.completers: # noqa: B023
self.completers.remove(completer) # noqa: B023
if inspector in self.completers: # noqa: B023
self.inspectors.remove(inspector) # noqa: B023
if formatter in self.completers: # noqa: B023
self.formatters.remove(formatter) # noqa: B023
if completer in self.completers: # noqa: B023
self.completers.remove(completer) # noqa: B023
if inspector in self.inspectors: # noqa: B023
self.inspectors.remove(inspector) # noqa: B023
if formatter in self.formatters: # noqa: B023
self.formatters.remove(formatter) # noqa: B023
lsp.on_exit += lsp_unload
# Remove the lsp exit handler if this tab closes
self.on_close += lambda tab: (
(lsp.on_exit.__isub__(lsp_unload) and None) or None # noqa: B023
) # Magical typing
# Tell the LSP we have an open file
self.lsp_open_handler(lsp)
def pre_init_kernel(self) -> None:
"""Run stuff before the kernel is loaded."""
def post_init_kernel(self) -> None:
"""Run stuff after the kernel is loaded."""
def init_kernel(
self,
kernel: Kernel | None = None,
comms: dict[str, Comm] | None = None,
use_kernel_history: bool = False,
connection_file: Path | None = None,
) -> None:
"""Set up the tab's kernel and related components."""
self.pre_init_kernel()
self.kernel_queue: deque[Callable] = deque()
if kernel:
self.kernel = kernel
self.kernel.default_callbacks = self.default_callbacks
else:
self.kernel = Kernel(
kernel_tab=self,
allow_stdin=self.allow_stdin,
default_callbacks=self.default_callbacks,
connection_file=connection_file,
)
self.comms = comms or {} # The client-side comm states
self.completers.append(KernelCompleter(self.kernel))
self.inspectors.append(KernelInspector(self.kernel))
self.use_kernel_history = use_kernel_history
self.history = (
KernelHistory(self.kernel) if use_kernel_history else InMemoryHistory()
)
self.suggester = HistoryAutoSuggest(self.history)
self.app.create_background_task(self.load_lsps())
self.post_init_kernel()
def close(self, cb: Callable | None = None) -> None:
"""Shut down kernel when tab is closed."""
if hasattr(self, "kernel"):
self.kernel.shutdown()
super().close(cb)
def interrupt_kernel(self) -> None:
"""Interrupt the current `Notebook`'s kernel."""
self.kernel.interrupt()
def restart_kernel(self, cb: Callable | None = None) -> None:
"""Restart the current `Notebook`'s kernel."""
def _cb(result: dict[str, Any]) -> None:
if callable(cb):
cb()
if confirm := self.app.dialogs.get("confirm"):
confirm.show(
message="Are you sure you want to restart the kernel?",
cb=partial(self.kernel.restart, cb=_cb),
)
else:
self.kernel.restart(cb=_cb)
def kernel_started(self, result: dict[str, Any] | None = None) -> None:
"""Task to run when the kernel has started."""
# Check kernel has not failed
if not self.kernel_name or self.kernel.missing:
if not self.kernel_name:
msg = "No kernel selected"
else:
msg = f"Kernel '{self.kernel_display_name}' not installed"
self.change_kernel(
msg=msg,
startup=True,
)
elif self.kernel.status == "error":
self.report_kernel_error(self.kernel.error)
else:
# Wait for an idle kernel
if self.kernel.status != "idle":
self.kernel.wait_for_status("idle")
# Load widget comm info
# self.kernel.comm_info(target_name="jupyter.widget")
# Load kernel info
self.kernel.info(set_kernel_info=self.set_kernel_info)
# Load kernel history
if self.use_kernel_history:
self.app.create_background_task(self.load_history())
# Run queued kernel tasks when the kernel is idle
log.debug("Running %d kernel tasks", len(self.kernel_queue))
while self.kernel_queue:
self.kernel_queue.popleft()()
self.app.invalidate()
def report_kernel_error(self, error: Exception | None) -> None:
"""Report a kernel error to the user."""
log.debug("Kernel error", exc_info=error)
async def load_history(self) -> None:
"""Load kernel history."""
try:
await self.history.load().__anext__()
except StopAsyncIteration:
pass
def metadata(self) -> dict[str, Any]:
"""Return a dictionary to hold notebook / kernel metadata."""
return self._metadata
def kernel_name(self) -> str:
"""Return the name of the kernel defined in the notebook JSON."""
return self.metadata.get("kernelspec", {}).get(
"name", self.app.config.kernel_name
)
def kernel_name(self, value: str) -> None:
"""Return the name of the kernel defined in the notebook JSON."""
self.metadata.setdefault("kernelspec", {})["name"] = value
def language(self) -> str:
"""Return the name of the kernel defined in the notebook JSON."""
return self.metadata.get("kernelspec", {}).get("language")
def kernel_display_name(self) -> str:
"""Return the display name of the kernel defined in the notebook JSON."""
return self.metadata.get("kernelspec", {}).get("display_name", self.kernel_name)
def kernel_lang_file_ext(self) -> str:
"""Return the display name of the kernel defined in the notebook JSON."""
return self.metadata.get("language_info", {}).get("file_extension", ".py")
def current_input(self) -> KernelInput:
"""Return the currently active kernel input, if any."""
return self._current_input or KernelInput(self)
def set_kernel_info(self, info: dict) -> None:
"""Handle kernel info requests."""
self.metadata["language_info"] = info.get("language_info", {})
def change_kernel(self, msg: str | None = None, startup: bool = False) -> None:
"""Prompt the user to select a new kernel."""
kernel_specs = self.kernel.specs
# Warn the user if no kernels are installed
if not kernel_specs:
if startup and "no-kernels" in self.app.dialogs:
self.app.dialogs["no-kernels"].show()
return
# Automatically select the only kernel if there is only one
if startup and len(kernel_specs) == 1:
self.kernel.change(next(iter(kernel_specs)))
return
self.app.dialogs["change-kernel"].show(
tab=self, message=msg, kernel_specs=kernel_specs
)
def comm_open(self, content: dict, buffers: Sequence[bytes]) -> None:
"""Register a new kernel Comm object in the notebook."""
comm_id = str(content.get("comm_id"))
self.comms[comm_id] = open_comm(
comm_container=self, content=content, buffers=buffers
)
def comm_msg(self, content: dict, buffers: Sequence[bytes]) -> None:
"""Respond to a Comm message from the kernel."""
comm_id = str(content.get("comm_id"))
if comm := self.comms.get(comm_id):
comm.process_data(content.get("data", {}), buffers)
def comm_close(self, content: dict, buffers: Sequence[bytes]) -> None:
"""Close a notebook Comm."""
comm_id = content.get("comm_id")
if comm_id in self.comms:
del self.comms[comm_id]
def lsp_open_handler(self, lsp: LspClient) -> None:
"""Tell the LSP we opened a file."""
lsp.open_doc(
path=self.path, language=self.language, text=self.current_input.buffer.text
)
def lsp_change_handler(self, lsp: LspClient) -> None:
"""Tell the LSP server a file has changed."""
lsp.change_doc(
path=self.path,
language=self.language,
text=self.current_input.buffer.text,
)
def lsp_before_save_handler(self, lsp: LspClient) -> None:
"""Tell the the LSP we are about to save a document."""
lsp.will_save_doc(self.path)
def lsp_after_save_handler(self, lsp: LspClient) -> None:
"""Tell the the LSP we saved a document."""
lsp.save_doc(self.path, text=self.current_input.buffer.text)
def lsp_close_handler(self, lsp: LspClient) -> None:
"""Tell the LSP we opened a file."""
lsp.close_doc(path=self.path)
def lsp_update_diagnostics(self, lsp: LspClient) -> None:
"""Process a new diagnostic report from the LSP."""
if (diagnostics := lsp.reports.pop(self.path.as_uri(), None)) is not None:
self.reports[lsp] = Report.from_lsp(self.current_input.text, diagnostics)
self.app.invalidate()
def report(self) -> Report:
"""Return the current diagnostic reports."""
return Report.from_reports(*self.reports.values())
# ################################### Commands ####################################
def _change_kernel() -> None:
"""Change the notebook's kernel."""
if isinstance(kt := get_app().tab, KernelTab):
kt.change_kernel()
# ################################### Settings ####################################
add_setting(
name="kernel_name",
flags=["--kernel-name", "--kernel"],
type_=str,
help_="The name of the kernel to start by default",
default="python3",
description="""
The name of the kernel selected automatically by the console app or in new
notebooks. If set to an empty string, the user will be asked which kernel
to launch.
""",
)
add_setting(
name="record_cell_timing",
title="cell timing recording",
flags=["--record-cell-timing"],
type_=bool,
help_="Should timing data be recorded in cell metadata.",
default=False,
schema={
"type": "boolean",
},
description="""
When set, execution timing data will be recorded in cell metadata.
""",
)
The provided code snippet includes necessary dependencies for implementing the `kernel_tab_has_focus` function. Write a Python function `def kernel_tab_has_focus() -> bool` to solve the following problem:
Determine if there is a focused kernel tab.
Here is the function:
def kernel_tab_has_focus() -> bool:
"""Determine if there is a focused kernel tab."""
from euporie.core.current import get_app
from euporie.core.tabs.base import KernelTab
return isinstance(get_app().tab, KernelTab) | Determine if there is a focused kernel tab. |
6,877 | from __future__ import annotations
import os
from functools import lru_cache, partial, reduce
from importlib import import_module
from shutil import which
from typing import TYPE_CHECKING
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.filters import (
Condition,
emacs_insert_mode,
emacs_mode,
to_filter,
vi_insert_mode,
vi_mode,
vi_replace_mode,
)
from euporie.core.key_binding.micro_state import MicroInputMode
The provided code snippet includes necessary dependencies for implementing the `scrollable` function. Write a Python function `def scrollable(window: Window) -> Filter` to solve the following problem:
Return a filter which indicates if a window is scrollable.
Here is the function:
def scrollable(window: Window) -> Filter:
"""Return a filter which indicates if a window is scrollable."""
return Condition(
lambda: (
window.render_info is not None
and window.render_info.content_height > window.render_info.window_height
)
) | Return a filter which indicates if a window is scrollable. |
6,878 | from __future__ import annotations
from typing import TYPE_CHECKING
from prompt_toolkit.key_binding.key_bindings import _parse_key
from euporie.core.keys import Keys
The provided code snippet includes necessary dependencies for implementing the `if_no_repeat` function. Write a Python function `def if_no_repeat(event: KeyPressEvent) -> bool` to solve the following problem:
Return True when the previous event was delivered to another handler.
Here is the function:
def if_no_repeat(event: KeyPressEvent) -> bool:
"""Return True when the previous event was delivered to another handler."""
return not event.is_repeat | Return True when the previous event was delivered to another handler. |
6,879 | from __future__ import annotations
from typing import TYPE_CHECKING
from prompt_toolkit.key_binding.key_bindings import _parse_key
from euporie.core.keys import Keys
The provided code snippet includes necessary dependencies for implementing the `parse_keys` function. Write a Python function `def parse_keys(keys: AnyKeys) -> list[tuple[str | Keys, ...]]` to solve the following problem:
Pare a list of keys.
Here is the function:
def parse_keys(keys: AnyKeys) -> list[tuple[str | Keys, ...]]:
"""Pare a list of keys."""
output: list[tuple[str | Keys, ...]] = []
if not isinstance(keys, list):
keys = [keys]
for key in keys:
if isinstance(key, Keys):
output.append((key,))
elif isinstance(key, tuple):
output.append(tuple(_parse_key(k) for k in key))
else:
output.append((_parse_key(key),))
return output | Pare a list of keys. |
6,880 | from __future__ import annotations
from typing import TYPE_CHECKING
from prompt_toolkit.key_binding.key_bindings import _parse_key
from euporie.core.keys import Keys
KEY_ALIASES: dict[str | Keys, str] = {
Keys.ControlH: "backspace",
Keys.ControlM: "enter",
Keys.ControlI: "tab",
Keys.ControlUnderscore: "c-/",
Keys.ControlAt: "c-space",
}
def _format_key_str(key: str) -> str:
if key:
key = key.replace("c-", "Ctrl+").replace("s-", "Shift+").replace("A-", "Alt+")
parts = key.split("+")
if parts[-1].isupper():
parts.insert(-1, "Shift")
key = "+".join(parts)
return key.title()
The provided code snippet includes necessary dependencies for implementing the `format_keys` function. Write a Python function `def format_keys(keys: list[tuple[str | Keys, ...]]) -> list[str]` to solve the following problem:
Convert a list of tuples of keys to a string.
Here is the function:
def format_keys(keys: list[tuple[str | Keys, ...]]) -> list[str]:
"""Convert a list of tuples of keys to a string."""
s: list[str] = []
# Add duplicate key aliases to the list
keys_: list[tuple[str | Keys, ...]] = []
for key in keys:
if len(key) == 1 and key[0] in KEY_ALIASES:
keys_.append((KEY_ALIASES[key[0]],))
keys_.append(key)
# Format the key text
for key in keys_:
if isinstance(key, tuple):
s.append(
", ".join([_format_key_str(k) for k in key])
.replace("Escape, ", "Alt+")
.replace("Alt+Ctrl+m", "Ctrl+Alt+Enter")
)
elif isinstance(key, str):
s.append(_format_key_str(key))
else:
s.append(_format_key_str(key.value))
# Remove duplicate entries but keep the order
keys_ = list(dict(zip(keys, range(len(keys)))).keys())
return s | Convert a list of tuples of keys to a string. |
6,881 | from __future__ import annotations
from typing import TYPE_CHECKING
from prompt_toolkit.key_binding import KeyBindings
from euporie.core.commands import get_cmd
BINDINGS: dict[str, KeyBindingDefs] = {}
The provided code snippet includes necessary dependencies for implementing the `register_bindings` function. Write a Python function `def register_bindings(bindings: dict[str, KeyBindingDefs]) -> None` to solve the following problem:
Update the key-binding registry.
Here is the function:
def register_bindings(bindings: dict[str, KeyBindingDefs]) -> None:
"""Update the key-binding registry."""
for group, items in bindings.items():
if group not in BINDINGS:
BINDINGS[group] = {}
for command, keys in items.items():
BINDINGS[group][command] = keys | Update the key-binding registry. |
6,882 | from __future__ import annotations
import logging
from typing import TYPE_CHECKING, NamedTuple
from prompt_toolkit.cache import FastDictCache
from prompt_toolkit.data_structures import Point
from prompt_toolkit.key_binding.bindings.mouse import (
MOUSE_MOVE,
UNKNOWN_BUTTON,
UNKNOWN_MODIFIER,
KeyBindings,
typical_mouse_events,
urxvt_mouse_events,
xterm_sgr_mouse_events,
)
from prompt_toolkit.key_binding.bindings.mouse import (
load_mouse_bindings as load_ptk_mouse_bindings,
)
from prompt_toolkit.keys import Keys
from prompt_toolkit.mouse_events import MouseButton, MouseEventType, MouseModifier
from prompt_toolkit.mouse_events import MouseEvent as PtkMouseEvent
from euporie.core.app import BaseApp
class RelativePosition(NamedTuple):
"""Store the relative position or the mouse within a terminal cell."""
x: float
y: float
class MouseEvent(PtkMouseEvent):
"""Mouse event, which also store relative position of the mouse event in a cell."""
def __init__(
self,
position: Point,
event_type: MouseEventType,
button: MouseButton,
modifiers: frozenset[MouseModifier],
cell_position: RelativePosition | None,
) -> None:
"""Create new event instance."""
super().__init__(
position=position,
event_type=event_type,
button=button,
modifiers=modifiers,
)
self.cell_position = cell_position or RelativePosition(0.5, 0.5)
The provided code snippet includes necessary dependencies for implementing the `_parse_mouse_data` function. Write a Python function `def _parse_mouse_data( data: str, sgr_pixels: bool, cell_size_xy: tuple[int, int] ) -> MouseEvent | None` to solve the following problem:
Convert key-press data to a mouse event.
Here is the function:
def _parse_mouse_data(
data: str, sgr_pixels: bool, cell_size_xy: tuple[int, int]
) -> MouseEvent | None:
"""Convert key-press data to a mouse event."""
rx = ry = 0.5
# Parse incoming packet.
if data[2] == "M":
# Typical.
mouse_event, x, y = map(ord, data[3:])
# TODO: Is it possible to add modifiers here?
mouse_button, mouse_event_type, mouse_modifiers = typical_mouse_events[
mouse_event
]
# Handle situations where `PosixStdinReader` used surrogateescapes.
if x >= 0xDC00:
x -= 0xDC00
if y >= 0xDC00:
y -= 0xDC00
x -= 32
y -= 32
else:
# Urxvt and Xterm SGR.
# When the '<' is not present, we are not using the Xterm SGR mode,
# but Urxvt instead.
data = data[2:]
if data[:1] == "<":
sgr = True
data = data[1:]
else:
sgr = False
# Extract coordinates.
mouse_event, x, y = map(int, data[:-1].split(";"))
m = data[-1]
# Parse event type.
if sgr:
if sgr_pixels:
# Calculate cell position
cell_x, cell_y = cell_size_xy
px, py = x, y
fx, fy = px / cell_x + 1, py / cell_y + 1
x, y = int(fx), int(fy)
rx, ry = fx - x, fy - y
try:
(
mouse_button,
mouse_event_type,
mouse_modifiers,
) = xterm_sgr_mouse_events[mouse_event, m]
except KeyError:
return None
else:
# Some other terminals, like urxvt, Hyper terminal, ...
(
mouse_button,
mouse_event_type,
mouse_modifiers,
) = urxvt_mouse_events.get(
mouse_event, (UNKNOWN_BUTTON, MOUSE_MOVE, UNKNOWN_MODIFIER)
)
x -= 1
y -= 1
return MouseEvent(
position=Point(x=x, y=y),
event_type=mouse_event_type,
button=mouse_button,
modifiers=mouse_modifiers,
cell_position=RelativePosition(rx, ry),
) | Convert key-press data to a mouse event. |
6,883 | from __future__ import annotations
import logging
from typing import TYPE_CHECKING, NamedTuple
from prompt_toolkit.cache import FastDictCache
from prompt_toolkit.data_structures import Point
from prompt_toolkit.key_binding.bindings.mouse import (
MOUSE_MOVE,
UNKNOWN_BUTTON,
UNKNOWN_MODIFIER,
KeyBindings,
typical_mouse_events,
urxvt_mouse_events,
xterm_sgr_mouse_events,
)
from prompt_toolkit.key_binding.bindings.mouse import (
load_mouse_bindings as load_ptk_mouse_bindings,
)
from prompt_toolkit.keys import Keys
from prompt_toolkit.mouse_events import MouseButton, MouseEventType, MouseModifier
from prompt_toolkit.mouse_events import MouseEvent as PtkMouseEvent
from euporie.core.app import BaseApp
_MOUSE_EVENT_CACHE: FastDictCache[
tuple[str, bool, tuple[int, int]], MouseEvent | None
] = FastDictCache(get_value=_parse_mouse_data)
class BaseApp(Application):
"""All euporie apps.
The base euporie application class.
This subclasses the `prompt_toolkit.application.Application` class, so application
wide methods can be easily added.
"""
name: str
color_palette: ColorPalette
mouse_position: Point
config = Config()
log_stdout_level: str = "CRITICAL"
def __init__(
self,
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,
) -> None:
"""Instantiate euporie specific application variables.
After euporie specific application variables are instantiated, the application
instance is initiated.
Args:
title: The title string to set in the terminal
set_title: Whether to set the terminal title
leave_graphics: A filter which determines if graphics should be cleared
from the display when they are no longer active
extend_renderer_height: Whether the renderer height should be extended
beyond the height of the display
extend_renderer_width: Whether the renderer width should be extended
beyond the height of the display
enable_page_navigation_bindings: Determines if page navigation keybindings
should be loaded
kwargs: The key-word arguments for the :py:class:`Application`
"""
# Initialise the application
super().__init__(
**{
"color_depth": self.config.color_depth,
"editing_mode": self.get_edit_mode(),
"mouse_support": True,
"cursor": CursorConfig(),
"enable_page_navigation_bindings": enable_page_navigation_bindings,
**kwargs,
}
)
# Use custom renderer
self.renderer = Renderer(
self._merged_style,
self.output,
full_screen=self.full_screen,
mouse_support=self.mouse_support,
cpr_not_supported_callback=self.cpr_not_supported_callback,
extend_height=extend_renderer_height,
extend_width=extend_renderer_width,
)
# Contains the opened tab containers
self.tabs: list[Tab] = []
# Holds the search bar to pass to cell inputs
self.search_bar: SearchBar | None = None
# Holds the index of the current tab
self._tab_idx = 0
# Add state for micro key-bindings
self.micro_state = MicroState()
# Load the terminal information system
self.term_info = TerminalInfo(self.input, self.output, self.config)
# Floats at the app level
self.leave_graphics = to_filter(leave_graphics)
self.graphics: WeakSet[Float] = WeakSet()
self.dialogs: dict[str, Dialog] = {}
self.menus: dict[str, Float] = {}
self.floats = ChainedList(
self.graphics,
self.dialogs.values(),
self.menus.values(),
)
# Continue loading when the application has been launched
# and an event loop has been created
self.pre_run_callables = [self.pre_run]
self.post_load_callables: list[Callable[[], None]] = []
# Set default vi input mode to navigate
self.vi_state = ViState()
# Set a long timeout for mappings (e.g. dd)
self.timeoutlen = 1.0
# Set a short timeout for flushing input
self.ttimeoutlen = 0.0
# Use a custom key-processor which does not wait after escape keys
self.key_processor = KeyProcessor(_CombinedRegistry(self))
# List of key-bindings groups to load
self.bindings_to_load = [
"euporie.core.app.BaseApp",
"euporie.core.terminal.TerminalInfo",
]
from euporie.core.key_binding.bindings.page_navigation import (
load_page_navigation_bindings,
)
self._page_navigation_bindings = load_page_navigation_bindings(self.config)
# Allow hiding element when manually redrawing app
self._redrawing = False
self.redrawing = Condition(lambda: self._redrawing)
# Add an optional pager
self.pager: Pager | None = None
# Stores the initially focused element
self.focused_element: FocusableElement | None = None
# Set the terminal title
self.set_title = to_filter(set_title)
self.title = title or self.__class__.__name__
# Register config hooks
self.config.get_item("edit_mode").event += self.update_edit_mode
self.config.get_item("syntax_theme").event += self.update_style
self.config.get_item("color_scheme").event += self.update_style
self.config.get_item("log_level").event += lambda x: setup_logs(self.config)
self.config.get_item("log_file").event += lambda x: setup_logs(self.config)
self.config.get_item("log_config").event += lambda x: setup_logs(self.config)
self.config.get_item("color_depth").event += lambda x: setattr(
self, "_color_depth", _COLOR_DEPTHS[x.value]
)
# Set up the color palette
self.color_palette = ColorPalette()
self.color_palette.add_color("fg", "#ffffff", "default")
self.color_palette.add_color("bg", "#000000", "default")
# Set up a write position to limit mouse events to a particular region
self.mouse_limits: WritePosition | None = None
self.mouse_position = Point(0, 0)
# Store LSP client instances
self.lsp_clients: WeakValueDictionary[str, LspClient] = WeakValueDictionary()
# Build list of configured external formatters
self.formatters: list[Formatter] = [
CliFormatter(**info) for info in self.config.formatters
]
def title(self) -> str:
"""The application's title."""
return self._title
def title(self, value: str) -> None:
"""Set the terminal title."""
self._title = value
if self.set_title():
self.output.set_title(value)
def pause_rendering(self) -> 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.
"""
self._is_running = False
self.renderer._waiting_for_cpr_futures.append(asyncio.Future())
def resume_rendering(self) -> None:
"""Reume rendering the app."""
self._is_running = True
if futures := self.renderer._waiting_for_cpr_futures:
futures.pop()
def pre_run(self, app: Application | None = None) -> None:
"""Call during the 'pre-run' stage of application loading."""
# Determines which clipboard mechanism to use based on configuration
self.clipboard: Clipboard = ConfiguredClipboard(self)
# Determine what color depth to use
self._color_depth = _COLOR_DEPTHS.get(
self.config.color_depth, self.term_info.depth_of_color.value
)
# Set the application's style, and update it when the terminal responds
self.update_style()
self.term_info.colors.event += self.update_style
# Load completions menu. This must be done after the app is set, because
# :py:func:`get_app` is needed to access the config
self.menus["completions"] = Float(
content=Shadow(CompletionsMenu()),
xcursor=True,
ycursor=True,
)
# Open any files we need to
self.open_files()
# Load the layout
# We delay this until we have terminal responses to allow terminal graphics
# support to be detected first
self.layout = Layout(self.load_container(), self.focused_element)
async def run_async(
self,
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."""
with set_app(self):
# Load key bindings
self.load_key_bindings()
# Send queries to the terminal
self.term_info.send_all()
# Read responses
kp = self.key_processor
def read_from_input() -> None:
kp.feed_multiple(self.input.read_keys())
with self.input.raw_mode(), self.input.attach(read_from_input):
# Give the terminal time to respond and allow the event loop to read
# the terminal responses from the input
await asyncio.sleep(0.1)
kp.process_keys()
return await super().run_async(
pre_run, set_exception_handler, handle_sigint, slow_callback_duration
)
def load_input(cls) -> 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
"""
input_ = create_input(always_prefer_tty=True)
if (stdin := getattr(input_, "stdin", None)) and not stdin.isatty():
from euporie.core.io import IgnoredInput
input_ = IgnoredInput()
# Use a custom vt100 parser to allow querying the terminal
if parser := getattr(input_, "vt100_parser", None):
setattr( # noqa B010
input_, "vt100_parser", Vt100Parser(parser.feed_key_callback)
)
return input_
def load_output(cls) -> 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
"""
output = create_output(always_prefer_tty=True)
if isinstance(output, PtkVt100_Output):
output = Vt100_Output(
stdout=output.stdout,
get_size=output._get_size,
term=output.term,
default_color_depth=output.default_color_depth,
enable_bell=output.enable_bell,
)
return output
def post_load(self) -> None:
"""Allow subclasses to define additional loading steps."""
# Call extra callables
for cb in self.post_load_callables:
cb()
def load_key_bindings(self) -> None:
"""Load the application's key bindings."""
from euporie.core.key_binding.bindings.basic import load_basic_bindings
from euporie.core.key_binding.bindings.micro import load_micro_bindings
from euporie.core.key_binding.bindings.mouse import load_mouse_bindings
self._default_bindings = merge_key_bindings(
[
# Make sure that the above key bindings are only active if the
# currently focused control is a `BufferControl`. For other controls, we
# don't want these key bindings to intervene. (This would break "ptterm"
# for instance, which handles 'Keys.Any' in the user control itself.)
ConditionalKeyBindings(
merge_key_bindings(
[
# Load basic bindings.
load_ptk_basic_bindings(),
load_basic_bindings(),
# Load micro bindings
load_micro_bindings(config=self.config),
# Load emacs bindings.
load_emacs_bindings(),
load_emacs_search_bindings(),
load_emacs_shift_selection_bindings(),
# Load Vi bindings.
load_vi_bindings(),
load_vi_search_bindings(),
]
),
buffer_has_focus,
),
# Active, even when no buffer has been focused.
load_ptk_mouse_bindings(),
load_cpr_bindings(),
# Load extra mouse bindings
load_mouse_bindings(),
# Load terminal query response key bindings
# load_command_bindings("terminal"),
]
)
self.key_bindings = load_registered_bindings(
*self.bindings_to_load, config=self.config
)
def _on_resize(self) -> None:
"""Query the terminal dimensions on a resize event."""
self.term_info.pixel_dimensions.send()
super()._on_resize()
def launch(cls) -> None:
"""Launch the app."""
# Load default logging
setup_logs()
# Load the app's configuration
cls.config.load(cls)
# Run the application
with create_app_session(input=cls.load_input(), output=cls.load_output()):
# Create an instance of the app and run it
app = cls()
# Handle SIGTERM while the app is running
original_sigterm = signal.getsignal(signal.SIGTERM)
signal.signal(signal.SIGTERM, app.cleanup)
# Run the app
try:
result = app.run()
except (EOFError, KeyboardInterrupt):
result = None
finally:
signal.signal(signal.SIGTERM, original_sigterm)
# Shut down any remaining LSP clients at exit
app.shutdown_lsps()
return result
def cleanup(self, signum: int, frame: FrameType | None) -> None:
"""Restore the state of the terminal on unexpected exit."""
log.critical("Unexpected exit signal, restoring terminal")
output = self.output
self.exit()
self.shutdown_lsps()
# Reset terminal state
output.reset_cursor_key_mode()
output.enable_autowrap()
output.clear_title()
output.show_cursor()
output.reset_attributes()
self.renderer.reset()
# Exit the main thread
sys.exit(1)
async def interact(cls, ssh_session: PromptToolkitSSHSession) -> None:
"""Run the app asynchronously for the hub SSH server."""
await cls().run_async()
def load_container(self) -> FloatContainer:
"""Load the root container for this application.
Returns:
The root container for this app
"""
return FloatContainer(
content=self.layout.container or Window(),
floats=cast("list[Float]", self.floats),
)
def get_file_tabs(self, path: Path) -> list[type[Tab]]:
"""Return the tab to use for a file path."""
from euporie.core.tabs.base import Tab
path_mime = get_mime(path) or "text/plain"
log.debug("File %s has mime type: %s", path, path_mime)
tab_options = set()
for tab_cls in Tab._registry:
for mime_type in tab_cls.mime_types:
if PurePath(path_mime).match(mime_type):
tab_options.add(tab_cls)
if path.suffix in tab_cls.file_extensions:
tab_options.add(tab_cls)
return sorted(tab_options, key=lambda x: x.weight, reverse=True)
def get_file_tab(self, path: Path) -> type[Tab] | None:
"""Return the tab to use for a file path."""
if tabs := self.get_file_tabs(path):
return tabs[0]
return None
def get_language_lsps(self, language: str) -> list[LspClient]:
"""Return the approprrate LSP clients for a given language."""
clients = []
if self.config.enable_language_servers:
from shutil import which
lsps = {**KNOWN_LSP_SERVERS, **self.config.language_servers}
for name, kwargs in lsps.items():
if kwargs:
client = None
if (
(
not (lsp_langs := kwargs.get("languages"))
or language in lsp_langs
)
and not (client := self.lsp_clients.get(name))
and which(kwargs["command"][0])
):
client = LspClient(name, **kwargs)
self.lsp_clients[name] = client
client.start()
if client:
clients.append(client)
return clients
def shutdown_lsps(self) -> None:
"""Shut down all the remaining LSP servers."""
from concurrent.futures import as_completed
# Wait for all LSP exit calls to complete
# The exit calls occur in the LSP event loop thread
list(as_completed([lsp.exit() for lsp in self.lsp_clients.values()]))
def open_file(
self, path: Path, read_only: bool = False, tab_class: type[Tab] | None = None
) -> None:
"""Create a tab for a file.
Args:
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
"""
ppath = parse_path(path)
log.info("Opening file %s", path)
for tab in self.tabs:
if ppath == getattr(tab, "path", "") and (
tab_class is None or isinstance(tab, tab_class)
):
log.info("File %s already open, activating", path)
self.layout.focus(tab)
break
else:
if tab_class is None:
tab_class = self.get_file_tab(path)
if tab_class is None:
log.error("Unable to display file %s", path)
else:
tab = tab_class(self, ppath)
self.tabs.append(tab)
# Ensure the opened tab is focused at app start
self.focused_element = tab
# Ensure the newly opened tab is selected
self.tab_idx = len(self.tabs) - 1
def open_files(self) -> None:
"""Open the files defined in the configuration."""
for file in self.config.files:
self.open_file(file)
def tab(self) -> Tab | None:
"""Return the currently selected tab container object."""
if self.tabs:
# Detect if focused tab has changed
# Find index of selected child
for i, tab in enumerate(self.tabs):
if self.render_counter > 0 and self.layout.has_focus(tab):
self._tab_idx = i
break
self._tab_idx = max(0, min(self._tab_idx, len(self.tabs) - 1))
return self.tabs[self._tab_idx]
else:
return None
def tab_idx(self) -> int:
"""Get the current tab index."""
return self._tab_idx
def tab_idx(self, value: int) -> None:
"""Set the current tab by index."""
self._tab_idx = value % (len(self.tabs) or 1)
if self.tabs:
container = to_container(self.tabs[self._tab_idx])
try:
self.layout.focus(container)
except ValueError:
self.to_focus = container
def focus_tab(self, tab: Tab) -> None:
"""Make a tab visible and focuses it."""
self.tab_idx = self.tabs.index(tab)
def cleanup_closed_tab(self, tab: Tab) -> None:
"""Remove a tab container from the current instance of the app.
Args:
tab: The closed instance of the tab container
"""
# Remove tab
if tab in self.tabs:
self.tabs.remove(tab)
# Update body container to reflect new tab list
# assert isinstance(self.body_container.body, HSplit)
# self.body_container.body.children[0] = VSplit(self.tabs)
# Focus another tab if one exists
if self.tab:
self.layout.focus(self.tab)
# If a tab is not open, the status bar is not shown, so focus the logo, so
# pressing tab focuses the menu
else:
try:
self.layout.focus_next()
except ValueError:
pass
def close_tab(self, tab: Tab | None = None) -> None:
"""Close a notebook tab.
Args:
tab: The instance of the tab to close. If `None`, the currently
selected tab will be closed.
"""
if tab is None:
tab = self.tab
if tab is not None:
tab.close(cb=partial(self.cleanup_closed_tab, tab))
def get_edit_mode(self) -> EditingMode:
"""Return the editing mode enum defined in the configuration."""
from euporie.core.key_binding.bindings.micro import EditingMode
return {
"micro": EditingMode.MICRO, # type: ignore
"vi": EditingMode.VI,
"emacs": EditingMode.EMACS,
}.get(
str(self.config.edit_mode),
EditingMode.MICRO, # type: ignore
)
def update_edit_mode(self, setting: Setting | None = None) -> None:
"""Set the keybindings for editing mode."""
self.editing_mode = self.get_edit_mode()
log.debug("Editing mode set to: %s", self.editing_mode)
def syntax_theme(self) -> str:
"""Calculate the current syntax theme."""
syntax_theme = self.config.syntax_theme
if syntax_theme == self.config.settings["syntax_theme"].default:
syntax_theme = "tango" if self.color_palette.bg.is_light else "euporie"
return syntax_theme
def create_merged_style(self) -> 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
"""
# Get foreground and background colors based on the configured colour scheme
theme_colors: dict[str, dict[str, str]] = {
"default": {},
"light": {"fg": "#202020", "bg": "#F0F0F0"},
"dark": {"fg": "#F0F0F0", "bg": "#202020"},
"white": {"fg": "#000000", "bg": "#FFFFFF"},
"black": {"fg": "#FFFFFF", "bg": "#000000"},
# TODO - use config.custom_colors
"custom": {
"fg": self.config.custom_foreground_color,
"bg": self.config.custom_background_color,
},
}
base_colors: dict[str, str] = {
**DEFAULT_COLORS,
**self.term_info.colors.value,
**theme_colors.get(self.config.color_scheme, theme_colors["default"]),
}
# Build a color palette from the fg/bg colors
self.color_palette = cp = ColorPalette()
for name, color in base_colors.items():
cp.add_color(
name,
color or theme_colors["default"][name],
"default" if name in ("fg", "bg") else name,
)
# Add accent color
# self.color_palette.add_color(
# "hl",
# (bg := self.color_palette.bg)
# .adjust(
# hue=(bg.hue + (bg.hue - 0.036)) % 1,
# saturation=(0.88 - bg.saturation),
# brightness=0.4255 - bg.brightness,
# )
# .base_hex,
# )
cp.add_color(
"hl", base_colors.get(self.config.accent_color, self.config.accent_color)
)
# Build app style
app_style = build_style(cp)
# Apply style transformations based on the configured color scheme
self.style_transformation = merge_style_transformations(
[
ConditionalStyleTransformation(
SetDefaultColorStyleTransformation(
fg=base_colors["fg"], bg=base_colors["bg"]
),
self.config.color_scheme != "default",
),
ConditionalStyleTransformation(
SwapLightAndDarkStyleTransformation(),
self.config.color_scheme == "inverse",
),
]
)
return merge_styles(
[
style_from_pygments_cls(get_style_by_name(self.syntax_theme)),
Style(MIME_STYLE),
Style(HTML_STYLE),
Style(LOG_STYLE),
Style(IPYWIDGET_STYLE),
app_style,
]
)
def update_style(
self,
query: TerminalQuery | Setting | None = None,
) -> None:
"""Update the application's style when the syntax theme is changed."""
self.renderer.style = self.create_merged_style()
def refresh(self) -> None:
"""Reset all tabs."""
for tab in self.tabs:
to_container(tab).reset()
def _create_merged_style(
self, include_default_pygments_style: Filter | None = None
) -> BaseStyle:
"""Block default style loading."""
return DummyStyle()
def draw(self, render_as_done: bool = True) -> None:
"""Draw the app without focus, leaving the cursor below the drawn output."""
# Hide ephemeral containers
self._redrawing = True
# Ensure nothing in the layout has focus
self.layout._stack.append(Window())
# Re-draw the app
self._redraw(render_as_done=render_as_done)
# Remove the focus block
self.layout._stack.pop()
# Show ephemeral containers
self._redrawing = False
# Ensure the renderer knows where the cursor is
self._request_absolute_cursor_position()
def _handle_exception(
self, loop: AbstractEventLoop, context: dict[str, Any]
) -> None:
exception = context.get("exception")
# Log observed exceptions to the log
log.exception("An unhandled exception occurred", exc_info=exception)
# async def cancel_and_wait_for_background_tasks(self) -> "None":
# """Cancel background tasks, ignoring exceptions."""
# # try:
# # await super().cancel_and_wait_for_background_tasks()
# # except ValueError as e:
# # for task in self._background_tasks:
# # print(task)
# # raise e
#
# for task in self._background_tasks:
# print(task)
# print(task.get_loop())
# await asyncio.wait([task])
# ################################### Commands ####################################
def _quit() -> None:
"""Quit euporie."""
get_app().exit()
name="close-tab",
filter=tab_has_focus,
menu_title="Close File",
)
def _close_tab() -> None:
"""Close the current tab."""
get_app().close_tab()
filter=tab_has_focus,
)
def _next_tab() -> None:
"""Switch to the next tab."""
get_app().tab_idx += 1
filter=tab_has_focus,
)
def _previous_tab() -> None:
"""Switch to the previous tab."""
get_app().tab_idx -= 1
filter=~buffer_has_focus,
)
def _focus_next() -> None:
"""Focus the next control."""
get_app().layout.focus_next()
filter=~buffer_has_focus,
)
def _focus_previous() -> None:
"""Focus the previous control."""
get_app().layout.focus_previous()
def _clear_screen() -> None:
"""Clear the screen."""
get_app().renderer.clear()
# ################################### Settings ####################################w
add_setting(
name="files",
default=[],
flags=["files"],
nargs="*",
type_=UPath,
help_="List of file names to open",
schema={
"type": "array",
"items": {
"description": "File path",
"type": "string",
},
},
description="""
A list of file paths to open when euporie is launched.
""",
)
add_setting(
name="edit_mode",
flags=["--edit-mode"],
type_=str,
choices=["micro", "emacs", "vi"],
title="Editor key bindings",
help_="Key-binding mode for text editing",
default="micro",
description="""
Key binding style to use when editing cells.
""",
)
add_setting(
name="tab_size",
flags=["--tab-size"],
type_=int,
help_="Spaces per indentation level",
default=4,
schema={
"minimum": 1,
},
description="""
The number of spaces to use per indentation level. Should be set to 4.
""",
)
add_setting(
name="terminal_polling_interval",
flags=["--terminal-polling-interval"],
type_=float,
help_="Time between terminal colour queries",
default=0.0,
schema={
"min": 0.0,
},
description="""
Determine how frequently the terminal should be polled for changes to the
background / foreground colours. Set to zero to disable terminal polling.
""",
)
add_setting(
name="formatters",
flags=["--formatters"],
type_=json.loads,
help_="List of external code formatters",
default=[
# {"command": ["ruff", "format", "-"], "languages": ["python"]},
# {"command": ["black", "-"], "languages": ["python"]},
# {"command": ["isort", "-"], "languages": ["python"]},
],
action="append",
schema={
"type": "array",
"items": {
"type": "object",
"properties": {
"command": {
"type": "array",
"items": [{"type": "string"}],
},
"languages": {
"type": "array",
"items": [{"type": "string", "unique": True}],
},
},
"required": ["command", "languages"],
},
},
description="""
An array listing languages and commands of formatters to use for
reformatting code cells. The command is an array of the command any any
arguments. Code to be formatted is pass in via the standard input, and
replaced with the standard output.
e.g.
[
{"command": ["ruff", "format", "-"], "languages": ["python"]},
{"command": ["black", "-"], "languages": ["python"]},
{"command": ["isort", "-"], "languages": ["python"]}
]
""",
)
add_setting(
name="syntax_theme",
flags=["--syntax-theme"],
type_=str,
help_="Syntax highlighting theme",
default="euporie",
schema={
# Do not want to print all theme names in `--help` screen as it looks messy
# so we only add them in the scheme, not as setting choices
"enum": list(pygments_styles.keys()),
},
description="""
The name of the pygments style to use for syntax highlighting.
""",
)
add_setting(
name="color_depth",
flags=["--color-depth"],
type_=int,
choices=[1, 4, 8, 24],
default=None,
help_="The color depth to use",
description="""
The number of bits to use to represent colors displayable on the screen.
If set to None, the supported color depth of the terminal will be detected
automatically.
""",
)
add_setting(
name="multiplexer_passthrough",
flags=["--multiplexer-passthrough"],
type_=bool,
help_="Use passthrough from within terminal multiplexers",
default=False,
hidden=~in_mplex,
description="""
If set and euporie is running inside a terminal multiplexer
(:program:`screen` or :program:`tmux`), then certain escape sequences
will be passed-through the multiplexer directly to the terminal.
This affects things such as terminal color detection and graphics display.
for tmux, you will also need to ensure that ``allow-passthrough`` is set to
``on`` in your :program:`tmux` configuration.
.. warning::
Terminal graphics in :program:`tmux` is experimental, and is not
guaranteed to work. Use at your own risk!
.. note::
As of version :command:`tmux` version ``3.4`` sixel graphics are
supported, which may result in better terminal graphics then using
multiplexer passthrough.
""",
)
add_setting(
name="color_scheme",
flags=["--color-scheme"],
type_=str,
choices=["default", "inverse", "light", "dark", "black", "white", "custom"],
help_="The color scheme to use",
default="default",
description="""
The color scheme to use: `auto` means euporie will try to use your
terminal's color scheme, `light` means black text on a white background,
and `dark` means white text on a black background.
""",
)
add_setting(
name="custom_background_color",
flags=["--custom-background-color", "--custom-bg-color", "--bg"],
type_=str,
help_='Background color for "Custom" color theme',
default="#073642",
schema={
"maxLength": 7,
},
description="""
The hex code of the color to use for the background in the "Custom" color
scheme.
""",
)
add_setting(
name="custom_foreground_color",
flags=["--custom-foreground-color", "--custom-fg-color", "--fg"],
type_=str,
help_='Foreground color for "Custom" color theme',
default="#839496",
schema={
"maxLength": 7,
},
description="""
The hex code of the color to use for the foreground in the "Custom" color
scheme.
""",
)
add_setting(
name="accent_color",
flags=["--accent-color"],
type_=str,
help_="Accent color to use in the app",
default="ansiblue",
description="""
The hex code of a color to use for the accent color in the application.
""",
)
add_setting(
name="key_bindings",
flags=["--key-bindings"],
type_=json.loads,
help_="Additional key binding definitions",
default={},
description="""
A mapping of component names to mappings of command name to key-binding lists.
""",
schema={
"type": "object",
},
)
add_setting(
name="graphics",
flags=["--graphics"],
choices=["none", "sixel", "kitty", "iterm"],
type_=str,
default=None,
help_="The preferred graphics protocol",
description="""
The graphics protocol to use, if supported by the terminal.
If set to "none", terminal graphics will not be used.
""",
)
add_setting(
name="force_graphics",
flags=["--force-graphics"],
type_=bool,
default=False,
help_="Force use of specified graphics protocol",
description="""
When set to :py:const:`True`, the graphics protocol specified by the
:option:`graphics` configuration option will be used even if the terminal
does not support it.
This is also useful if you want to use graphics in :command:`euporie-hub`.
""",
)
add_setting(
name="enable_language_servers",
flags=["--enable-language-servers", "--lsp"],
menu_title="Language servers",
type_=bool,
default=False,
help_="Enable language server support",
description="""
When set to :py:const:`True`, language servers will be used for liniting,
code inspection, and code formatting.
Additional language servers can be added using the
:option:`language-servers` option.
""",
)
add_setting(
name="language_servers",
flags=["--language-servers"],
type_=json.loads,
help_="Language server configurations",
default={},
schema={
"type": "object",
"items": {
"type": "object",
"patternProperties": {
"^[0-9]+$": {
"type": "object",
"properties": {
"command": {
"type": "array",
"items": [{"type": "string"}],
},
"language": {
"type": "array",
"items": [{"type": "string", "unique": True}],
},
},
"required": ["command"],
}
},
},
},
description="""
Additional language servers can be defined here, e.g.:
{
"ruff": {"command": ["ruff-lsp"], "languages": ["python"]},
"pylsp": {"command": ["pylsp"], "languages": ["python"]},
"typos": {"command": ["typos-lsp"], "languages": []}
}
The following properties are required:
- The name to be given to the the language server, must be unique
- The command list consists of the process to launch, followed by any
command line arguments
- A list of language the language server supports. If no languages are
given, the language server will be used for documents of any language.
To disable one of the default language servers, its name can be set to an
empty dictionary. For example, the following would disable the awk language
server:
{
"awk-language-server": {},
}
""",
)
# ################################# Key Bindings ##################################
register_bindings(
{
"euporie.core.app.BaseApp": {
"quit": ["c-q", "<sigint>"],
"close-tab": "c-w",
"next-tab": "c-pagedown",
"previous-tab": "c-pageup",
"focus-next": "s-tab",
"focus-previous": "tab",
"clear-screen": "c-l",
}
}
)
The provided code snippet includes necessary dependencies for implementing the `load_mouse_bindings` function. Write a Python function `def load_mouse_bindings() -> KeyBindings` to solve the following problem:
Additional key-bindings to deal with SGR-pixel mouse positioning.
Here is the function:
def load_mouse_bindings() -> KeyBindings:
"""Additional key-bindings to deal with SGR-pixel mouse positioning."""
key_bindings = load_ptk_mouse_bindings()
@key_bindings.add(Keys.Vt100MouseEvent, eager=True)
def _(event: KeyPressEvent) -> NotImplementedOrNone:
"""Handle incoming mouse event, include SGR-pixel mode."""
# Ensure mypy knows this would only run in a euporie appo
assert isinstance(app := event.app, BaseApp)
if not event.app.renderer.height_is_known:
return NotImplemented
mouse_event = _MOUSE_EVENT_CACHE[
event.data, app.term_info.sgr_pixel_status.value, app.term_info.cell_size_px
]
if mouse_event is None:
return NotImplemented
# Only handle mouse events when we know the window height.
if mouse_event.event_type is not None:
# Take region above the layout into account. The reported
# coordinates are absolute to the visible part of the terminal.
from prompt_toolkit.renderer import HeightIsUnknownError
x, y = mouse_event.position
try:
rows_above = app.renderer.rows_above_layout
except HeightIsUnknownError:
return NotImplemented
else:
y -= rows_above
# Save global mouse position
app.mouse_position = mouse_event.position
# Apply limits to mouse position if enabled
if (mouse_limits := app.mouse_limits) is not None:
x = max(
mouse_limits.xpos,
min(x, mouse_limits.xpos + (mouse_limits.width - 1)),
)
y = max(
mouse_limits.ypos,
min(y, mouse_limits.ypos + (mouse_limits.height - 1)),
)
mouse_event.position = Point(x=x, y=y)
# Call the mouse handler from the renderer.
# Note: This can return `NotImplemented` if no mouse handler was
# found for this position, or if no repainting needs to
# happen. this way, we avoid excessive repaints during mouse
# movements.
handler = event.app.renderer.mouse_handlers.mouse_handlers[y][x]
return handler(mouse_event)
return NotImplemented
return key_bindings | Additional key-bindings to deal with SGR-pixel mouse positioning. |
6,884 | from __future__ import annotations
import logging
from typing import TYPE_CHECKING
from prompt_toolkit.application.current import get_app
from prompt_toolkit.filters import buffer_has_focus
from prompt_toolkit.key_binding.bindings.page_navigation import (
load_emacs_page_navigation_bindings,
load_vi_page_navigation_bindings,
)
from prompt_toolkit.key_binding.key_bindings import (
ConditionalKeyBindings,
merge_key_bindings,
)
from euporie.core.commands import add_cmd
from euporie.core.filters import micro_mode
from euporie.core.key_binding.registry import (
load_registered_bindings,
register_bindings,
)
def micro_mode() -> bool:
"""When the micro key-bindings are active."""
from euporie.core.current import get_app
return get_app().editing_mode == EditingMode.MICRO # type: ignore
def load_registered_bindings(
*names: str, config: Config | None = None
) -> KeyBindingsBase:
"""Assign key-bindings to commands based on a dictionary."""
kb = KeyBindings()
for name in names:
binding_dict = BINDINGS.get(name, {})
# Augment with bindings from config
if config is not None:
binding_dict.update(config.key_bindings.get(name, {}))
for command, keys in binding_dict.items():
get_cmd(command).bind(kb, keys)
return kb
class Config:
"""A configuration store."""
settings: ClassVar[dict[str, Setting]] = {}
conf_file_name = "config.json"
def __init__(self) -> None:
"""Create a new configuration object instance."""
self.app_name: str = "base"
self.app_cls: type[ConfigurableApp] | None = None
def _save(self, setting: Setting) -> None:
"""Save settings to user's configuration file."""
json_data = self.load_config_file()
json_data.setdefault(self.app_name, {})[setting.name] = setting.value
if self.valid_user:
log.debug("Saving setting `%s`", setting)
with self.config_file_path.open("w") as f:
json.dump(json_data, f, indent=2)
def load(self, cls: type[ConfigurableApp]) -> None:
"""Load the command line, environment, and user configuration."""
from euporie.core.log import setup_logs
self.app_cls = cls
self.app_name = cls.name
log.debug("Loading config for %s", self.app_name)
user_conf_dir = Path(user_config_dir(__app_name__, appauthor=None))
user_conf_dir.mkdir(exist_ok=True, parents=True)
self.config_file_path = (user_conf_dir / self.conf_file_name).with_suffix(
".json"
)
self.valid_user = True
config_maps = {
# Load command line arguments
"command line arguments": self.load_args(),
# Load app specific env vars
"app-specific environment variable": self.load_env(app_name=self.app_name),
# Load global env vars
"global environment variable": self.load_env(),
# Load app specific user config
"app-specific user configuration": self.load_user(app_name=self.app_name),
# Load global user config
"user configuration": self.load_user(),
}
set_values = ChainMap(*config_maps.values())
for name, setting in Config.settings.items():
if setting.name in set_values:
# Set value without triggering hooks
setting._value = set_values[name]
setting.event += self._save
# Set-up logs
setup_logs(self)
# Save a list of unknown configuration options so we can warn about them once
# the logs are configured
for map_name, map_values in config_maps.items():
for option_name in map_values.keys() - Config.settings.keys():
if not isinstance(set_values[option_name], dict):
log.warning(
"Configuration option '%s' not recognised in %s",
option_name,
map_name,
)
def schema(self) -> dict[str, Any]:
"""Return a JSON schema for the config."""
return {
"title": "Euporie Configuration",
"description": "A configuration for euporie",
"type": "object",
"properties": {name: item.schema for name, item in self.settings.items()},
}
def load_parser(self) -> argparse.ArgumentParser:
"""Construct an :py:class:`ArgumentParser`."""
parser = ArgumentParser(
description=self.app_cls.__doc__,
epilog=__copyright__,
allow_abbrev=True,
formatter_class=argparse.MetavarTypeHelpFormatter,
)
# Add options to the relevant subparsers
for setting in self.settings.values():
args, kwargs = setting.parser_args
parser.add_argument(*args, **kwargs)
return parser
def load_args(self) -> dict[str, Any]:
"""Attempt to load configuration settings from commandline flags."""
result = {}
# Parse known arguments
namespace, remainder = self.load_parser().parse_known_intermixed_args()
# Update argv to leave the remaining arguments for subsequent apps
sys.argv[1:] = remainder
# Validate arguments
for name, value in vars(namespace).items():
if value is not None:
# Convert to json and back to attain json types
json_data = json.loads(_json_encoder.encode({name: value}))
try:
fastjsonschema.validate(self.schema, json_data)
except fastjsonschema.JsonSchemaValueException as error:
log.warning("Error in command line parameter `%s`: %s", name, error)
log.warning("%s: %s", name, value)
else:
result[name] = value
return result
def load_env(self, app_name: str = "") -> dict[str, Any]:
"""Attempt to load configuration settings from environment variables."""
result = {}
for name, setting in self.settings.items():
if app_name:
env = f"{__app_name__.upper()}_{self.app_name.upper()}_{setting.name.upper()}"
else:
env = f"{__app_name__.upper()}_{setting.name.upper()}"
if env in os.environ:
value = os.environ.get(env)
parsed_value: Any = value
# Attempt to parse the value as a literal
if value:
try:
parsed_value = literal_eval(value)
except (
ValueError,
TypeError,
SyntaxError,
MemoryError,
RecursionError,
):
pass
# Attempt to cast the value to the desired type
try:
parsed_value = setting.type(value)
except (ValueError, TypeError):
log.warning(
"Environment variable `%s` not understood" " - `%s` expected",
env,
setting.type.__name__,
)
else:
json_data = json.loads(_json_encoder.encode({name: parsed_value}))
try:
fastjsonschema.validate(self.schema, json_data)
except fastjsonschema.JsonSchemaValueException as error:
log.error("Error in environment variable: `%s`\n%s", env, error)
else:
result[name] = parsed_value
return result
def load_config_file(self) -> dict[str, Any]:
"""Attempt to load JSON configuration file."""
results = {}
assert isinstance(self.config_file_path, Path)
if self.valid_user and self.config_file_path.exists():
with self.config_file_path.open() as f:
try:
json_data = json.load(f)
except json.decoder.JSONDecodeError:
log.error(
"Could not parse the configuration file: %s\nIs it valid json?",
self.config_file_path,
)
self.valid_user = False
else:
results.update(json_data)
return results
def load_user(self, app_name: str = "") -> dict[str, Any]:
"""Attempt to load JSON configuration file."""
results = {}
# Load config file
json_data = self.load_config_file()
# Load section for the current app
if app_name:
json_data = json_data.get(self.app_name, {})
# Validate the configuration file
try:
# Validate a copy so the original data is not modified
fastjsonschema.validate(self.schema, dict(json_data))
except fastjsonschema.JsonSchemaValueException as error:
log.warning("Error in config file: `%s`: %s", self.config_file_pathi, error)
self.valid_user = False
else:
results.update(json_data)
return results
def get(self, name: str, default: Any = None) -> Any:
"""Access a configuration value, falling back to the default value if unset.
Args:
name: The name of the attribute to access.
default: The value to return if the name is not found
Returns:
The configuration variable value.
"""
if name in self.settings:
return self.settings[name].value
else:
return default
def get_item(self, name: str) -> Any:
"""Access a configuration item.
Args:
name: The name of the attribute to access.
Returns:
The configuration item.
"""
return self.settings.get(name)
def filter(self, name: str) -> Filter:
"""Return a :py:class:`Filter` for a configuration item."""
return Condition(partial(self.get, name))
def __getattr__(self, name: str) -> Any:
"""Enable access of config elements via dotted attributes.
Args:
name: The name of the attribute to access.
Returns:
The configuration variable value.
"""
return self.get(name)
def __setitem__(self, name: str, value: Any) -> None:
"""Set a configuration attribute.
Args:
name: The name of the attribute to set.
value: The value to give the attribute.
"""
setting = self.settings[name]
setting.value = value
The provided code snippet includes necessary dependencies for implementing the `load_page_navigation_bindings` function. Write a Python function `def load_page_navigation_bindings(config: Config | None = None) -> KeyBindingsBase` to solve the following problem:
Load page navigation key-bindings for text entry.
Here is the function:
def load_page_navigation_bindings(config: Config | None = None) -> KeyBindingsBase:
"""Load page navigation key-bindings for text entry."""
return ConditionalKeyBindings(
merge_key_bindings(
[
load_emacs_page_navigation_bindings(),
load_vi_page_navigation_bindings(),
ConditionalKeyBindings(
load_registered_bindings(
"euporie.core.key_binding.bindings.page_navigation.PageNavigation",
config=config,
),
micro_mode,
),
]
),
buffer_has_focus,
) | Load page navigation key-bindings for text entry. |
6,885 | from __future__ import annotations
import logging
from typing import TYPE_CHECKING
from prompt_toolkit.application.current import get_app
from prompt_toolkit.filters import buffer_has_focus
from prompt_toolkit.key_binding.bindings.page_navigation import (
load_emacs_page_navigation_bindings,
load_vi_page_navigation_bindings,
)
from prompt_toolkit.key_binding.key_bindings import (
ConditionalKeyBindings,
merge_key_bindings,
)
from euporie.core.commands import add_cmd
from euporie.core.filters import micro_mode
from euporie.core.key_binding.registry import (
load_registered_bindings,
register_bindings,
)
The provided code snippet includes necessary dependencies for implementing the `scroll_page_down` function. Write a Python function `def scroll_page_down(event: KeyPressEvent) -> None` to solve the following problem:
Scroll page down (prefer the cursor at the top of the page, after scrolling).
Here is the function:
def scroll_page_down(event: KeyPressEvent) -> None:
"""Scroll page down (prefer the cursor at the top of the page, after scrolling)."""
w = event.app.layout.current_window
b = event.app.current_buffer
if w and w.render_info:
# Scroll down one page.
line_index = b.document.cursor_position_row
page = w.render_info.window_height
if (
(screen := get_app().renderer._last_screen)
and (wp := screen.visible_windows_to_write_positions.get(w))
and (bbox := getattr(wp, "bbox", None))
):
page -= bbox.top + bbox.bottom
line_index = max(line_index + page, w.vertical_scroll + 1)
w.vertical_scroll = line_index
b.cursor_position = b.document.translate_row_col_to_index(line_index, 0)
b.cursor_position += b.document.get_start_of_line_position(
after_whitespace=True
) | Scroll page down (prefer the cursor at the top of the page, after scrolling). |
6,886 | from __future__ import annotations
import logging
from typing import TYPE_CHECKING
from prompt_toolkit.application.current import get_app
from prompt_toolkit.filters import buffer_has_focus
from prompt_toolkit.key_binding.bindings.page_navigation import (
load_emacs_page_navigation_bindings,
load_vi_page_navigation_bindings,
)
from prompt_toolkit.key_binding.key_bindings import (
ConditionalKeyBindings,
merge_key_bindings,
)
from euporie.core.commands import add_cmd
from euporie.core.filters import micro_mode
from euporie.core.key_binding.registry import (
load_registered_bindings,
register_bindings,
)
The provided code snippet includes necessary dependencies for implementing the `scroll_page_up` function. Write a Python function `def scroll_page_up(event: KeyPressEvent) -> None` to solve the following problem:
Scroll page up (prefer the cursor at the bottom of the page, after scrolling).
Here is the function:
def scroll_page_up(event: KeyPressEvent) -> None:
"""Scroll page up (prefer the cursor at the bottom of the page, after scrolling)."""
w = event.app.layout.current_window
b = event.app.current_buffer
if w and w.render_info:
line_index = b.document.cursor_position_row
page = w.render_info.window_height
if (
(screen := get_app().renderer._last_screen)
and (wp := screen.visible_windows_to_write_positions.get(w))
and (bbox := getattr(wp, "bbox", None))
):
page -= bbox.top + bbox.bottom
# Put cursor at the first visible line. (But make sure that the cursor
# moves at least one line up.)
line_index = max(
0,
min(line_index - page, b.document.cursor_position_row - 1),
)
b.cursor_position = b.document.translate_row_col_to_index(line_index, 0)
b.cursor_position += b.document.get_start_of_line_position(
after_whitespace=True
)
# Set the scroll offset. We can safely set it to zero; the Window will
# make sure that it scrolls at least until the cursor becomes visible.
w.vertical_scroll = 0 | Scroll page up (prefer the cursor at the bottom of the page, after scrolling). |
6,887 | from __future__ import annotations
import logging
from typing import TYPE_CHECKING
from prompt_toolkit.filters import (
buffer_has_focus,
)
from prompt_toolkit.key_binding import ConditionalKeyBindings
from euporie.core.commands import add_cmd
from euporie.core.filters import (
micro_mode,
replace_mode,
)
from euporie.core.key_binding.registry import (
load_registered_bindings,
register_bindings,
)
from euporie.core.key_binding.utils import if_no_repeat
def micro_mode() -> bool:
"""When the micro key-bindings are active."""
from euporie.core.current import get_app
return get_app().editing_mode == EditingMode.MICRO # type: ignore
def load_registered_bindings(
*names: str, config: Config | None = None
) -> KeyBindingsBase:
"""Assign key-bindings to commands based on a dictionary."""
kb = KeyBindings()
for name in names:
binding_dict = BINDINGS.get(name, {})
# Augment with bindings from config
if config is not None:
binding_dict.update(config.key_bindings.get(name, {}))
for command, keys in binding_dict.items():
get_cmd(command).bind(kb, keys)
return kb
class Config:
"""A configuration store."""
settings: ClassVar[dict[str, Setting]] = {}
conf_file_name = "config.json"
def __init__(self) -> None:
"""Create a new configuration object instance."""
self.app_name: str = "base"
self.app_cls: type[ConfigurableApp] | None = None
def _save(self, setting: Setting) -> None:
"""Save settings to user's configuration file."""
json_data = self.load_config_file()
json_data.setdefault(self.app_name, {})[setting.name] = setting.value
if self.valid_user:
log.debug("Saving setting `%s`", setting)
with self.config_file_path.open("w") as f:
json.dump(json_data, f, indent=2)
def load(self, cls: type[ConfigurableApp]) -> None:
"""Load the command line, environment, and user configuration."""
from euporie.core.log import setup_logs
self.app_cls = cls
self.app_name = cls.name
log.debug("Loading config for %s", self.app_name)
user_conf_dir = Path(user_config_dir(__app_name__, appauthor=None))
user_conf_dir.mkdir(exist_ok=True, parents=True)
self.config_file_path = (user_conf_dir / self.conf_file_name).with_suffix(
".json"
)
self.valid_user = True
config_maps = {
# Load command line arguments
"command line arguments": self.load_args(),
# Load app specific env vars
"app-specific environment variable": self.load_env(app_name=self.app_name),
# Load global env vars
"global environment variable": self.load_env(),
# Load app specific user config
"app-specific user configuration": self.load_user(app_name=self.app_name),
# Load global user config
"user configuration": self.load_user(),
}
set_values = ChainMap(*config_maps.values())
for name, setting in Config.settings.items():
if setting.name in set_values:
# Set value without triggering hooks
setting._value = set_values[name]
setting.event += self._save
# Set-up logs
setup_logs(self)
# Save a list of unknown configuration options so we can warn about them once
# the logs are configured
for map_name, map_values in config_maps.items():
for option_name in map_values.keys() - Config.settings.keys():
if not isinstance(set_values[option_name], dict):
log.warning(
"Configuration option '%s' not recognised in %s",
option_name,
map_name,
)
def schema(self) -> dict[str, Any]:
"""Return a JSON schema for the config."""
return {
"title": "Euporie Configuration",
"description": "A configuration for euporie",
"type": "object",
"properties": {name: item.schema for name, item in self.settings.items()},
}
def load_parser(self) -> argparse.ArgumentParser:
"""Construct an :py:class:`ArgumentParser`."""
parser = ArgumentParser(
description=self.app_cls.__doc__,
epilog=__copyright__,
allow_abbrev=True,
formatter_class=argparse.MetavarTypeHelpFormatter,
)
# Add options to the relevant subparsers
for setting in self.settings.values():
args, kwargs = setting.parser_args
parser.add_argument(*args, **kwargs)
return parser
def load_args(self) -> dict[str, Any]:
"""Attempt to load configuration settings from commandline flags."""
result = {}
# Parse known arguments
namespace, remainder = self.load_parser().parse_known_intermixed_args()
# Update argv to leave the remaining arguments for subsequent apps
sys.argv[1:] = remainder
# Validate arguments
for name, value in vars(namespace).items():
if value is not None:
# Convert to json and back to attain json types
json_data = json.loads(_json_encoder.encode({name: value}))
try:
fastjsonschema.validate(self.schema, json_data)
except fastjsonschema.JsonSchemaValueException as error:
log.warning("Error in command line parameter `%s`: %s", name, error)
log.warning("%s: %s", name, value)
else:
result[name] = value
return result
def load_env(self, app_name: str = "") -> dict[str, Any]:
"""Attempt to load configuration settings from environment variables."""
result = {}
for name, setting in self.settings.items():
if app_name:
env = f"{__app_name__.upper()}_{self.app_name.upper()}_{setting.name.upper()}"
else:
env = f"{__app_name__.upper()}_{setting.name.upper()}"
if env in os.environ:
value = os.environ.get(env)
parsed_value: Any = value
# Attempt to parse the value as a literal
if value:
try:
parsed_value = literal_eval(value)
except (
ValueError,
TypeError,
SyntaxError,
MemoryError,
RecursionError,
):
pass
# Attempt to cast the value to the desired type
try:
parsed_value = setting.type(value)
except (ValueError, TypeError):
log.warning(
"Environment variable `%s` not understood" " - `%s` expected",
env,
setting.type.__name__,
)
else:
json_data = json.loads(_json_encoder.encode({name: parsed_value}))
try:
fastjsonschema.validate(self.schema, json_data)
except fastjsonschema.JsonSchemaValueException as error:
log.error("Error in environment variable: `%s`\n%s", env, error)
else:
result[name] = parsed_value
return result
def load_config_file(self) -> dict[str, Any]:
"""Attempt to load JSON configuration file."""
results = {}
assert isinstance(self.config_file_path, Path)
if self.valid_user and self.config_file_path.exists():
with self.config_file_path.open() as f:
try:
json_data = json.load(f)
except json.decoder.JSONDecodeError:
log.error(
"Could not parse the configuration file: %s\nIs it valid json?",
self.config_file_path,
)
self.valid_user = False
else:
results.update(json_data)
return results
def load_user(self, app_name: str = "") -> dict[str, Any]:
"""Attempt to load JSON configuration file."""
results = {}
# Load config file
json_data = self.load_config_file()
# Load section for the current app
if app_name:
json_data = json_data.get(self.app_name, {})
# Validate the configuration file
try:
# Validate a copy so the original data is not modified
fastjsonschema.validate(self.schema, dict(json_data))
except fastjsonschema.JsonSchemaValueException as error:
log.warning("Error in config file: `%s`: %s", self.config_file_pathi, error)
self.valid_user = False
else:
results.update(json_data)
return results
def get(self, name: str, default: Any = None) -> Any:
"""Access a configuration value, falling back to the default value if unset.
Args:
name: The name of the attribute to access.
default: The value to return if the name is not found
Returns:
The configuration variable value.
"""
if name in self.settings:
return self.settings[name].value
else:
return default
def get_item(self, name: str) -> Any:
"""Access a configuration item.
Args:
name: The name of the attribute to access.
Returns:
The configuration item.
"""
return self.settings.get(name)
def filter(self, name: str) -> Filter:
"""Return a :py:class:`Filter` for a configuration item."""
return Condition(partial(self.get, name))
def __getattr__(self, name: str) -> Any:
"""Enable access of config elements via dotted attributes.
Args:
name: The name of the attribute to access.
Returns:
The configuration variable value.
"""
return self.get(name)
def __setitem__(self, name: str, value: Any) -> None:
"""Set a configuration attribute.
Args:
name: The name of the attribute to set.
value: The value to give the attribute.
"""
setting = self.settings[name]
setting.value = value
The provided code snippet includes necessary dependencies for implementing the `load_basic_bindings` function. Write a Python function `def load_basic_bindings(config: Config | None = None) -> KeyBindingsBase` to solve the following problem:
Load basic key-bindings for text entry.
Here is the function:
def load_basic_bindings(config: Config | None = None) -> KeyBindingsBase:
"""Load basic key-bindings for text entry."""
return ConditionalKeyBindings(
load_registered_bindings(
"euporie.core.key_binding.bindings.basic.TextEntry", config=config
),
micro_mode,
) | Load basic key-bindings for text entry. |
6,888 | from __future__ import annotations
import logging
from typing import TYPE_CHECKING
from prompt_toolkit.filters import (
buffer_has_focus,
)
from prompt_toolkit.key_binding import ConditionalKeyBindings
from euporie.core.commands import add_cmd
from euporie.core.filters import (
micro_mode,
replace_mode,
)
from euporie.core.key_binding.registry import (
load_registered_bindings,
register_bindings,
)
from euporie.core.key_binding.utils import if_no_repeat
replace_mode = micro_replace_mode | vi_replace_mode
The provided code snippet includes necessary dependencies for implementing the `type_key` function. Write a Python function `def type_key(event: KeyPressEvent) -> None` to solve the following problem:
Enter a key.
Here is the function:
def type_key(event: KeyPressEvent) -> None:
"""Enter a key."""
# Do not insert escape sequences
if not event.data.startswith("\x1b"):
event.current_buffer.insert_text(
event.data * event.arg, overwrite=replace_mode()
) | Enter a key. |
6,889 | from __future__ import annotations
import logging
import re
from functools import partial
from typing import TYPE_CHECKING
from aenum import extend_enum
from prompt_toolkit.buffer import indent, unindent
from prompt_toolkit.document import Document
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.filters import (
buffer_has_focus,
has_selection,
in_paste_mode,
is_multiline,
shift_selection_mode,
)
from prompt_toolkit.key_binding import ConditionalKeyBindings
from prompt_toolkit.key_binding.bindings.named_commands import (
accept_line,
backward_delete_char,
backward_word,
beginning_of_buffer,
delete_char,
end_of_buffer,
forward_word,
get_by_name,
)
from prompt_toolkit.key_binding.bindings.scroll import (
scroll_backward,
scroll_forward,
scroll_half_page_down,
scroll_half_page_up,
scroll_one_line_down,
scroll_one_line_up,
)
from prompt_toolkit.keys import Keys
from prompt_toolkit.selection import SelectionState, SelectionType
from euporie.core.commands import add_cmd, get_cmd
from euporie.core.current import get_app
from euporie.core.filters import (
buffer_is_code,
buffer_is_markdown,
cursor_at_start_of_line,
cursor_in_leading_ws,
has_suggestion,
insert_mode,
is_returnable,
micro_insert_mode,
micro_mode,
micro_recording_macro,
micro_replace_mode,
)
from euporie.core.key_binding.micro_state import MicroInputMode
from euporie.core.key_binding.registry import (
load_registered_bindings,
register_bindings,
)
from euporie.core.key_binding.utils import if_no_repeat
def micro_mode() -> bool:
"""When the micro key-bindings are active."""
from euporie.core.current import get_app
return get_app().editing_mode == EditingMode.MICRO # type: ignore
def load_registered_bindings(
*names: str, config: Config | None = None
) -> KeyBindingsBase:
"""Assign key-bindings to commands based on a dictionary."""
kb = KeyBindings()
for name in names:
binding_dict = BINDINGS.get(name, {})
# Augment with bindings from config
if config is not None:
binding_dict.update(config.key_bindings.get(name, {}))
for command, keys in binding_dict.items():
get_cmd(command).bind(kb, keys)
return kb
class Config:
"""A configuration store."""
settings: ClassVar[dict[str, Setting]] = {}
conf_file_name = "config.json"
def __init__(self) -> None:
"""Create a new configuration object instance."""
self.app_name: str = "base"
self.app_cls: type[ConfigurableApp] | None = None
def _save(self, setting: Setting) -> None:
"""Save settings to user's configuration file."""
json_data = self.load_config_file()
json_data.setdefault(self.app_name, {})[setting.name] = setting.value
if self.valid_user:
log.debug("Saving setting `%s`", setting)
with self.config_file_path.open("w") as f:
json.dump(json_data, f, indent=2)
def load(self, cls: type[ConfigurableApp]) -> None:
"""Load the command line, environment, and user configuration."""
from euporie.core.log import setup_logs
self.app_cls = cls
self.app_name = cls.name
log.debug("Loading config for %s", self.app_name)
user_conf_dir = Path(user_config_dir(__app_name__, appauthor=None))
user_conf_dir.mkdir(exist_ok=True, parents=True)
self.config_file_path = (user_conf_dir / self.conf_file_name).with_suffix(
".json"
)
self.valid_user = True
config_maps = {
# Load command line arguments
"command line arguments": self.load_args(),
# Load app specific env vars
"app-specific environment variable": self.load_env(app_name=self.app_name),
# Load global env vars
"global environment variable": self.load_env(),
# Load app specific user config
"app-specific user configuration": self.load_user(app_name=self.app_name),
# Load global user config
"user configuration": self.load_user(),
}
set_values = ChainMap(*config_maps.values())
for name, setting in Config.settings.items():
if setting.name in set_values:
# Set value without triggering hooks
setting._value = set_values[name]
setting.event += self._save
# Set-up logs
setup_logs(self)
# Save a list of unknown configuration options so we can warn about them once
# the logs are configured
for map_name, map_values in config_maps.items():
for option_name in map_values.keys() - Config.settings.keys():
if not isinstance(set_values[option_name], dict):
log.warning(
"Configuration option '%s' not recognised in %s",
option_name,
map_name,
)
def schema(self) -> dict[str, Any]:
"""Return a JSON schema for the config."""
return {
"title": "Euporie Configuration",
"description": "A configuration for euporie",
"type": "object",
"properties": {name: item.schema for name, item in self.settings.items()},
}
def load_parser(self) -> argparse.ArgumentParser:
"""Construct an :py:class:`ArgumentParser`."""
parser = ArgumentParser(
description=self.app_cls.__doc__,
epilog=__copyright__,
allow_abbrev=True,
formatter_class=argparse.MetavarTypeHelpFormatter,
)
# Add options to the relevant subparsers
for setting in self.settings.values():
args, kwargs = setting.parser_args
parser.add_argument(*args, **kwargs)
return parser
def load_args(self) -> dict[str, Any]:
"""Attempt to load configuration settings from commandline flags."""
result = {}
# Parse known arguments
namespace, remainder = self.load_parser().parse_known_intermixed_args()
# Update argv to leave the remaining arguments for subsequent apps
sys.argv[1:] = remainder
# Validate arguments
for name, value in vars(namespace).items():
if value is not None:
# Convert to json and back to attain json types
json_data = json.loads(_json_encoder.encode({name: value}))
try:
fastjsonschema.validate(self.schema, json_data)
except fastjsonschema.JsonSchemaValueException as error:
log.warning("Error in command line parameter `%s`: %s", name, error)
log.warning("%s: %s", name, value)
else:
result[name] = value
return result
def load_env(self, app_name: str = "") -> dict[str, Any]:
"""Attempt to load configuration settings from environment variables."""
result = {}
for name, setting in self.settings.items():
if app_name:
env = f"{__app_name__.upper()}_{self.app_name.upper()}_{setting.name.upper()}"
else:
env = f"{__app_name__.upper()}_{setting.name.upper()}"
if env in os.environ:
value = os.environ.get(env)
parsed_value: Any = value
# Attempt to parse the value as a literal
if value:
try:
parsed_value = literal_eval(value)
except (
ValueError,
TypeError,
SyntaxError,
MemoryError,
RecursionError,
):
pass
# Attempt to cast the value to the desired type
try:
parsed_value = setting.type(value)
except (ValueError, TypeError):
log.warning(
"Environment variable `%s` not understood" " - `%s` expected",
env,
setting.type.__name__,
)
else:
json_data = json.loads(_json_encoder.encode({name: parsed_value}))
try:
fastjsonschema.validate(self.schema, json_data)
except fastjsonschema.JsonSchemaValueException as error:
log.error("Error in environment variable: `%s`\n%s", env, error)
else:
result[name] = parsed_value
return result
def load_config_file(self) -> dict[str, Any]:
"""Attempt to load JSON configuration file."""
results = {}
assert isinstance(self.config_file_path, Path)
if self.valid_user and self.config_file_path.exists():
with self.config_file_path.open() as f:
try:
json_data = json.load(f)
except json.decoder.JSONDecodeError:
log.error(
"Could not parse the configuration file: %s\nIs it valid json?",
self.config_file_path,
)
self.valid_user = False
else:
results.update(json_data)
return results
def load_user(self, app_name: str = "") -> dict[str, Any]:
"""Attempt to load JSON configuration file."""
results = {}
# Load config file
json_data = self.load_config_file()
# Load section for the current app
if app_name:
json_data = json_data.get(self.app_name, {})
# Validate the configuration file
try:
# Validate a copy so the original data is not modified
fastjsonschema.validate(self.schema, dict(json_data))
except fastjsonschema.JsonSchemaValueException as error:
log.warning("Error in config file: `%s`: %s", self.config_file_pathi, error)
self.valid_user = False
else:
results.update(json_data)
return results
def get(self, name: str, default: Any = None) -> Any:
"""Access a configuration value, falling back to the default value if unset.
Args:
name: The name of the attribute to access.
default: The value to return if the name is not found
Returns:
The configuration variable value.
"""
if name in self.settings:
return self.settings[name].value
else:
return default
def get_item(self, name: str) -> Any:
"""Access a configuration item.
Args:
name: The name of the attribute to access.
Returns:
The configuration item.
"""
return self.settings.get(name)
def filter(self, name: str) -> Filter:
"""Return a :py:class:`Filter` for a configuration item."""
return Condition(partial(self.get, name))
def __getattr__(self, name: str) -> Any:
"""Enable access of config elements via dotted attributes.
Args:
name: The name of the attribute to access.
Returns:
The configuration variable value.
"""
return self.get(name)
def __setitem__(self, name: str, value: Any) -> None:
"""Set a configuration attribute.
Args:
name: The name of the attribute to set.
value: The value to give the attribute.
"""
setting = self.settings[name]
setting.value = value
The provided code snippet includes necessary dependencies for implementing the `load_micro_bindings` function. Write a Python function `def load_micro_bindings(config: Config | None = None) -> KeyBindingsBase` to solve the following problem:
Load editor key-bindings in the style of the ``micro`` text editor.
Here is the function:
def load_micro_bindings(config: Config | None = None) -> KeyBindingsBase:
"""Load editor key-bindings in the style of the ``micro`` text editor."""
return ConditionalKeyBindings(
load_registered_bindings(
"euporie.core.key_binding.bindings.micro.EditMode", config=config
),
micro_mode,
) | Load editor key-bindings in the style of the ``micro`` text editor. |
6,890 | from __future__ import annotations
import logging
import re
from functools import partial
from typing import TYPE_CHECKING
from aenum import extend_enum
from prompt_toolkit.buffer import indent, unindent
from prompt_toolkit.document import Document
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.filters import (
buffer_has_focus,
has_selection,
in_paste_mode,
is_multiline,
shift_selection_mode,
)
from prompt_toolkit.key_binding import ConditionalKeyBindings
from prompt_toolkit.key_binding.bindings.named_commands import (
accept_line,
backward_delete_char,
backward_word,
beginning_of_buffer,
delete_char,
end_of_buffer,
forward_word,
get_by_name,
)
from prompt_toolkit.key_binding.bindings.scroll import (
scroll_backward,
scroll_forward,
scroll_half_page_down,
scroll_half_page_up,
scroll_one_line_down,
scroll_one_line_up,
)
from prompt_toolkit.keys import Keys
from prompt_toolkit.selection import SelectionState, SelectionType
from euporie.core.commands import add_cmd, get_cmd
from euporie.core.current import get_app
from euporie.core.filters import (
buffer_is_code,
buffer_is_markdown,
cursor_at_start_of_line,
cursor_in_leading_ws,
has_suggestion,
insert_mode,
is_returnable,
micro_insert_mode,
micro_mode,
micro_recording_macro,
micro_replace_mode,
)
from euporie.core.key_binding.micro_state import MicroInputMode
from euporie.core.key_binding.registry import (
load_registered_bindings,
register_bindings,
)
from euporie.core.key_binding.utils import if_no_repeat
def get_app() -> BaseApp:
"""Get the current active (running) Application."""
from euporie.core.app import BaseApp
session = _current_app_session.get()
if isinstance(session.app, BaseApp):
return session.app
# Use a baseapp as our "DummyApplication"
return BaseApp()
def micro_replace_mode() -> bool:
"""Determine if the editor is in overwrite mode."""
from euporie.core.current import get_app
app = get_app()
return app.micro_state.input_mode == MicroInputMode.REPLACE
def micro_insert_mode() -> bool:
"""Determine if the editor is in insert mode."""
from euporie.core.current import get_app
app = get_app()
return app.micro_state.input_mode == MicroInputMode.INSERT
class MicroInputMode(str, Enum):
"""Enum to define edit mode state types."""
value: str
INSERT = "insert"
REPLACE = "replace"
The provided code snippet includes necessary dependencies for implementing the `toggle_overwrite_mode` function. Write a Python function `def toggle_overwrite_mode() -> None` to solve the following problem:
Toggle overwrite when using micro editing mode.
Here is the function:
def toggle_overwrite_mode() -> None:
"""Toggle overwrite when using micro editing mode."""
if micro_replace_mode():
get_app().micro_state.input_mode = MicroInputMode.INSERT
elif micro_insert_mode():
get_app().micro_state.input_mode = MicroInputMode.REPLACE | Toggle overwrite when using micro editing mode. |
6,891 | from __future__ import annotations
import logging
import re
from functools import partial
from typing import TYPE_CHECKING
from aenum import extend_enum
from prompt_toolkit.buffer import indent, unindent
from prompt_toolkit.document import Document
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.filters import (
buffer_has_focus,
has_selection,
in_paste_mode,
is_multiline,
shift_selection_mode,
)
from prompt_toolkit.key_binding import ConditionalKeyBindings
from prompt_toolkit.key_binding.bindings.named_commands import (
accept_line,
backward_delete_char,
backward_word,
beginning_of_buffer,
delete_char,
end_of_buffer,
forward_word,
get_by_name,
)
from prompt_toolkit.key_binding.bindings.scroll import (
scroll_backward,
scroll_forward,
scroll_half_page_down,
scroll_half_page_up,
scroll_one_line_down,
scroll_one_line_up,
)
from prompt_toolkit.keys import Keys
from prompt_toolkit.selection import SelectionState, SelectionType
from euporie.core.commands import add_cmd, get_cmd
from euporie.core.current import get_app
from euporie.core.filters import (
buffer_is_code,
buffer_is_markdown,
cursor_at_start_of_line,
cursor_in_leading_ws,
has_suggestion,
insert_mode,
is_returnable,
micro_insert_mode,
micro_mode,
micro_recording_macro,
micro_replace_mode,
)
from euporie.core.key_binding.micro_state import MicroInputMode
from euporie.core.key_binding.registry import (
load_registered_bindings,
register_bindings,
)
from euporie.core.key_binding.utils import if_no_repeat
def get_app() -> BaseApp:
"""Get the current active (running) Application."""
from euporie.core.app import BaseApp
session = _current_app_session.get()
if isinstance(session.app, BaseApp):
return session.app
# Use a baseapp as our "DummyApplication"
return BaseApp()
The provided code snippet includes necessary dependencies for implementing the `start_macro` function. Write a Python function `def start_macro() -> None` to solve the following problem:
Start recording a macro.
Here is the function:
def start_macro() -> None:
"""Start recording a macro."""
get_app().micro_state.start_macro() | Start recording a macro. |
6,892 | from __future__ import annotations
import logging
import re
from functools import partial
from typing import TYPE_CHECKING
from aenum import extend_enum
from prompt_toolkit.buffer import indent, unindent
from prompt_toolkit.document import Document
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.filters import (
buffer_has_focus,
has_selection,
in_paste_mode,
is_multiline,
shift_selection_mode,
)
from prompt_toolkit.key_binding import ConditionalKeyBindings
from prompt_toolkit.key_binding.bindings.named_commands import (
accept_line,
backward_delete_char,
backward_word,
beginning_of_buffer,
delete_char,
end_of_buffer,
forward_word,
get_by_name,
)
from prompt_toolkit.key_binding.bindings.scroll import (
scroll_backward,
scroll_forward,
scroll_half_page_down,
scroll_half_page_up,
scroll_one_line_down,
scroll_one_line_up,
)
from prompt_toolkit.keys import Keys
from prompt_toolkit.selection import SelectionState, SelectionType
from euporie.core.commands import add_cmd, get_cmd
from euporie.core.current import get_app
from euporie.core.filters import (
buffer_is_code,
buffer_is_markdown,
cursor_at_start_of_line,
cursor_in_leading_ws,
has_suggestion,
insert_mode,
is_returnable,
micro_insert_mode,
micro_mode,
micro_recording_macro,
micro_replace_mode,
)
from euporie.core.key_binding.micro_state import MicroInputMode
from euporie.core.key_binding.registry import (
load_registered_bindings,
register_bindings,
)
from euporie.core.key_binding.utils import if_no_repeat
def get_app() -> BaseApp:
"""Get the current active (running) Application."""
from euporie.core.app import BaseApp
session = _current_app_session.get()
if isinstance(session.app, BaseApp):
return session.app
# Use a baseapp as our "DummyApplication"
return BaseApp()
The provided code snippet includes necessary dependencies for implementing the `end_macro` function. Write a Python function `def end_macro() -> None` to solve the following problem:
Stop recording a macro.
Here is the function:
def end_macro() -> None:
"""Stop recording a macro."""
get_app().micro_state.end_macro() | Stop recording a macro. |
6,893 | from __future__ import annotations
import logging
import re
from functools import partial
from typing import TYPE_CHECKING
from aenum import extend_enum
from prompt_toolkit.buffer import indent, unindent
from prompt_toolkit.document import Document
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.filters import (
buffer_has_focus,
has_selection,
in_paste_mode,
is_multiline,
shift_selection_mode,
)
from prompt_toolkit.key_binding import ConditionalKeyBindings
from prompt_toolkit.key_binding.bindings.named_commands import (
accept_line,
backward_delete_char,
backward_word,
beginning_of_buffer,
delete_char,
end_of_buffer,
forward_word,
get_by_name,
)
from prompt_toolkit.key_binding.bindings.scroll import (
scroll_backward,
scroll_forward,
scroll_half_page_down,
scroll_half_page_up,
scroll_one_line_down,
scroll_one_line_up,
)
from prompt_toolkit.keys import Keys
from prompt_toolkit.selection import SelectionState, SelectionType
from euporie.core.commands import add_cmd, get_cmd
from euporie.core.current import get_app
from euporie.core.filters import (
buffer_is_code,
buffer_is_markdown,
cursor_at_start_of_line,
cursor_in_leading_ws,
has_suggestion,
insert_mode,
is_returnable,
micro_insert_mode,
micro_mode,
micro_recording_macro,
micro_replace_mode,
)
from euporie.core.key_binding.micro_state import MicroInputMode
from euporie.core.key_binding.registry import (
load_registered_bindings,
register_bindings,
)
from euporie.core.key_binding.utils import if_no_repeat
def get_app() -> BaseApp:
"""Get the current active (running) Application."""
from euporie.core.app import BaseApp
session = _current_app_session.get()
if isinstance(session.app, BaseApp):
return session.app
# Use a baseapp as our "DummyApplication"
return BaseApp()
The provided code snippet includes necessary dependencies for implementing the `run_macro` function. Write a Python function `def run_macro() -> None` to solve the following problem:
Re-execute the last keyboard macro defined.
Here is the function:
def run_macro() -> None:
"""Re-execute the last keyboard macro defined."""
# Insert the macro.
app = get_app()
macro = app.micro_state.macro
if macro:
app.key_processor.feed_multiple(macro, first=True) | Re-execute the last keyboard macro defined. |
6,894 | from __future__ import annotations
import logging
import re
from functools import partial
from typing import TYPE_CHECKING
from aenum import extend_enum
from prompt_toolkit.buffer import indent, unindent
from prompt_toolkit.document import Document
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.filters import (
buffer_has_focus,
has_selection,
in_paste_mode,
is_multiline,
shift_selection_mode,
)
from prompt_toolkit.key_binding import ConditionalKeyBindings
from prompt_toolkit.key_binding.bindings.named_commands import (
accept_line,
backward_delete_char,
backward_word,
beginning_of_buffer,
delete_char,
end_of_buffer,
forward_word,
get_by_name,
)
from prompt_toolkit.key_binding.bindings.scroll import (
scroll_backward,
scroll_forward,
scroll_half_page_down,
scroll_half_page_up,
scroll_one_line_down,
scroll_one_line_up,
)
from prompt_toolkit.keys import Keys
from prompt_toolkit.selection import SelectionState, SelectionType
from euporie.core.commands import add_cmd, get_cmd
from euporie.core.current import get_app
from euporie.core.filters import (
buffer_is_code,
buffer_is_markdown,
cursor_at_start_of_line,
cursor_in_leading_ws,
has_suggestion,
insert_mode,
is_returnable,
micro_insert_mode,
micro_mode,
micro_recording_macro,
micro_replace_mode,
)
from euporie.core.key_binding.micro_state import MicroInputMode
from euporie.core.key_binding.registry import (
load_registered_bindings,
register_bindings,
)
from euporie.core.key_binding.utils import if_no_repeat
The provided code snippet includes necessary dependencies for implementing the `backward_kill_word` function. Write a Python function `def backward_kill_word(event: KeyPressEvent) -> None` to solve the following problem:
Delete the word behind the cursor, using whitespace as a word boundary.
Here is the function:
def backward_kill_word(event: KeyPressEvent) -> None:
"""Delete the word behind the cursor, using whitespace as a word boundary."""
buff = event.current_buffer
pos = buff.document.find_start_of_previous_word()
# Delete until the start of the document if nothing is found
if pos is None:
pos = -buff.cursor_position
# Delete the word
if pos:
buff.delete_before_cursor(count=-pos)
else:
# Nothing to delete. Bell.
event.app.output.bell() | Delete the word behind the cursor, using whitespace as a word boundary. |
6,895 | from __future__ import annotations
import logging
import re
from functools import partial
from typing import TYPE_CHECKING
from aenum import extend_enum
from prompt_toolkit.buffer import indent, unindent
from prompt_toolkit.document import Document
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.filters import (
buffer_has_focus,
has_selection,
in_paste_mode,
is_multiline,
shift_selection_mode,
)
from prompt_toolkit.key_binding import ConditionalKeyBindings
from prompt_toolkit.key_binding.bindings.named_commands import (
accept_line,
backward_delete_char,
backward_word,
beginning_of_buffer,
delete_char,
end_of_buffer,
forward_word,
get_by_name,
)
from prompt_toolkit.key_binding.bindings.scroll import (
scroll_backward,
scroll_forward,
scroll_half_page_down,
scroll_half_page_up,
scroll_one_line_down,
scroll_one_line_up,
)
from prompt_toolkit.keys import Keys
from prompt_toolkit.selection import SelectionState, SelectionType
from euporie.core.commands import add_cmd, get_cmd
from euporie.core.current import get_app
from euporie.core.filters import (
buffer_is_code,
buffer_is_markdown,
cursor_at_start_of_line,
cursor_in_leading_ws,
has_suggestion,
insert_mode,
is_returnable,
micro_insert_mode,
micro_mode,
micro_recording_macro,
micro_replace_mode,
)
from euporie.core.key_binding.micro_state import MicroInputMode
from euporie.core.key_binding.registry import (
load_registered_bindings,
register_bindings,
)
from euporie.core.key_binding.utils import if_no_repeat
def get_app() -> BaseApp:
"""Get the current active (running) Application."""
from euporie.core.app import BaseApp
session = _current_app_session.get()
if isinstance(session.app, BaseApp):
return session.app
# Use a baseapp as our "DummyApplication"
return BaseApp()
The provided code snippet includes necessary dependencies for implementing the `move_cursor_left` function. Write a Python function `def move_cursor_left() -> None` to solve the following problem:
Move back a character, or up a line.
Here is the function:
def move_cursor_left() -> None:
"""Move back a character, or up a line."""
get_app().current_buffer.cursor_position -= 1 | Move back a character, or up a line. |
6,896 | from __future__ import annotations
import logging
import re
from functools import partial
from typing import TYPE_CHECKING
from aenum import extend_enum
from prompt_toolkit.buffer import indent, unindent
from prompt_toolkit.document import Document
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.filters import (
buffer_has_focus,
has_selection,
in_paste_mode,
is_multiline,
shift_selection_mode,
)
from prompt_toolkit.key_binding import ConditionalKeyBindings
from prompt_toolkit.key_binding.bindings.named_commands import (
accept_line,
backward_delete_char,
backward_word,
beginning_of_buffer,
delete_char,
end_of_buffer,
forward_word,
get_by_name,
)
from prompt_toolkit.key_binding.bindings.scroll import (
scroll_backward,
scroll_forward,
scroll_half_page_down,
scroll_half_page_up,
scroll_one_line_down,
scroll_one_line_up,
)
from prompt_toolkit.keys import Keys
from prompt_toolkit.selection import SelectionState, SelectionType
from euporie.core.commands import add_cmd, get_cmd
from euporie.core.current import get_app
from euporie.core.filters import (
buffer_is_code,
buffer_is_markdown,
cursor_at_start_of_line,
cursor_in_leading_ws,
has_suggestion,
insert_mode,
is_returnable,
micro_insert_mode,
micro_mode,
micro_recording_macro,
micro_replace_mode,
)
from euporie.core.key_binding.micro_state import MicroInputMode
from euporie.core.key_binding.registry import (
load_registered_bindings,
register_bindings,
)
from euporie.core.key_binding.utils import if_no_repeat
def get_app() -> BaseApp:
"""Get the current active (running) Application."""
from euporie.core.app import BaseApp
session = _current_app_session.get()
if isinstance(session.app, BaseApp):
return session.app
# Use a baseapp as our "DummyApplication"
return BaseApp()
The provided code snippet includes necessary dependencies for implementing the `move_cursor_right` function. Write a Python function `def move_cursor_right() -> None` to solve the following problem:
Move forward a character, or down a line.
Here is the function:
def move_cursor_right() -> None:
"""Move forward a character, or down a line."""
get_app().current_buffer.cursor_position += 1 | Move forward a character, or down a line. |
6,897 | from __future__ import annotations
import logging
import re
from functools import partial
from typing import TYPE_CHECKING
from aenum import extend_enum
from prompt_toolkit.buffer import indent, unindent
from prompt_toolkit.document import Document
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.filters import (
buffer_has_focus,
has_selection,
in_paste_mode,
is_multiline,
shift_selection_mode,
)
from prompt_toolkit.key_binding import ConditionalKeyBindings
from prompt_toolkit.key_binding.bindings.named_commands import (
accept_line,
backward_delete_char,
backward_word,
beginning_of_buffer,
delete_char,
end_of_buffer,
forward_word,
get_by_name,
)
from prompt_toolkit.key_binding.bindings.scroll import (
scroll_backward,
scroll_forward,
scroll_half_page_down,
scroll_half_page_up,
scroll_one_line_down,
scroll_one_line_up,
)
from prompt_toolkit.keys import Keys
from prompt_toolkit.selection import SelectionState, SelectionType
from euporie.core.commands import add_cmd, get_cmd
from euporie.core.current import get_app
from euporie.core.filters import (
buffer_is_code,
buffer_is_markdown,
cursor_at_start_of_line,
cursor_in_leading_ws,
has_suggestion,
insert_mode,
is_returnable,
micro_insert_mode,
micro_mode,
micro_recording_macro,
micro_replace_mode,
)
from euporie.core.key_binding.micro_state import MicroInputMode
from euporie.core.key_binding.registry import (
load_registered_bindings,
register_bindings,
)
from euporie.core.key_binding.utils import if_no_repeat
def get_app() -> BaseApp:
"""Get the current active (running) Application."""
from euporie.core.app import BaseApp
session = _current_app_session.get()
if isinstance(session.app, BaseApp):
return session.app
# Use a baseapp as our "DummyApplication"
return BaseApp()
def cursor_in_leading_ws() -> bool:
"""Determine if the cursor of the current buffer is in leading whitespace."""
from prompt_toolkit.application.current import get_app
before = get_app().current_buffer.document.current_line_before_cursor
return (not before) or before.isspace()
The provided code snippet includes necessary dependencies for implementing the `go_to_start_of_line` function. Write a Python function `def go_to_start_of_line() -> None` to solve the following problem:
Move the cursor to the start of the line.
Here is the function:
def go_to_start_of_line() -> None:
"""Move the cursor to the start of the line."""
buff = get_app().current_buffer
buff.cursor_position += buff.document.get_start_of_line_position(
after_whitespace=not cursor_in_leading_ws()
or buff.document.cursor_position_col == 0
) | Move the cursor to the start of the line. |
6,898 | from __future__ import annotations
import logging
import re
from functools import partial
from typing import TYPE_CHECKING
from aenum import extend_enum
from prompt_toolkit.buffer import indent, unindent
from prompt_toolkit.document import Document
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.filters import (
buffer_has_focus,
has_selection,
in_paste_mode,
is_multiline,
shift_selection_mode,
)
from prompt_toolkit.key_binding import ConditionalKeyBindings
from prompt_toolkit.key_binding.bindings.named_commands import (
accept_line,
backward_delete_char,
backward_word,
beginning_of_buffer,
delete_char,
end_of_buffer,
forward_word,
get_by_name,
)
from prompt_toolkit.key_binding.bindings.scroll import (
scroll_backward,
scroll_forward,
scroll_half_page_down,
scroll_half_page_up,
scroll_one_line_down,
scroll_one_line_up,
)
from prompt_toolkit.keys import Keys
from prompt_toolkit.selection import SelectionState, SelectionType
from euporie.core.commands import add_cmd, get_cmd
from euporie.core.current import get_app
from euporie.core.filters import (
buffer_is_code,
buffer_is_markdown,
cursor_at_start_of_line,
cursor_in_leading_ws,
has_suggestion,
insert_mode,
is_returnable,
micro_insert_mode,
micro_mode,
micro_recording_macro,
micro_replace_mode,
)
from euporie.core.key_binding.micro_state import MicroInputMode
from euporie.core.key_binding.registry import (
load_registered_bindings,
register_bindings,
)
from euporie.core.key_binding.utils import if_no_repeat
def get_app() -> BaseApp:
"""Get the current active (running) Application."""
from euporie.core.app import BaseApp
session = _current_app_session.get()
if isinstance(session.app, BaseApp):
return session.app
# Use a baseapp as our "DummyApplication"
return BaseApp()
The provided code snippet includes necessary dependencies for implementing the `go_to_end_of_line` function. Write a Python function `def go_to_end_of_line() -> None` to solve the following problem:
Move the cursor to the end of the line.
Here is the function:
def go_to_end_of_line() -> None:
"""Move the cursor to the end of the line."""
buff = get_app().current_buffer
buff.cursor_position += buff.document.get_end_of_line_position() | Move the cursor to the end of the line. |
6,899 | from __future__ import annotations
import logging
import re
from functools import partial
from typing import TYPE_CHECKING
from aenum import extend_enum
from prompt_toolkit.buffer import indent, unindent
from prompt_toolkit.document import Document
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.filters import (
buffer_has_focus,
has_selection,
in_paste_mode,
is_multiline,
shift_selection_mode,
)
from prompt_toolkit.key_binding import ConditionalKeyBindings
from prompt_toolkit.key_binding.bindings.named_commands import (
accept_line,
backward_delete_char,
backward_word,
beginning_of_buffer,
delete_char,
end_of_buffer,
forward_word,
get_by_name,
)
from prompt_toolkit.key_binding.bindings.scroll import (
scroll_backward,
scroll_forward,
scroll_half_page_down,
scroll_half_page_up,
scroll_one_line_down,
scroll_one_line_up,
)
from prompt_toolkit.keys import Keys
from prompt_toolkit.selection import SelectionState, SelectionType
from euporie.core.commands import add_cmd, get_cmd
from euporie.core.current import get_app
from euporie.core.filters import (
buffer_is_code,
buffer_is_markdown,
cursor_at_start_of_line,
cursor_in_leading_ws,
has_suggestion,
insert_mode,
is_returnable,
micro_insert_mode,
micro_mode,
micro_recording_macro,
micro_replace_mode,
)
from euporie.core.key_binding.micro_state import MicroInputMode
from euporie.core.key_binding.registry import (
load_registered_bindings,
register_bindings,
)
from euporie.core.key_binding.utils import if_no_repeat
def get_app() -> BaseApp:
"""Get the current active (running) Application."""
from euporie.core.app import BaseApp
session = _current_app_session.get()
if isinstance(session.app, BaseApp):
return session.app
# Use a baseapp as our "DummyApplication"
return BaseApp()
The provided code snippet includes necessary dependencies for implementing the `go_to_start_of_paragraph` function. Write a Python function `def go_to_start_of_paragraph() -> None` to solve the following problem:
Move the cursor to the start of the current paragraph.
Here is the function:
def go_to_start_of_paragraph() -> None:
"""Move the cursor to the start of the current paragraph."""
buf = get_app().current_buffer
buf.cursor_position += buf.document.start_of_paragraph() | Move the cursor to the start of the current paragraph. |
6,900 | from __future__ import annotations
import logging
import re
from functools import partial
from typing import TYPE_CHECKING
from aenum import extend_enum
from prompt_toolkit.buffer import indent, unindent
from prompt_toolkit.document import Document
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.filters import (
buffer_has_focus,
has_selection,
in_paste_mode,
is_multiline,
shift_selection_mode,
)
from prompt_toolkit.key_binding import ConditionalKeyBindings
from prompt_toolkit.key_binding.bindings.named_commands import (
accept_line,
backward_delete_char,
backward_word,
beginning_of_buffer,
delete_char,
end_of_buffer,
forward_word,
get_by_name,
)
from prompt_toolkit.key_binding.bindings.scroll import (
scroll_backward,
scroll_forward,
scroll_half_page_down,
scroll_half_page_up,
scroll_one_line_down,
scroll_one_line_up,
)
from prompt_toolkit.keys import Keys
from prompt_toolkit.selection import SelectionState, SelectionType
from euporie.core.commands import add_cmd, get_cmd
from euporie.core.current import get_app
from euporie.core.filters import (
buffer_is_code,
buffer_is_markdown,
cursor_at_start_of_line,
cursor_in_leading_ws,
has_suggestion,
insert_mode,
is_returnable,
micro_insert_mode,
micro_mode,
micro_recording_macro,
micro_replace_mode,
)
from euporie.core.key_binding.micro_state import MicroInputMode
from euporie.core.key_binding.registry import (
load_registered_bindings,
register_bindings,
)
from euporie.core.key_binding.utils import if_no_repeat
def get_app() -> BaseApp:
"""Get the current active (running) Application."""
from euporie.core.app import BaseApp
session = _current_app_session.get()
if isinstance(session.app, BaseApp):
return session.app
# Use a baseapp as our "DummyApplication"
return BaseApp()
The provided code snippet includes necessary dependencies for implementing the `go_to_end_of_paragraph` function. Write a Python function `def go_to_end_of_paragraph() -> None` to solve the following problem:
Move the cursor to the end of the current paragraph.
Here is the function:
def go_to_end_of_paragraph() -> None:
"""Move the cursor to the end of the current paragraph."""
buffer = get_app().current_buffer
buffer.cursor_position += buffer.document.end_of_paragraph() | Move the cursor to the end of the current paragraph. |
6,901 | from __future__ import annotations
import logging
import re
from functools import partial
from typing import TYPE_CHECKING
from aenum import extend_enum
from prompt_toolkit.buffer import indent, unindent
from prompt_toolkit.document import Document
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.filters import (
buffer_has_focus,
has_selection,
in_paste_mode,
is_multiline,
shift_selection_mode,
)
from prompt_toolkit.key_binding import ConditionalKeyBindings
from prompt_toolkit.key_binding.bindings.named_commands import (
accept_line,
backward_delete_char,
backward_word,
beginning_of_buffer,
delete_char,
end_of_buffer,
forward_word,
get_by_name,
)
from prompt_toolkit.key_binding.bindings.scroll import (
scroll_backward,
scroll_forward,
scroll_half_page_down,
scroll_half_page_up,
scroll_one_line_down,
scroll_one_line_up,
)
from prompt_toolkit.keys import Keys
from prompt_toolkit.selection import SelectionState, SelectionType
from euporie.core.commands import add_cmd, get_cmd
from euporie.core.current import get_app
from euporie.core.filters import (
buffer_is_code,
buffer_is_markdown,
cursor_at_start_of_line,
cursor_in_leading_ws,
has_suggestion,
insert_mode,
is_returnable,
micro_insert_mode,
micro_mode,
micro_recording_macro,
micro_replace_mode,
)
from euporie.core.key_binding.micro_state import MicroInputMode
from euporie.core.key_binding.registry import (
load_registered_bindings,
register_bindings,
)
from euporie.core.key_binding.utils import if_no_repeat
def get_app() -> BaseApp:
"""Get the current active (running) Application."""
from euporie.core.app import BaseApp
session = _current_app_session.get()
if isinstance(session.app, BaseApp):
return session.app
# Use a baseapp as our "DummyApplication"
return BaseApp()
The provided code snippet includes necessary dependencies for implementing the `toggle_comment` function. Write a Python function `def toggle_comment() -> None` to solve the following problem:
Comment or uncomments the current or selected lines.
Here is the function:
def toggle_comment() -> None:
"""Comment or uncomments the current or selected lines."""
comment = "# "
buffer = get_app().current_buffer
document = buffer.document
selection_state = buffer.selection_state
lines = buffer.text.splitlines(keepends=False)
start, end = (
document.translate_index_to_position(x)[0] for x in document.selection_range()
)
cursor_in_first_line = document.cursor_position_row == start
# Only remove comments if all lines in the selection have a comment
uncommenting = all(
line.lstrip().startswith(comment.rstrip()) for line in lines[start : end + 1]
)
if uncommenting:
for i in range(start, end + 1):
if not lines:
lines = [""]
# Replace the first instance of the comment in each line
lines[i] = lines[i].replace(comment, "", 1)
if len(lines[i]) < len(comment):
# The line might be blank and have trailing whitespace removed
lines[i] = lines[i].replace(comment.rstrip(), "", 1)
# Find cursor and selection column positions
cur_col = document.translate_index_to_position(buffer.cursor_position)[1]
if selection_state is not None:
sel_col = document.translate_index_to_position(
selection_state.original_cursor_position
)[1]
# Move cursor & adjust selection
if cursor_in_first_line:
bcp = buffer.cursor_position - min(len(comment), cur_col)
if selection_state is not None:
selection_state.original_cursor_position -= len(comment) * (
end - start
) + min(len(comment), sel_col)
else:
if selection_state is not None:
selection_state.original_cursor_position -= min(len(comment), sel_col)
bcp = buffer.cursor_position - (
len(comment) * (end - start) + min(len(comment), cur_col)
)
else:
# Find the minimum leading whitespace in the selected lines
whitespace = min(
len(line) - len(line.lstrip()) for line in lines[start : end + 1]
)
for i in range(start, end + 1):
# Add a comment after the minimum leading whitespace to each line
line = lines[i]
lines[i] = line[:whitespace] + comment + line[whitespace:]
# Move cursor & adjust selection
if cursor_in_first_line:
bcp = buffer.cursor_position + len(comment)
if selection_state is not None:
selection_state.original_cursor_position += len(comment) * (
end - start + 1
)
else:
if selection_state is not None:
selection_state.original_cursor_position += len(comment)
bcp = buffer.cursor_position + len(comment) * (end - start + 1)
# Set the buffer text, curor position and selection state
buffer.document = Document("\n".join(lines), bcp)
buffer.selection_state = selection_state | Comment or uncomments the current or selected lines. |
6,902 | from __future__ import annotations
import logging
import re
from functools import partial
from typing import TYPE_CHECKING
from aenum import extend_enum
from prompt_toolkit.buffer import indent, unindent
from prompt_toolkit.document import Document
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.filters import (
buffer_has_focus,
has_selection,
in_paste_mode,
is_multiline,
shift_selection_mode,
)
from prompt_toolkit.key_binding import ConditionalKeyBindings
from prompt_toolkit.key_binding.bindings.named_commands import (
accept_line,
backward_delete_char,
backward_word,
beginning_of_buffer,
delete_char,
end_of_buffer,
forward_word,
get_by_name,
)
from prompt_toolkit.key_binding.bindings.scroll import (
scroll_backward,
scroll_forward,
scroll_half_page_down,
scroll_half_page_up,
scroll_one_line_down,
scroll_one_line_up,
)
from prompt_toolkit.keys import Keys
from prompt_toolkit.selection import SelectionState, SelectionType
from euporie.core.commands import add_cmd, get_cmd
from euporie.core.current import get_app
from euporie.core.filters import (
buffer_is_code,
buffer_is_markdown,
cursor_at_start_of_line,
cursor_in_leading_ws,
has_suggestion,
insert_mode,
is_returnable,
micro_insert_mode,
micro_mode,
micro_recording_macro,
micro_replace_mode,
)
from euporie.core.key_binding.micro_state import MicroInputMode
from euporie.core.key_binding.registry import (
load_registered_bindings,
register_bindings,
)
from euporie.core.key_binding.utils import if_no_repeat
def get_app() -> BaseApp:
"""Get the current active (running) Application."""
from euporie.core.app import BaseApp
session = _current_app_session.get()
if isinstance(session.app, BaseApp):
return session.app
# Use a baseapp as our "DummyApplication"
return BaseApp()
The provided code snippet includes necessary dependencies for implementing the `wrap_selection_cmd` function. Write a Python function `def wrap_selection_cmd(left: str, right: str) -> None` to solve the following problem:
Add strings to either end of the current selection.
Here is the function:
def wrap_selection_cmd(left: str, right: str) -> None:
"""Add strings to either end of the current selection."""
buffer = get_app().current_buffer
selection_state = buffer.selection_state
for start, end in buffer.document.selection_ranges():
buffer.transform_region(start, end, lambda s: f"{left}{s}{right}")
# keep the selection of the inner expression
buffer.cursor_position += len(left)
if selection_state is not None:
selection_state.original_cursor_position += len(left)
buffer.selection_state = selection_state | Add strings to either end of the current selection. |
6,903 | from __future__ import annotations
import logging
import re
from functools import partial
from typing import TYPE_CHECKING
from aenum import extend_enum
from prompt_toolkit.buffer import indent, unindent
from prompt_toolkit.document import Document
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.filters import (
buffer_has_focus,
has_selection,
in_paste_mode,
is_multiline,
shift_selection_mode,
)
from prompt_toolkit.key_binding import ConditionalKeyBindings
from prompt_toolkit.key_binding.bindings.named_commands import (
accept_line,
backward_delete_char,
backward_word,
beginning_of_buffer,
delete_char,
end_of_buffer,
forward_word,
get_by_name,
)
from prompt_toolkit.key_binding.bindings.scroll import (
scroll_backward,
scroll_forward,
scroll_half_page_down,
scroll_half_page_up,
scroll_one_line_down,
scroll_one_line_up,
)
from prompt_toolkit.keys import Keys
from prompt_toolkit.selection import SelectionState, SelectionType
from euporie.core.commands import add_cmd, get_cmd
from euporie.core.current import get_app
from euporie.core.filters import (
buffer_is_code,
buffer_is_markdown,
cursor_at_start_of_line,
cursor_in_leading_ws,
has_suggestion,
insert_mode,
is_returnable,
micro_insert_mode,
micro_mode,
micro_recording_macro,
micro_replace_mode,
)
from euporie.core.key_binding.micro_state import MicroInputMode
from euporie.core.key_binding.registry import (
load_registered_bindings,
register_bindings,
)
from euporie.core.key_binding.utils import if_no_repeat
def newline(event: KeyPressEvent) -> None:
"""Inert a new line, replacing any selection and indenting if appropriate."""
# TODO https://git.io/J9GfI
buffer = get_app().current_buffer
document = buffer.document
buffer.cut_selection()
buffer.newline(copy_margin=not in_paste_mode())
if buffer_is_code():
pre = document.current_line_before_cursor.rstrip()
post = document.current_line_after_cursor.lstrip()
if post and post.strip()[0] in (")", "]", "}"):
buffer.insert_text(
"\n" + buffer.document.leading_whitespace_in_current_line,
move_cursor=False,
fire_event=False,
)
if pre and pre[-1:] in (":", "(", "[", "{"):
dent_buffer(event)
filter=(buffer_has_focus & (cursor_in_leading_ws | has_selection)),
def get_app() -> BaseApp:
"""Get the current active (running) Application."""
from euporie.core.app import BaseApp
session = _current_app_session.get()
if isinstance(session.app, BaseApp):
return session.app
# Use a baseapp as our "DummyApplication"
return BaseApp()
The provided code snippet includes necessary dependencies for implementing the `duplicate_line` function. Write a Python function `def duplicate_line() -> None` to solve the following problem:
Duplicate the current line.
Here is the function:
def duplicate_line() -> None:
"""Duplicate the current line."""
buffer = get_app().current_buffer
line = buffer.document.current_line
eol = buffer.document.get_end_of_line_position()
buffer.cursor_position += eol
buffer.newline(copy_margin=False)
buffer.insert_text(line)
buffer.cursor_position -= eol | Duplicate the current line. |
6,904 | from __future__ import annotations
import logging
import re
from functools import partial
from typing import TYPE_CHECKING
from aenum import extend_enum
from prompt_toolkit.buffer import indent, unindent
from prompt_toolkit.document import Document
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.filters import (
buffer_has_focus,
has_selection,
in_paste_mode,
is_multiline,
shift_selection_mode,
)
from prompt_toolkit.key_binding import ConditionalKeyBindings
from prompt_toolkit.key_binding.bindings.named_commands import (
accept_line,
backward_delete_char,
backward_word,
beginning_of_buffer,
delete_char,
end_of_buffer,
forward_word,
get_by_name,
)
from prompt_toolkit.key_binding.bindings.scroll import (
scroll_backward,
scroll_forward,
scroll_half_page_down,
scroll_half_page_up,
scroll_one_line_down,
scroll_one_line_up,
)
from prompt_toolkit.keys import Keys
from prompt_toolkit.selection import SelectionState, SelectionType
from euporie.core.commands import add_cmd, get_cmd
from euporie.core.current import get_app
from euporie.core.filters import (
buffer_is_code,
buffer_is_markdown,
cursor_at_start_of_line,
cursor_in_leading_ws,
has_suggestion,
insert_mode,
is_returnable,
micro_insert_mode,
micro_mode,
micro_recording_macro,
micro_replace_mode,
)
from euporie.core.key_binding.micro_state import MicroInputMode
from euporie.core.key_binding.registry import (
load_registered_bindings,
register_bindings,
)
from euporie.core.key_binding.utils import if_no_repeat
def get_app() -> BaseApp:
"""Get the current active (running) Application."""
from euporie.core.app import BaseApp
session = _current_app_session.get()
if isinstance(session.app, BaseApp):
return session.app
# Use a baseapp as our "DummyApplication"
return BaseApp()
The provided code snippet includes necessary dependencies for implementing the `duplicate_selection` function. Write a Python function `def duplicate_selection() -> None` to solve the following problem:
Duplicate the current selection.
Here is the function:
def duplicate_selection() -> None:
"""Duplicate the current selection."""
buffer = get_app().current_buffer
selection_state = buffer.selection_state
from_, to = buffer.document.selection_range()
text = buffer.document.text[from_:to]
buffer.insert_text(text)
buffer.selection_state = selection_state | Duplicate the current selection. |
6,905 | from __future__ import annotations
import logging
import re
from functools import partial
from typing import TYPE_CHECKING
from aenum import extend_enum
from prompt_toolkit.buffer import indent, unindent
from prompt_toolkit.document import Document
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.filters import (
buffer_has_focus,
has_selection,
in_paste_mode,
is_multiline,
shift_selection_mode,
)
from prompt_toolkit.key_binding import ConditionalKeyBindings
from prompt_toolkit.key_binding.bindings.named_commands import (
accept_line,
backward_delete_char,
backward_word,
beginning_of_buffer,
delete_char,
end_of_buffer,
forward_word,
get_by_name,
)
from prompt_toolkit.key_binding.bindings.scroll import (
scroll_backward,
scroll_forward,
scroll_half_page_down,
scroll_half_page_up,
scroll_one_line_down,
scroll_one_line_up,
)
from prompt_toolkit.keys import Keys
from prompt_toolkit.selection import SelectionState, SelectionType
from euporie.core.commands import add_cmd, get_cmd
from euporie.core.current import get_app
from euporie.core.filters import (
buffer_is_code,
buffer_is_markdown,
cursor_at_start_of_line,
cursor_in_leading_ws,
has_suggestion,
insert_mode,
is_returnable,
micro_insert_mode,
micro_mode,
micro_recording_macro,
micro_replace_mode,
)
from euporie.core.key_binding.micro_state import MicroInputMode
from euporie.core.key_binding.registry import (
load_registered_bindings,
register_bindings,
)
from euporie.core.key_binding.utils import if_no_repeat
def cut_selection() -> None:
"""Remove the current selection and adds it to the clipboard."""
data = get_app().current_buffer.cut_selection()
get_app().clipboard.set_data(data)
filter=buffer_has_focus,
def get_app() -> BaseApp:
"""Get the current active (running) Application."""
from euporie.core.app import BaseApp
session = _current_app_session.get()
if isinstance(session.app, BaseApp):
return session.app
# Use a baseapp as our "DummyApplication"
return BaseApp()
The provided code snippet includes necessary dependencies for implementing the `paste_clipboard` function. Write a Python function `def paste_clipboard() -> None` to solve the following problem:
Pate the clipboard contents, replacing any current selection.
Here is the function:
def paste_clipboard() -> None:
"""Pate the clipboard contents, replacing any current selection."""
app = get_app()
buff = app.current_buffer
if buff.selection_state:
buff.cut_selection()
buff.paste_clipboard_data(app.clipboard.get_data()) | Pate the clipboard contents, replacing any current selection. |
6,906 | from __future__ import annotations
import logging
import re
from functools import partial
from typing import TYPE_CHECKING
from aenum import extend_enum
from prompt_toolkit.buffer import indent, unindent
from prompt_toolkit.document import Document
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.filters import (
buffer_has_focus,
has_selection,
in_paste_mode,
is_multiline,
shift_selection_mode,
)
from prompt_toolkit.key_binding import ConditionalKeyBindings
from prompt_toolkit.key_binding.bindings.named_commands import (
accept_line,
backward_delete_char,
backward_word,
beginning_of_buffer,
delete_char,
end_of_buffer,
forward_word,
get_by_name,
)
from prompt_toolkit.key_binding.bindings.scroll import (
scroll_backward,
scroll_forward,
scroll_half_page_down,
scroll_half_page_up,
scroll_one_line_down,
scroll_one_line_up,
)
from prompt_toolkit.keys import Keys
from prompt_toolkit.selection import SelectionState, SelectionType
from euporie.core.commands import add_cmd, get_cmd
from euporie.core.current import get_app
from euporie.core.filters import (
buffer_is_code,
buffer_is_markdown,
cursor_at_start_of_line,
cursor_in_leading_ws,
has_suggestion,
insert_mode,
is_returnable,
micro_insert_mode,
micro_mode,
micro_recording_macro,
micro_replace_mode,
)
from euporie.core.key_binding.micro_state import MicroInputMode
from euporie.core.key_binding.registry import (
load_registered_bindings,
register_bindings,
)
from euporie.core.key_binding.utils import if_no_repeat
def get_app() -> BaseApp:
"""Get the current active (running) Application."""
from euporie.core.app import BaseApp
session = _current_app_session.get()
if isinstance(session.app, BaseApp):
return session.app
# Use a baseapp as our "DummyApplication"
return BaseApp()
The provided code snippet includes necessary dependencies for implementing the `copy_selection` function. Write a Python function `def copy_selection() -> None` to solve the following problem:
Add the current selection to the clipboard.
Here is the function:
def copy_selection() -> None:
"""Add the current selection to the clipboard."""
app = get_app()
buffer = app.current_buffer
selection_state = buffer.selection_state
data = buffer.copy_selection()
buffer.selection_state = selection_state
app.clipboard.set_data(data) | Add the current selection to the clipboard. |
6,907 | from __future__ import annotations
import logging
import re
from functools import partial
from typing import TYPE_CHECKING
from aenum import extend_enum
from prompt_toolkit.buffer import indent, unindent
from prompt_toolkit.document import Document
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.filters import (
buffer_has_focus,
has_selection,
in_paste_mode,
is_multiline,
shift_selection_mode,
)
from prompt_toolkit.key_binding import ConditionalKeyBindings
from prompt_toolkit.key_binding.bindings.named_commands import (
accept_line,
backward_delete_char,
backward_word,
beginning_of_buffer,
delete_char,
end_of_buffer,
forward_word,
get_by_name,
)
from prompt_toolkit.key_binding.bindings.scroll import (
scroll_backward,
scroll_forward,
scroll_half_page_down,
scroll_half_page_up,
scroll_one_line_down,
scroll_one_line_up,
)
from prompt_toolkit.keys import Keys
from prompt_toolkit.selection import SelectionState, SelectionType
from euporie.core.commands import add_cmd, get_cmd
from euporie.core.current import get_app
from euporie.core.filters import (
buffer_is_code,
buffer_is_markdown,
cursor_at_start_of_line,
cursor_in_leading_ws,
has_suggestion,
insert_mode,
is_returnable,
micro_insert_mode,
micro_mode,
micro_recording_macro,
micro_replace_mode,
)
from euporie.core.key_binding.micro_state import MicroInputMode
from euporie.core.key_binding.registry import (
load_registered_bindings,
register_bindings,
)
from euporie.core.key_binding.utils import if_no_repeat
def get_app() -> BaseApp:
"""Get the current active (running) Application."""
from euporie.core.app import BaseApp
session = _current_app_session.get()
if isinstance(session.app, BaseApp):
return session.app
# Use a baseapp as our "DummyApplication"
return BaseApp()
The provided code snippet includes necessary dependencies for implementing the `cut_line` function. Write a Python function `def cut_line() -> None` to solve the following problem:
Remove the current line adds it to the clipboard.
Here is the function:
def cut_line() -> None:
"""Remove the current line adds it to the clipboard."""
app = get_app()
buffer = app.current_buffer
clipboard = app.clipboard
clipboard_text = clipboard.get_data().text
line = buffer.document.current_line
clipboard.set_text(f"{clipboard_text}\n{line}")
lines = buffer.document.lines[:]
del lines[buffer.document.cursor_position_row]
text = "\n".join(lines)
buffer.document = Document(
text,
min(
buffer.cursor_position + buffer.document.get_start_of_line_position(),
len(text),
),
) | Remove the current line adds it to the clipboard. |
6,908 | from __future__ import annotations
import logging
import re
from functools import partial
from typing import TYPE_CHECKING
from aenum import extend_enum
from prompt_toolkit.buffer import indent, unindent
from prompt_toolkit.document import Document
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.filters import (
buffer_has_focus,
has_selection,
in_paste_mode,
is_multiline,
shift_selection_mode,
)
from prompt_toolkit.key_binding import ConditionalKeyBindings
from prompt_toolkit.key_binding.bindings.named_commands import (
accept_line,
backward_delete_char,
backward_word,
beginning_of_buffer,
delete_char,
end_of_buffer,
forward_word,
get_by_name,
)
from prompt_toolkit.key_binding.bindings.scroll import (
scroll_backward,
scroll_forward,
scroll_half_page_down,
scroll_half_page_up,
scroll_one_line_down,
scroll_one_line_up,
)
from prompt_toolkit.keys import Keys
from prompt_toolkit.selection import SelectionState, SelectionType
from euporie.core.commands import add_cmd, get_cmd
from euporie.core.current import get_app
from euporie.core.filters import (
buffer_is_code,
buffer_is_markdown,
cursor_at_start_of_line,
cursor_in_leading_ws,
has_suggestion,
insert_mode,
is_returnable,
micro_insert_mode,
micro_mode,
micro_recording_macro,
micro_replace_mode,
)
from euporie.core.key_binding.micro_state import MicroInputMode
from euporie.core.key_binding.registry import (
load_registered_bindings,
register_bindings,
)
from euporie.core.key_binding.utils import if_no_repeat
def move_line(n: int) -> None:
"""Move the current or selected lines up or down by one or more lines."""
buffer = get_app().current_buffer
selection_state = buffer.selection_state
lines = buffer.text.splitlines(keepends=False)
start, end = (
buffer.document.translate_index_to_position(x)[0]
for x in buffer.document.selection_range()
)
end += 1
# Check that we are not moving lines off the edge of the document
if start + n < 0 or end > len(lines):
return
# Rearrange the lines
sel_lines = lines[start:end]
lines_new = lines[:start] + lines[end:]
lines_new = lines_new[: start + n] + sel_lines + lines_new[start + n :]
# Calculate the new cursor position
row = buffer.document.cursor_position_row
col = buffer.document.cursor_position_col
text = "\n".join(lines_new)
cursor_position_new = Document(text).translate_row_col_to_index(row + n, col)
cursor_position_diff = buffer.cursor_position - cursor_position_new
# Update the selection if we have one
if selection_state:
selection_state.original_cursor_position -= cursor_position_diff
# Update the buffer contents
buffer.document = Document(text, cursor_position_new)
buffer.selection_state = selection_state
filter=buffer_has_focus,
The provided code snippet includes necessary dependencies for implementing the `move_lines_up` function. Write a Python function `def move_lines_up() -> None` to solve the following problem:
Move the current or selected lines up by one line.
Here is the function:
def move_lines_up() -> None:
"""Move the current or selected lines up by one line."""
move_line(-1) | Move the current or selected lines up by one line. |
6,909 | from __future__ import annotations
import logging
import re
from functools import partial
from typing import TYPE_CHECKING
from aenum import extend_enum
from prompt_toolkit.buffer import indent, unindent
from prompt_toolkit.document import Document
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.filters import (
buffer_has_focus,
has_selection,
in_paste_mode,
is_multiline,
shift_selection_mode,
)
from prompt_toolkit.key_binding import ConditionalKeyBindings
from prompt_toolkit.key_binding.bindings.named_commands import (
accept_line,
backward_delete_char,
backward_word,
beginning_of_buffer,
delete_char,
end_of_buffer,
forward_word,
get_by_name,
)
from prompt_toolkit.key_binding.bindings.scroll import (
scroll_backward,
scroll_forward,
scroll_half_page_down,
scroll_half_page_up,
scroll_one_line_down,
scroll_one_line_up,
)
from prompt_toolkit.keys import Keys
from prompt_toolkit.selection import SelectionState, SelectionType
from euporie.core.commands import add_cmd, get_cmd
from euporie.core.current import get_app
from euporie.core.filters import (
buffer_is_code,
buffer_is_markdown,
cursor_at_start_of_line,
cursor_in_leading_ws,
has_suggestion,
insert_mode,
is_returnable,
micro_insert_mode,
micro_mode,
micro_recording_macro,
micro_replace_mode,
)
from euporie.core.key_binding.micro_state import MicroInputMode
from euporie.core.key_binding.registry import (
load_registered_bindings,
register_bindings,
)
from euporie.core.key_binding.utils import if_no_repeat
def move_line(n: int) -> None:
"""Move the current or selected lines up or down by one or more lines."""
buffer = get_app().current_buffer
selection_state = buffer.selection_state
lines = buffer.text.splitlines(keepends=False)
start, end = (
buffer.document.translate_index_to_position(x)[0]
for x in buffer.document.selection_range()
)
end += 1
# Check that we are not moving lines off the edge of the document
if start + n < 0 or end > len(lines):
return
# Rearrange the lines
sel_lines = lines[start:end]
lines_new = lines[:start] + lines[end:]
lines_new = lines_new[: start + n] + sel_lines + lines_new[start + n :]
# Calculate the new cursor position
row = buffer.document.cursor_position_row
col = buffer.document.cursor_position_col
text = "\n".join(lines_new)
cursor_position_new = Document(text).translate_row_col_to_index(row + n, col)
cursor_position_diff = buffer.cursor_position - cursor_position_new
# Update the selection if we have one
if selection_state:
selection_state.original_cursor_position -= cursor_position_diff
# Update the buffer contents
buffer.document = Document(text, cursor_position_new)
buffer.selection_state = selection_state
filter=buffer_has_focus,
The provided code snippet includes necessary dependencies for implementing the `move_lines_down` function. Write a Python function `def move_lines_down() -> None` to solve the following problem:
Move the current or selected lines down by one line.
Here is the function:
def move_lines_down() -> None:
"""Move the current or selected lines down by one line."""
move_line(1) | Move the current or selected lines down by one line. |
6,910 | from __future__ import annotations
import logging
import re
from functools import partial
from typing import TYPE_CHECKING
from aenum import extend_enum
from prompt_toolkit.buffer import indent, unindent
from prompt_toolkit.document import Document
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.filters import (
buffer_has_focus,
has_selection,
in_paste_mode,
is_multiline,
shift_selection_mode,
)
from prompt_toolkit.key_binding import ConditionalKeyBindings
from prompt_toolkit.key_binding.bindings.named_commands import (
accept_line,
backward_delete_char,
backward_word,
beginning_of_buffer,
delete_char,
end_of_buffer,
forward_word,
get_by_name,
)
from prompt_toolkit.key_binding.bindings.scroll import (
scroll_backward,
scroll_forward,
scroll_half_page_down,
scroll_half_page_up,
scroll_one_line_down,
scroll_one_line_up,
)
from prompt_toolkit.keys import Keys
from prompt_toolkit.selection import SelectionState, SelectionType
from euporie.core.commands import add_cmd, get_cmd
from euporie.core.current import get_app
from euporie.core.filters import (
buffer_is_code,
buffer_is_markdown,
cursor_at_start_of_line,
cursor_in_leading_ws,
has_suggestion,
insert_mode,
is_returnable,
micro_insert_mode,
micro_mode,
micro_recording_macro,
micro_replace_mode,
)
from euporie.core.key_binding.micro_state import MicroInputMode
from euporie.core.key_binding.registry import (
load_registered_bindings,
register_bindings,
)
from euporie.core.key_binding.utils import if_no_repeat
def dent_buffer(event: KeyPressEvent, indenting: bool = True) -> None:
"""Indent or unindent the current or selected lines in a buffer."""
buffer = get_app().current_buffer
document = buffer.document
selection_state = buffer.selection_state
cursor_position = buffer.cursor_position
lines = buffer.document.lines
# Apply indentation end the selected range
start, end = (
document.translate_index_to_position(x)[0] for x in document.selection_range()
)
dent_func = indent if indenting else unindent
dent_func(buffer, start, end + 1)
# If there is a selection, adjust the selection range
if selection_state:
# Calculate the direction of the change
sign = indenting * 2 - 1
# Determine which lines were affected
lines_affected = {
i: indenting or lines[i][:1] == " " for i in range(start, end + 1)
}
total_lines_affected = sum(lines_affected.values())
# If the cursor was in the first line, it will only move by the change of that line
# otherwise it will move by the total change of all lines
cursor_in_first_line = document.cursor_position_row == start
diffs = (
get_app().config.tab_size * total_lines_affected,
get_app().config.tab_size * lines_affected[start],
)
# Do not move the cursor or the start of the selection back onto a previous line
buffer.cursor_position = (
cursor_position
+ max(
diffs[cursor_in_first_line],
document.get_start_of_line_position(),
)
* sign
)
og_cursor_col = document.translate_index_to_position(
selection_state.original_cursor_position
)[1]
selection_state.original_cursor_position += (
max(
diffs[not cursor_in_first_line],
-og_cursor_col,
)
* sign
)
# Maintain the selection state before indentation
buffer.selection_state = selection_state
filter=buffer_has_focus & is_multiline,
The provided code snippet includes necessary dependencies for implementing the `indent_lines` function. Write a Python function `def indent_lines(event: KeyPressEvent) -> None` to solve the following problem:
Inndent the current or selected lines.
Here is the function:
def indent_lines(event: KeyPressEvent) -> None:
"""Inndent the current or selected lines."""
dent_buffer(event) | Inndent the current or selected lines. |
6,911 | from __future__ import annotations
import logging
import re
from functools import partial
from typing import TYPE_CHECKING
from aenum import extend_enum
from prompt_toolkit.buffer import indent, unindent
from prompt_toolkit.document import Document
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.filters import (
buffer_has_focus,
has_selection,
in_paste_mode,
is_multiline,
shift_selection_mode,
)
from prompt_toolkit.key_binding import ConditionalKeyBindings
from prompt_toolkit.key_binding.bindings.named_commands import (
accept_line,
backward_delete_char,
backward_word,
beginning_of_buffer,
delete_char,
end_of_buffer,
forward_word,
get_by_name,
)
from prompt_toolkit.key_binding.bindings.scroll import (
scroll_backward,
scroll_forward,
scroll_half_page_down,
scroll_half_page_up,
scroll_one_line_down,
scroll_one_line_up,
)
from prompt_toolkit.keys import Keys
from prompt_toolkit.selection import SelectionState, SelectionType
from euporie.core.commands import add_cmd, get_cmd
from euporie.core.current import get_app
from euporie.core.filters import (
buffer_is_code,
buffer_is_markdown,
cursor_at_start_of_line,
cursor_in_leading_ws,
has_suggestion,
insert_mode,
is_returnable,
micro_insert_mode,
micro_mode,
micro_recording_macro,
micro_replace_mode,
)
from euporie.core.key_binding.micro_state import MicroInputMode
from euporie.core.key_binding.registry import (
load_registered_bindings,
register_bindings,
)
from euporie.core.key_binding.utils import if_no_repeat
def dent_buffer(event: KeyPressEvent, indenting: bool = True) -> None:
"""Indent or unindent the current or selected lines in a buffer."""
buffer = get_app().current_buffer
document = buffer.document
selection_state = buffer.selection_state
cursor_position = buffer.cursor_position
lines = buffer.document.lines
# Apply indentation end the selected range
start, end = (
document.translate_index_to_position(x)[0] for x in document.selection_range()
)
dent_func = indent if indenting else unindent
dent_func(buffer, start, end + 1)
# If there is a selection, adjust the selection range
if selection_state:
# Calculate the direction of the change
sign = indenting * 2 - 1
# Determine which lines were affected
lines_affected = {
i: indenting or lines[i][:1] == " " for i in range(start, end + 1)
}
total_lines_affected = sum(lines_affected.values())
# If the cursor was in the first line, it will only move by the change of that line
# otherwise it will move by the total change of all lines
cursor_in_first_line = document.cursor_position_row == start
diffs = (
get_app().config.tab_size * total_lines_affected,
get_app().config.tab_size * lines_affected[start],
)
# Do not move the cursor or the start of the selection back onto a previous line
buffer.cursor_position = (
cursor_position
+ max(
diffs[cursor_in_first_line],
document.get_start_of_line_position(),
)
* sign
)
og_cursor_col = document.translate_index_to_position(
selection_state.original_cursor_position
)[1]
selection_state.original_cursor_position += (
max(
diffs[not cursor_in_first_line],
-og_cursor_col,
)
* sign
)
# Maintain the selection state before indentation
buffer.selection_state = selection_state
filter=buffer_has_focus & is_multiline,
The provided code snippet includes necessary dependencies for implementing the `unindent_lines` function. Write a Python function `def unindent_lines(event: KeyPressEvent) -> None` to solve the following problem:
Unindent the current or selected lines.
Here is the function:
def unindent_lines(event: KeyPressEvent) -> None:
"""Unindent the current or selected lines."""
dent_buffer(event, indenting=False) | Unindent the current or selected lines. |
6,912 | from __future__ import annotations
import logging
import re
from functools import partial
from typing import TYPE_CHECKING
from aenum import extend_enum
from prompt_toolkit.buffer import indent, unindent
from prompt_toolkit.document import Document
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.filters import (
buffer_has_focus,
has_selection,
in_paste_mode,
is_multiline,
shift_selection_mode,
)
from prompt_toolkit.key_binding import ConditionalKeyBindings
from prompt_toolkit.key_binding.bindings.named_commands import (
accept_line,
backward_delete_char,
backward_word,
beginning_of_buffer,
delete_char,
end_of_buffer,
forward_word,
get_by_name,
)
from prompt_toolkit.key_binding.bindings.scroll import (
scroll_backward,
scroll_forward,
scroll_half_page_down,
scroll_half_page_up,
scroll_one_line_down,
scroll_one_line_up,
)
from prompt_toolkit.keys import Keys
from prompt_toolkit.selection import SelectionState, SelectionType
from euporie.core.commands import add_cmd, get_cmd
from euporie.core.current import get_app
from euporie.core.filters import (
buffer_is_code,
buffer_is_markdown,
cursor_at_start_of_line,
cursor_in_leading_ws,
has_suggestion,
insert_mode,
is_returnable,
micro_insert_mode,
micro_mode,
micro_recording_macro,
micro_replace_mode,
)
from euporie.core.key_binding.micro_state import MicroInputMode
from euporie.core.key_binding.registry import (
load_registered_bindings,
register_bindings,
)
from euporie.core.key_binding.utils import if_no_repeat
def cut_selection() -> None:
"""Remove the current selection and adds it to the clipboard."""
data = get_app().current_buffer.cut_selection()
get_app().clipboard.set_data(data)
filter=buffer_has_focus,
def get_app() -> BaseApp:
"""Get the current active (running) Application."""
from euporie.core.app import BaseApp
session = _current_app_session.get()
if isinstance(session.app, BaseApp):
return session.app
# Use a baseapp as our "DummyApplication"
return BaseApp()
The provided code snippet includes necessary dependencies for implementing the `toggle_case` function. Write a Python function `def toggle_case() -> None` to solve the following problem:
Toggle the case of the current word or selection.
Here is the function:
def toggle_case() -> None:
"""Toggle the case of the current word or selection."""
buffer = get_app().current_buffer
selection_state = buffer.selection_state
if selection_state is None:
start, end = buffer.document.find_boundaries_of_current_word()
selection_state = SelectionState(buffer.cursor_position + start)
selection_state.enter_shift_mode()
buffer.cursor_position += end
if selection_state is not None:
cp = buffer.cursor_position
text = buffer.cut_selection().text
if text.islower():
text = text.title()
elif text.istitle():
text = text.upper()
else:
text = text.lower()
buffer.insert_text(text)
buffer.cursor_position = cp
buffer.selection_state = selection_state | Toggle the case of the current word or selection. |
6,913 | from __future__ import annotations
import logging
import re
from functools import partial
from typing import TYPE_CHECKING
from aenum import extend_enum
from prompt_toolkit.buffer import indent, unindent
from prompt_toolkit.document import Document
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.filters import (
buffer_has_focus,
has_selection,
in_paste_mode,
is_multiline,
shift_selection_mode,
)
from prompt_toolkit.key_binding import ConditionalKeyBindings
from prompt_toolkit.key_binding.bindings.named_commands import (
accept_line,
backward_delete_char,
backward_word,
beginning_of_buffer,
delete_char,
end_of_buffer,
forward_word,
get_by_name,
)
from prompt_toolkit.key_binding.bindings.scroll import (
scroll_backward,
scroll_forward,
scroll_half_page_down,
scroll_half_page_up,
scroll_one_line_down,
scroll_one_line_up,
)
from prompt_toolkit.keys import Keys
from prompt_toolkit.selection import SelectionState, SelectionType
from euporie.core.commands import add_cmd, get_cmd
from euporie.core.current import get_app
from euporie.core.filters import (
buffer_is_code,
buffer_is_markdown,
cursor_at_start_of_line,
cursor_in_leading_ws,
has_suggestion,
insert_mode,
is_returnable,
micro_insert_mode,
micro_mode,
micro_recording_macro,
micro_replace_mode,
)
from euporie.core.key_binding.micro_state import MicroInputMode
from euporie.core.key_binding.registry import (
load_registered_bindings,
register_bindings,
)
from euporie.core.key_binding.utils import if_no_repeat
def get_app() -> BaseApp:
"""Get the current active (running) Application."""
from euporie.core.app import BaseApp
session = _current_app_session.get()
if isinstance(session.app, BaseApp):
return session.app
# Use a baseapp as our "DummyApplication"
return BaseApp()
The provided code snippet includes necessary dependencies for implementing the `undo` function. Write a Python function `def undo() -> None` to solve the following problem:
Undo the last edit.
Here is the function:
def undo() -> None:
"""Undo the last edit."""
get_app().current_buffer.undo() | Undo the last edit. |
6,914 | from __future__ import annotations
import logging
import re
from functools import partial
from typing import TYPE_CHECKING
from aenum import extend_enum
from prompt_toolkit.buffer import indent, unindent
from prompt_toolkit.document import Document
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.filters import (
buffer_has_focus,
has_selection,
in_paste_mode,
is_multiline,
shift_selection_mode,
)
from prompt_toolkit.key_binding import ConditionalKeyBindings
from prompt_toolkit.key_binding.bindings.named_commands import (
accept_line,
backward_delete_char,
backward_word,
beginning_of_buffer,
delete_char,
end_of_buffer,
forward_word,
get_by_name,
)
from prompt_toolkit.key_binding.bindings.scroll import (
scroll_backward,
scroll_forward,
scroll_half_page_down,
scroll_half_page_up,
scroll_one_line_down,
scroll_one_line_up,
)
from prompt_toolkit.keys import Keys
from prompt_toolkit.selection import SelectionState, SelectionType
from euporie.core.commands import add_cmd, get_cmd
from euporie.core.current import get_app
from euporie.core.filters import (
buffer_is_code,
buffer_is_markdown,
cursor_at_start_of_line,
cursor_in_leading_ws,
has_suggestion,
insert_mode,
is_returnable,
micro_insert_mode,
micro_mode,
micro_recording_macro,
micro_replace_mode,
)
from euporie.core.key_binding.micro_state import MicroInputMode
from euporie.core.key_binding.registry import (
load_registered_bindings,
register_bindings,
)
from euporie.core.key_binding.utils import if_no_repeat
def get_app() -> BaseApp:
"""Get the current active (running) Application."""
from euporie.core.app import BaseApp
session = _current_app_session.get()
if isinstance(session.app, BaseApp):
return session.app
# Use a baseapp as our "DummyApplication"
return BaseApp()
The provided code snippet includes necessary dependencies for implementing the `redo` function. Write a Python function `def redo() -> None` to solve the following problem:
Redo the last edit.
Here is the function:
def redo() -> None:
"""Redo the last edit."""
get_app().current_buffer.redo() | Redo the last edit. |
6,915 | from __future__ import annotations
import logging
import re
from functools import partial
from typing import TYPE_CHECKING
from aenum import extend_enum
from prompt_toolkit.buffer import indent, unindent
from prompt_toolkit.document import Document
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.filters import (
buffer_has_focus,
has_selection,
in_paste_mode,
is_multiline,
shift_selection_mode,
)
from prompt_toolkit.key_binding import ConditionalKeyBindings
from prompt_toolkit.key_binding.bindings.named_commands import (
accept_line,
backward_delete_char,
backward_word,
beginning_of_buffer,
delete_char,
end_of_buffer,
forward_word,
get_by_name,
)
from prompt_toolkit.key_binding.bindings.scroll import (
scroll_backward,
scroll_forward,
scroll_half_page_down,
scroll_half_page_up,
scroll_one_line_down,
scroll_one_line_up,
)
from prompt_toolkit.keys import Keys
from prompt_toolkit.selection import SelectionState, SelectionType
from euporie.core.commands import add_cmd, get_cmd
from euporie.core.current import get_app
from euporie.core.filters import (
buffer_is_code,
buffer_is_markdown,
cursor_at_start_of_line,
cursor_in_leading_ws,
has_suggestion,
insert_mode,
is_returnable,
micro_insert_mode,
micro_mode,
micro_recording_macro,
micro_replace_mode,
)
from euporie.core.key_binding.micro_state import MicroInputMode
from euporie.core.key_binding.registry import (
load_registered_bindings,
register_bindings,
)
from euporie.core.key_binding.utils import if_no_repeat
def get_app() -> BaseApp:
"""Get the current active (running) Application."""
from euporie.core.app import BaseApp
session = _current_app_session.get()
if isinstance(session.app, BaseApp):
return session.app
# Use a baseapp as our "DummyApplication"
return BaseApp()
The provided code snippet includes necessary dependencies for implementing the `select_all` function. Write a Python function `def select_all() -> None` to solve the following problem:
Select all text.
Here is the function:
def select_all() -> None:
"""Select all text."""
buffer = get_app().current_buffer
buffer.selection_state = SelectionState(0)
buffer.cursor_position = len(buffer.text)
buffer.selection_state.enter_shift_mode() | Select all text. |
6,916 | from __future__ import annotations
import logging
import re
from functools import partial
from typing import TYPE_CHECKING
from aenum import extend_enum
from prompt_toolkit.buffer import indent, unindent
from prompt_toolkit.document import Document
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.filters import (
buffer_has_focus,
has_selection,
in_paste_mode,
is_multiline,
shift_selection_mode,
)
from prompt_toolkit.key_binding import ConditionalKeyBindings
from prompt_toolkit.key_binding.bindings.named_commands import (
accept_line,
backward_delete_char,
backward_word,
beginning_of_buffer,
delete_char,
end_of_buffer,
forward_word,
get_by_name,
)
from prompt_toolkit.key_binding.bindings.scroll import (
scroll_backward,
scroll_forward,
scroll_half_page_down,
scroll_half_page_up,
scroll_one_line_down,
scroll_one_line_up,
)
from prompt_toolkit.keys import Keys
from prompt_toolkit.selection import SelectionState, SelectionType
from euporie.core.commands import add_cmd, get_cmd
from euporie.core.current import get_app
from euporie.core.filters import (
buffer_is_code,
buffer_is_markdown,
cursor_at_start_of_line,
cursor_in_leading_ws,
has_suggestion,
insert_mode,
is_returnable,
micro_insert_mode,
micro_mode,
micro_recording_macro,
micro_replace_mode,
)
from euporie.core.key_binding.micro_state import MicroInputMode
from euporie.core.key_binding.registry import (
load_registered_bindings,
register_bindings,
)
from euporie.core.key_binding.utils import if_no_repeat
def unshift_move(event: KeyPressEvent) -> None:
"""Handle keys in shift selection mode.
When called with a shift + movement key press event, moves the cursor as if shift
is not pressed.
Args:
event: The key press event to process
"""
key = event.key_sequence[0].key
if key == Keys.ShiftUp:
event.current_buffer.auto_up(count=event.arg)
return
if key == Keys.ShiftDown:
event.current_buffer.auto_down(count=event.arg)
return
# the other keys are handled through their readline command
key_to_command: dict[tuple[Keys | str, ...], str] = {
(Keys.ShiftLeft,): "move-cursor-left",
(Keys.ShiftRight,): "move-cursor-right",
(Keys.ShiftHome,): "go-to-start-of-line",
(Keys.ShiftEnd,): "go-to-end-of-line",
(
Keys.Escape,
Keys.ShiftLeft,
): "backward-word",
(
Keys.Escape,
Keys.ShiftRight,
): "forward-word",
(Keys.ControlShiftLeft,): "backward-word",
(Keys.ControlShiftRight,): "forward-word",
(Keys.ControlShiftHome,): "beginning-of-buffer",
(Keys.ControlShiftEnd,): "end-of-buffer",
}
key_sequence = tuple(key_ress.key for key_ress in event.key_sequence)
try:
command = get_cmd(key_to_command[key_sequence])
except KeyError:
pass
else:
command.key_handler(event)
The provided code snippet includes necessary dependencies for implementing the `start_selection` function. Write a Python function `def start_selection(event: KeyPressEvent) -> None` to solve the following problem:
Start a new selection.
Here is the function:
def start_selection(event: KeyPressEvent) -> None:
"""Start a new selection."""
# Take the current cursor position as the start of this selection.
buff = event.current_buffer
if buff.text:
buff.start_selection(selection_type=SelectionType.CHARACTERS)
if buff.selection_state is not None:
buff.selection_state.enter_shift_mode()
# Then move the cursor
original_position = buff.cursor_position
unshift_move(event)
if buff.cursor_position == original_position:
# Cursor didn't actually move - so cancel selection
# to avoid having an empty selection
buff.exit_selection() | Start a new selection. |
6,917 | from __future__ import annotations
import logging
import re
from functools import partial
from typing import TYPE_CHECKING
from aenum import extend_enum
from prompt_toolkit.buffer import indent, unindent
from prompt_toolkit.document import Document
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.filters import (
buffer_has_focus,
has_selection,
in_paste_mode,
is_multiline,
shift_selection_mode,
)
from prompt_toolkit.key_binding import ConditionalKeyBindings
from prompt_toolkit.key_binding.bindings.named_commands import (
accept_line,
backward_delete_char,
backward_word,
beginning_of_buffer,
delete_char,
end_of_buffer,
forward_word,
get_by_name,
)
from prompt_toolkit.key_binding.bindings.scroll import (
scroll_backward,
scroll_forward,
scroll_half_page_down,
scroll_half_page_up,
scroll_one_line_down,
scroll_one_line_up,
)
from prompt_toolkit.keys import Keys
from prompt_toolkit.selection import SelectionState, SelectionType
from euporie.core.commands import add_cmd, get_cmd
from euporie.core.current import get_app
from euporie.core.filters import (
buffer_is_code,
buffer_is_markdown,
cursor_at_start_of_line,
cursor_in_leading_ws,
has_suggestion,
insert_mode,
is_returnable,
micro_insert_mode,
micro_mode,
micro_recording_macro,
micro_replace_mode,
)
from euporie.core.key_binding.micro_state import MicroInputMode
from euporie.core.key_binding.registry import (
load_registered_bindings,
register_bindings,
)
from euporie.core.key_binding.utils import if_no_repeat
def unshift_move(event: KeyPressEvent) -> None:
"""Handle keys in shift selection mode.
When called with a shift + movement key press event, moves the cursor as if shift
is not pressed.
Args:
event: The key press event to process
"""
key = event.key_sequence[0].key
if key == Keys.ShiftUp:
event.current_buffer.auto_up(count=event.arg)
return
if key == Keys.ShiftDown:
event.current_buffer.auto_down(count=event.arg)
return
# the other keys are handled through their readline command
key_to_command: dict[tuple[Keys | str, ...], str] = {
(Keys.ShiftLeft,): "move-cursor-left",
(Keys.ShiftRight,): "move-cursor-right",
(Keys.ShiftHome,): "go-to-start-of-line",
(Keys.ShiftEnd,): "go-to-end-of-line",
(
Keys.Escape,
Keys.ShiftLeft,
): "backward-word",
(
Keys.Escape,
Keys.ShiftRight,
): "forward-word",
(Keys.ControlShiftLeft,): "backward-word",
(Keys.ControlShiftRight,): "forward-word",
(Keys.ControlShiftHome,): "beginning-of-buffer",
(Keys.ControlShiftEnd,): "end-of-buffer",
}
key_sequence = tuple(key_ress.key for key_ress in event.key_sequence)
try:
command = get_cmd(key_to_command[key_sequence])
except KeyError:
pass
else:
command.key_handler(event)
The provided code snippet includes necessary dependencies for implementing the `extend_selection` function. Write a Python function `def extend_selection(event: KeyPressEvent) -> None` to solve the following problem:
Extend the selection.
Here is the function:
def extend_selection(event: KeyPressEvent) -> None:
"""Extend the selection."""
# Just move the cursor, like shift was not pressed
unshift_move(event)
buff = event.current_buffer
if (
buff.selection_state is not None
and buff.cursor_position == buff.selection_state.original_cursor_position
):
# selection is now empty, so cancel selection
buff.exit_selection() | Extend the selection. |
6,918 | from __future__ import annotations
import logging
import re
from functools import partial
from typing import TYPE_CHECKING
from aenum import extend_enum
from prompt_toolkit.buffer import indent, unindent
from prompt_toolkit.document import Document
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.filters import (
buffer_has_focus,
has_selection,
in_paste_mode,
is_multiline,
shift_selection_mode,
)
from prompt_toolkit.key_binding import ConditionalKeyBindings
from prompt_toolkit.key_binding.bindings.named_commands import (
accept_line,
backward_delete_char,
backward_word,
beginning_of_buffer,
delete_char,
end_of_buffer,
forward_word,
get_by_name,
)
from prompt_toolkit.key_binding.bindings.scroll import (
scroll_backward,
scroll_forward,
scroll_half_page_down,
scroll_half_page_up,
scroll_one_line_down,
scroll_one_line_up,
)
from prompt_toolkit.keys import Keys
from prompt_toolkit.selection import SelectionState, SelectionType
from euporie.core.commands import add_cmd, get_cmd
from euporie.core.current import get_app
from euporie.core.filters import (
buffer_is_code,
buffer_is_markdown,
cursor_at_start_of_line,
cursor_in_leading_ws,
has_suggestion,
insert_mode,
is_returnable,
micro_insert_mode,
micro_mode,
micro_recording_macro,
micro_replace_mode,
)
from euporie.core.key_binding.micro_state import MicroInputMode
from euporie.core.key_binding.registry import (
load_registered_bindings,
register_bindings,
)
from euporie.core.key_binding.utils import if_no_repeat
def cut_selection() -> None:
"""Remove the current selection and adds it to the clipboard."""
data = get_app().current_buffer.cut_selection()
get_app().clipboard.set_data(data)
filter=buffer_has_focus,
The provided code snippet includes necessary dependencies for implementing the `replace_selection` function. Write a Python function `def replace_selection(event: KeyPressEvent) -> None` to solve the following problem:
Replace selection by what is typed.
Here is the function:
def replace_selection(event: KeyPressEvent) -> None:
"""Replace selection by what is typed."""
event.current_buffer.cut_selection()
get_by_name("self-insert").call(event) | Replace selection by what is typed. |
6,919 | from __future__ import annotations
import logging
import re
from functools import partial
from typing import TYPE_CHECKING
from aenum import extend_enum
from prompt_toolkit.buffer import indent, unindent
from prompt_toolkit.document import Document
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.filters import (
buffer_has_focus,
has_selection,
in_paste_mode,
is_multiline,
shift_selection_mode,
)
from prompt_toolkit.key_binding import ConditionalKeyBindings
from prompt_toolkit.key_binding.bindings.named_commands import (
accept_line,
backward_delete_char,
backward_word,
beginning_of_buffer,
delete_char,
end_of_buffer,
forward_word,
get_by_name,
)
from prompt_toolkit.key_binding.bindings.scroll import (
scroll_backward,
scroll_forward,
scroll_half_page_down,
scroll_half_page_up,
scroll_one_line_down,
scroll_one_line_up,
)
from prompt_toolkit.keys import Keys
from prompt_toolkit.selection import SelectionState, SelectionType
from euporie.core.commands import add_cmd, get_cmd
from euporie.core.current import get_app
from euporie.core.filters import (
buffer_is_code,
buffer_is_markdown,
cursor_at_start_of_line,
cursor_in_leading_ws,
has_suggestion,
insert_mode,
is_returnable,
micro_insert_mode,
micro_mode,
micro_recording_macro,
micro_replace_mode,
)
from euporie.core.key_binding.micro_state import MicroInputMode
from euporie.core.key_binding.registry import (
load_registered_bindings,
register_bindings,
)
from euporie.core.key_binding.utils import if_no_repeat
def cut_selection() -> None:
"""Remove the current selection and adds it to the clipboard."""
data = get_app().current_buffer.cut_selection()
get_app().clipboard.set_data(data)
filter=buffer_has_focus,
def get_app() -> BaseApp:
"""Get the current active (running) Application."""
from euporie.core.app import BaseApp
session = _current_app_session.get()
if isinstance(session.app, BaseApp):
return session.app
# Use a baseapp as our "DummyApplication"
return BaseApp()
The provided code snippet includes necessary dependencies for implementing the `delete_selection` function. Write a Python function `def delete_selection() -> None` to solve the following problem:
Delete the contents of the current selection.
Here is the function:
def delete_selection() -> None:
"""Delete the contents of the current selection."""
get_app().current_buffer.cut_selection() | Delete the contents of the current selection. |
6,920 | from __future__ import annotations
import logging
import re
from functools import partial
from typing import TYPE_CHECKING
from aenum import extend_enum
from prompt_toolkit.buffer import indent, unindent
from prompt_toolkit.document import Document
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.filters import (
buffer_has_focus,
has_selection,
in_paste_mode,
is_multiline,
shift_selection_mode,
)
from prompt_toolkit.key_binding import ConditionalKeyBindings
from prompt_toolkit.key_binding.bindings.named_commands import (
accept_line,
backward_delete_char,
backward_word,
beginning_of_buffer,
delete_char,
end_of_buffer,
forward_word,
get_by_name,
)
from prompt_toolkit.key_binding.bindings.scroll import (
scroll_backward,
scroll_forward,
scroll_half_page_down,
scroll_half_page_up,
scroll_one_line_down,
scroll_one_line_up,
)
from prompt_toolkit.keys import Keys
from prompt_toolkit.selection import SelectionState, SelectionType
from euporie.core.commands import add_cmd, get_cmd
from euporie.core.current import get_app
from euporie.core.filters import (
buffer_is_code,
buffer_is_markdown,
cursor_at_start_of_line,
cursor_in_leading_ws,
has_suggestion,
insert_mode,
is_returnable,
micro_insert_mode,
micro_mode,
micro_recording_macro,
micro_replace_mode,
)
from euporie.core.key_binding.micro_state import MicroInputMode
from euporie.core.key_binding.registry import (
load_registered_bindings,
register_bindings,
)
from euporie.core.key_binding.utils import if_no_repeat
The provided code snippet includes necessary dependencies for implementing the `cancel_selection` function. Write a Python function `def cancel_selection(event: KeyPressEvent) -> None` to solve the following problem:
Cancel the selection.
Here is the function:
def cancel_selection(event: KeyPressEvent) -> None:
"""Cancel the selection."""
event.current_buffer.exit_selection()
# we then process the cursor movement
key_press = event.key_sequence[0]
event.key_processor.feed(key_press, first=True) | Cancel the selection. |
6,921 | from __future__ import annotations
import logging
import re
from functools import partial
from typing import TYPE_CHECKING
from aenum import extend_enum
from prompt_toolkit.buffer import indent, unindent
from prompt_toolkit.document import Document
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.filters import (
buffer_has_focus,
has_selection,
in_paste_mode,
is_multiline,
shift_selection_mode,
)
from prompt_toolkit.key_binding import ConditionalKeyBindings
from prompt_toolkit.key_binding.bindings.named_commands import (
accept_line,
backward_delete_char,
backward_word,
beginning_of_buffer,
delete_char,
end_of_buffer,
forward_word,
get_by_name,
)
from prompt_toolkit.key_binding.bindings.scroll import (
scroll_backward,
scroll_forward,
scroll_half_page_down,
scroll_half_page_up,
scroll_one_line_down,
scroll_one_line_up,
)
from prompt_toolkit.keys import Keys
from prompt_toolkit.selection import SelectionState, SelectionType
from euporie.core.commands import add_cmd, get_cmd
from euporie.core.current import get_app
from euporie.core.filters import (
buffer_is_code,
buffer_is_markdown,
cursor_at_start_of_line,
cursor_in_leading_ws,
has_suggestion,
insert_mode,
is_returnable,
micro_insert_mode,
micro_mode,
micro_recording_macro,
micro_replace_mode,
)
from euporie.core.key_binding.micro_state import MicroInputMode
from euporie.core.key_binding.registry import (
load_registered_bindings,
register_bindings,
)
from euporie.core.key_binding.utils import if_no_repeat
The provided code snippet includes necessary dependencies for implementing the `go_to_matching_bracket` function. Write a Python function `def go_to_matching_bracket(event: KeyPressEvent) -> None` to solve the following problem:
Go to matching bracket if the cursor is on a paired bracket.
Here is the function:
def go_to_matching_bracket(event: KeyPressEvent) -> None:
"""Go to matching bracket if the cursor is on a paired bracket."""
buff = event.current_buffer
buff.cursor_position += buff.document.find_matching_bracket_position() | Go to matching bracket if the cursor is on a paired bracket. |
6,922 | from __future__ import annotations
import logging
import re
from functools import partial
from typing import TYPE_CHECKING
from aenum import extend_enum
from prompt_toolkit.buffer import indent, unindent
from prompt_toolkit.document import Document
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.filters import (
buffer_has_focus,
has_selection,
in_paste_mode,
is_multiline,
shift_selection_mode,
)
from prompt_toolkit.key_binding import ConditionalKeyBindings
from prompt_toolkit.key_binding.bindings.named_commands import (
accept_line,
backward_delete_char,
backward_word,
beginning_of_buffer,
delete_char,
end_of_buffer,
forward_word,
get_by_name,
)
from prompt_toolkit.key_binding.bindings.scroll import (
scroll_backward,
scroll_forward,
scroll_half_page_down,
scroll_half_page_up,
scroll_one_line_down,
scroll_one_line_up,
)
from prompt_toolkit.keys import Keys
from prompt_toolkit.selection import SelectionState, SelectionType
from euporie.core.commands import add_cmd, get_cmd
from euporie.core.current import get_app
from euporie.core.filters import (
buffer_is_code,
buffer_is_markdown,
cursor_at_start_of_line,
cursor_in_leading_ws,
has_suggestion,
insert_mode,
is_returnable,
micro_insert_mode,
micro_mode,
micro_recording_macro,
micro_replace_mode,
)
from euporie.core.key_binding.micro_state import MicroInputMode
from euporie.core.key_binding.registry import (
load_registered_bindings,
register_bindings,
)
from euporie.core.key_binding.utils import if_no_repeat
def get_app() -> BaseApp:
"""Get the current active (running) Application."""
from euporie.core.app import BaseApp
session = _current_app_session.get()
if isinstance(session.app, BaseApp):
return session.app
# Use a baseapp as our "DummyApplication"
return BaseApp()
The provided code snippet includes necessary dependencies for implementing the `accept_suggestion` function. Write a Python function `def accept_suggestion(event: KeyPressEvent) -> None` to solve the following problem:
Accept suggestion.
Here is the function:
def accept_suggestion(event: KeyPressEvent) -> None:
"""Accept suggestion."""
b = get_app().current_buffer
suggestion = b.suggestion
if suggestion:
b.insert_text(suggestion.text) | Accept suggestion. |
6,923 | from __future__ import annotations
import logging
import re
from functools import partial
from typing import TYPE_CHECKING
from aenum import extend_enum
from prompt_toolkit.buffer import indent, unindent
from prompt_toolkit.document import Document
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.filters import (
buffer_has_focus,
has_selection,
in_paste_mode,
is_multiline,
shift_selection_mode,
)
from prompt_toolkit.key_binding import ConditionalKeyBindings
from prompt_toolkit.key_binding.bindings.named_commands import (
accept_line,
backward_delete_char,
backward_word,
beginning_of_buffer,
delete_char,
end_of_buffer,
forward_word,
get_by_name,
)
from prompt_toolkit.key_binding.bindings.scroll import (
scroll_backward,
scroll_forward,
scroll_half_page_down,
scroll_half_page_up,
scroll_one_line_down,
scroll_one_line_up,
)
from prompt_toolkit.keys import Keys
from prompt_toolkit.selection import SelectionState, SelectionType
from euporie.core.commands import add_cmd, get_cmd
from euporie.core.current import get_app
from euporie.core.filters import (
buffer_is_code,
buffer_is_markdown,
cursor_at_start_of_line,
cursor_in_leading_ws,
has_suggestion,
insert_mode,
is_returnable,
micro_insert_mode,
micro_mode,
micro_recording_macro,
micro_replace_mode,
)
from euporie.core.key_binding.micro_state import MicroInputMode
from euporie.core.key_binding.registry import (
load_registered_bindings,
register_bindings,
)
from euporie.core.key_binding.utils import if_no_repeat
def get_app() -> BaseApp:
"""Get the current active (running) Application."""
from euporie.core.app import BaseApp
session = _current_app_session.get()
if isinstance(session.app, BaseApp):
return session.app
# Use a baseapp as our "DummyApplication"
return BaseApp()
The provided code snippet includes necessary dependencies for implementing the `fill_suggestion` function. Write a Python function `def fill_suggestion(event: KeyPressEvent) -> None` to solve the following problem:
Fill partial suggestion.
Here is the function:
def fill_suggestion(event: KeyPressEvent) -> None:
"""Fill partial suggestion."""
b = get_app().current_buffer
suggestion = b.suggestion
if suggestion:
t = re.split(r"(\S+\s+)", suggestion.text)
b.insert_text(next(x for x in t if x)) | Fill partial suggestion. |
6,924 | from __future__ import annotations
import logging
from prompt_toolkit.application import get_app
from prompt_toolkit.completion import Completion
from prompt_toolkit.filters import (
buffer_has_focus,
completion_is_selected,
has_completions,
has_selection,
)
from prompt_toolkit.key_binding.bindings.named_commands import (
menu_complete,
menu_complete_backward,
)
from euporie.core.commands import add_cmd
from euporie.core.filters import buffer_is_code, cursor_in_leading_ws, insert_mode
from euporie.core.key_binding.registry import register_bindings
The provided code snippet includes necessary dependencies for implementing the `cancel_completion` function. Write a Python function `def cancel_completion() -> None` to solve the following problem:
Cancel a completion.
Here is the function:
def cancel_completion() -> None:
"""Cancel a completion."""
get_app().current_buffer.cancel_completion() | Cancel a completion. |
6,925 | from __future__ import annotations
import logging
from prompt_toolkit.application import get_app
from prompt_toolkit.completion import Completion
from prompt_toolkit.filters import (
buffer_has_focus,
completion_is_selected,
has_completions,
has_selection,
)
from prompt_toolkit.key_binding.bindings.named_commands import (
menu_complete,
menu_complete_backward,
)
from euporie.core.commands import add_cmd
from euporie.core.filters import buffer_is_code, cursor_in_leading_ws, insert_mode
from euporie.core.key_binding.registry import register_bindings
The provided code snippet includes necessary dependencies for implementing the `accept_completion` function. Write a Python function `def accept_completion() -> None` to solve the following problem:
Accept a selected completion.
Here is the function:
def accept_completion() -> None:
"""Accept a selected completion."""
buffer = get_app().current_buffer
complete_state = buffer.complete_state
if complete_state and isinstance(complete_state.current_completion, Completion):
buffer.apply_completion(complete_state.current_completion)
get_app().layout.focus(buffer) | Accept a selected completion. |
6,926 | from __future__ import annotations
import logging
import weakref
from abc import ABCMeta, abstractmethod
from math import ceil
from typing import TYPE_CHECKING
from prompt_toolkit.cache import FastDictCache, SimpleCache
from prompt_toolkit.data_structures import Point
from prompt_toolkit.filters.app import has_completions
from prompt_toolkit.filters.base import Condition
from prompt_toolkit.filters.utils import to_filter
from prompt_toolkit.formatted_text.base import to_formatted_text
from prompt_toolkit.formatted_text.utils import split_lines
from prompt_toolkit.layout.containers import Float, Window
from prompt_toolkit.layout.controls import GetLinePrefixCallable, UIContent, UIControl
from prompt_toolkit.layout.mouse_handlers import MouseHandlers
from prompt_toolkit.layout.screen import Char, WritePosition
from prompt_toolkit.utils import get_cwidth
from euporie.core.convert.datum import Datum
from euporie.core.convert.registry import find_route
from euporie.core.current import get_app
from euporie.core.data_structures import DiInt
from euporie.core.filters import has_dialog, has_menus, in_mplex
from euporie.core.ft.utils import _ZERO_WIDTH_FRAGMENTS
from euporie.core.layout.scroll import BoundedWritePosition
from euporie.core.terminal import passthrough
class GraphicControl(UIControl, metaclass=ABCMeta):
"""A base-class for display controls which render terminal graphics."""
def __init__(
self,
datum: Datum,
scale: float = 0,
bbox: DiInt | None = None,
) -> None:
"""Initialize the graphic control."""
self.app = get_app()
self.datum = datum
self.scale = scale
self.bbox = bbox or DiInt(0, 0, 0, 0)
self.rendered_lines: list[StyleAndTextTuples] = []
self._content_cache: SimpleCache = SimpleCache(maxsize=50)
self._format_cache: SimpleCache = SimpleCache(maxsize=50)
def preferred_width(self, max_available_width: int) -> int | None:
"""Return the width of the rendered content."""
cols, _aspect = self.datum.cell_size()
return min(cols, max_available_width) if cols else max_available_width
def preferred_height(
self,
width: int,
max_available_height: int,
wrap_lines: bool,
get_line_prefix: GetLinePrefixCallable | None,
) -> int:
"""Return the number of lines in the rendered content."""
cols, aspect = self.datum.cell_size()
if aspect:
return ceil(min(width, cols) * aspect)
self.rendered_lines = self.get_rendered_lines(width, max_available_height)
return len(self.rendered_lines)
def convert_data(self, wp: WritePosition) -> str:
"""Convert datum to required format."""
return ""
def get_rendered_lines(
self, width: int, height: int, wrap_lines: bool = False
) -> list[StyleAndTextTuples]:
"""Render the output data."""
return []
def create_content(self, width: int, height: int) -> UIContent:
"""Generate rendered output at a given size.
Args:
width: The desired output width
height: The desired output height
Returns:
`UIContent` for the given output size.
"""
max_cols, aspect = self.datum.cell_size()
bbox = self.bbox
cols = min(max_cols, width) if max_cols else width
rows = ceil(cols * aspect) - bbox.top - bbox.bottom if aspect else height
def get_content() -> dict[str, Any]:
rendered_lines = self.get_rendered_lines(width=cols, height=rows)
self.rendered_lines = rendered_lines[:]
line_count = len(rendered_lines)
def get_line(i: int) -> StyleAndTextTuples:
# Return blank lines if the renderer expects more content than we have
line = []
if i < line_count:
line += rendered_lines[i]
# Add a space at the end, because that is a possible cursor position.
# This is what PTK does, and fixes a nasty bug which took me ages to
# track down the source of, where scrolling would stop working when the
# cursor was on an empty line.
line += [("", " ")]
return line
return {
"get_line": get_line,
"line_count": line_count,
"menu_position": Point(0, 0),
}
# Re-render if the image width changes, or the terminal character size changes
key = (
cols,
rows,
self.app.color_palette,
self.app.term_info.cell_size_px,
self.bbox,
)
return UIContent(
**self._content_cache.get(key, get_content),
)
def hide(self) -> None:
"""Hide the graphic from show."""
def close(self) -> None:
"""Remove the displayed object entirely."""
if not self.app.leave_graphics():
self.hide()
class SixelGraphicControl(GraphicControl):
"""A graphic control which displays images as sixels."""
def convert_data(self, wp: WritePosition) -> str:
"""Convert datum to required format."""
bbox = wp.bbox if isinstance(wp, BoundedWritePosition) else DiInt(0, 0, 0, 0)
full_width = wp.width + bbox.left + bbox.right
full_height = wp.height + bbox.top + bbox.bottom
cmd = str(
self.datum.convert(
to="sixel",
cols=full_width,
rows=full_height,
)
)
if any(self.bbox):
from sixelcrop import sixelcrop
cell_size_x, cell_size_y = self.app.term_info.cell_size_px
cmd = sixelcrop(
data=cmd,
# Horizontal pixel offset of the displayed image region
x=bbox.left * cell_size_x,
# Vertical pixel offset of the displayed image region
y=bbox.top * cell_size_y,
# Pixel width of the displayed image region
w=wp.width * cell_size_x,
# Pixel height of the displayed image region
h=wp.height * cell_size_y,
)
return cmd
def get_rendered_lines(
self, width: int, height: int, wrap_lines: bool = False
) -> list[StyleAndTextTuples]:
"""Get rendered lines from the cache, or generate them."""
def render_lines() -> list[StyleAndTextTuples]:
"""Render the lines to display in the control."""
ft: list[StyleAndTextTuples] = []
if height:
cmd = self.convert_data(
BoundedWritePosition(0, 0, width, height, self.bbox)
)
ft.extend(
split_lines(
to_formatted_text(
[
# Move cursor down and across by image height and width
("", "\n".join((height) * [" " * (width)])),
# Save position, then move back
("[ZeroWidthEscape]", "\x1b[s"),
# Move cursor up if there is more than one line to display
*(
[("[ZeroWidthEscape]", f"\x1b[{height-1}A")]
if height > 1
else []
),
("[ZeroWidthEscape]", f"\x1b[{width}D"),
# Place the image without moving cursor
("[ZeroWidthEscape]", passthrough(cmd)),
# Restore the last known cursor position (at the bottom)
("[ZeroWidthEscape]", "\x1b[u"),
]
)
)
)
return ft
key = (
width,
self.app.color_palette,
self.app.term_info.cell_size_px,
self.bbox,
)
return self._format_cache.get(key, render_lines)
class ItermGraphicControl(GraphicControl):
"""A graphic control which displays images using iTerm's graphics protocol."""
def convert_data(self, wp: WritePosition) -> str:
"""Convert the graphic's data to base64 data."""
datum = self.datum
bbox = wp.bbox if isinstance(wp, BoundedWritePosition) else DiInt(0, 0, 0, 0)
full_width = wp.width + bbox.left + bbox.right
full_height = wp.height + bbox.top + bbox.bottom
# Crop image if necessary
if any(bbox):
import io
image = datum.convert(
to="pil",
cols=full_width,
rows=full_height,
)
if image is not None:
cell_size_x, cell_size_y = self.app.term_info.cell_size_px
# Downscale image to fit target region for precise cropping
image.thumbnail((full_width * cell_size_x, full_height * cell_size_y))
left = self.bbox.left * cell_size_x
top = self.bbox.top * cell_size_y
right = (self.bbox.left + wp.width) * cell_size_x
bottom = (self.bbox.top + wp.height) * cell_size_y
upper, lower = sorted((top, bottom))
image = image.crop((left, upper, right, lower))
with io.BytesIO() as output:
image.save(output, format="PNG")
datum = Datum(data=output.getvalue(), format="png")
if datum.format.startswith("base64-"):
b64data = datum.data
else:
b64data = datum.convert(
to="base64-png",
cols=full_width,
rows=full_height,
)
return b64data.replace("\n", "").strip()
def get_rendered_lines(
self, width: int, height: int, wrap_lines: bool = False
) -> list[StyleAndTextTuples]:
"""Get rendered lines from the cache, or generate them."""
def render_lines() -> list[StyleAndTextTuples]:
"""Render the lines to display in the control."""
ft: list[StyleAndTextTuples] = []
if height:
b64data = self.convert_data(
BoundedWritePosition(0, 0, width, height, self.bbox)
)
cmd = f"\x1b]1337;File=inline=1;width={width}:{b64data}\a"
ft.extend(
split_lines(
to_formatted_text(
[
# Move cursor down and across by image height and width
("", "\n".join((height) * [" " * (width)])),
# Save position, then move back
("[ZeroWidthEscape]", "\x1b[s"),
# Move cursor up if there is more than one line to display
*(
[("[ZeroWidthEscape]", f"\x1b[{height-1}A")]
if height > 1
else []
),
("[ZeroWidthEscape]", f"\x1b[{width}D"),
# Place the image without moving cursor
("[ZeroWidthEscape]", passthrough(cmd)),
# Restore the last known cursor position (at the bottom)
("[ZeroWidthEscape]", "\x1b[u"),
]
)
)
)
return ft
key = (
width,
self.app.color_palette,
self.app.term_info.cell_size_px,
self.bbox,
)
return self._format_cache.get(key, render_lines)
class KittyGraphicControl(GraphicControl):
"""A graphic control which displays images using Kitty's graphics protocol."""
_kitty_image_count: ClassVar[int] = 1
def __init__(
self,
datum: Datum,
scale: float = 0,
bbox: DiInt | None = None,
) -> None:
"""Create a new kitty graphic instance."""
super().__init__(datum=datum, scale=scale, bbox=bbox)
self.kitty_image_id = 0
self.loaded = False
self._datum_pad_cache: FastDictCache[
tuple[Datum, int, int], Datum
] = FastDictCache(get_value=self._pad_datum, size=1)
def _pad_datum(self, datum: Datum, cell_size_x: int, cell_size_y: int) -> Datum:
from PIL import ImageOps
px, py = datum.pixel_size()
if px and py:
target_width = int((px + cell_size_x - 1) // cell_size_x * cell_size_x)
target_height = int((py + cell_size_y - 1) // cell_size_y * cell_size_y)
image = ImageOps.pad(
datum.convert("pil").convert("RGBA"),
(target_width, target_height),
centering=(0, 0),
)
datum = Datum(
image,
format="pil",
px=target_width,
py=target_height,
path=datum.path,
align=datum.align,
)
return datum
def convert_data(self, wp: WritePosition) -> str:
"""Convert the graphic's data to base64 data for kitty graphics protocol."""
bbox = wp.bbox if isinstance(wp, BoundedWritePosition) else DiInt(0, 0, 0, 0)
full_width = wp.width + bbox.left + bbox.right
full_height = wp.height + bbox.top + bbox.bottom
datum = self._datum_pad_cache[(self.datum, *self.app.term_info.cell_size_px)]
return str(
datum.convert(
to="base64-png",
cols=full_width,
rows=full_height,
)
).replace("\n", "")
def _kitty_cmd(chunk: str = "", **params: Any) -> str:
param_str = ",".join(
[f"{key}={value}" for key, value in params.items() if value is not None]
)
cmd = f"\x1b_G{param_str}"
if chunk:
cmd += f";{chunk}"
cmd += "\x1b\\"
return cmd
def load(self, rows: int, cols: int) -> None:
"""Send the graphic to the terminal without displaying it."""
# global _kitty_image_count
data = self.convert_data(
BoundedWritePosition(0, 0, width=cols, height=rows, bbox=self.bbox)
)
self.kitty_image_id = self._kitty_image_count
KittyGraphicControl._kitty_image_count += 1
while data:
chunk, data = data[:4096], data[4096:]
cmd = self._kitty_cmd(
chunk=chunk,
a="t", # We are sending an image without displaying it
t="d", # Transferring the image directly
i=self.kitty_image_id, # Send a unique image number, wait for an image id
# I=self.kitty_image_number, # Send a unique image number, wait for an image id
p=1, # Placement ID
q=2, # No chatback
f=100, # Sending a PNG image
C=1, # Do not move the cursor
m=1 if data else 0, # Data will be chunked
)
self.app.output.write_raw(passthrough(cmd))
self.app.output.flush()
self.loaded = True
def hide(self) -> None:
"""Hide the graphic from show without deleting it."""
if self.kitty_image_id > 0:
self.app.output.write_raw(
passthrough(
self._kitty_cmd(
a="d",
d="i",
i=self.kitty_image_id,
q=1,
)
)
)
self.app.output.flush()
def delete(self) -> None:
"""Delete the graphic from the terminal."""
if self.kitty_image_id > 0:
self.app.output.write_raw(
passthrough(
self._kitty_cmd(
a="D",
d="I",
i=self.kitty_image_id,
q=2,
)
)
)
self.app.output.flush()
self.loaded = False
def get_rendered_lines(
self, width: int, height: int, wrap_lines: bool = False
) -> list[StyleAndTextTuples]:
"""Get rendered lines from the cache, or generate them."""
# TODO - wezterm does not scale kitty graphics, so we might want to resize
# images at this point rather than just loading them once
if not self.loaded:
self.load(cols=width, rows=height)
cell_size_px = self.app.term_info.cell_size_px
datum = self._datum_pad_cache[(self.datum, *cell_size_px)]
px, py = datum.pixel_size()
px = px or 100
py = py or 100
def render_lines() -> list[StyleAndTextTuples]:
"""Render the lines to display in the control."""
ft: list[StyleAndTextTuples] = []
if height:
full_width = width + self.bbox.left + self.bbox.right
full_height = height + self.bbox.top + self.bbox.bottom
cmd = self._kitty_cmd(
a="p", # Display a previously transmitted image
i=self.kitty_image_id,
p=1, # Placement ID
m=0, # No batches remaining
q=2, # No backchat
c=width,
r=height,
C=1, # 1 = Do move the cursor
# Horizontal pixel offset of the displayed image region
x=int(px * self.bbox.left / full_width),
# Vertical pixel offset of the displayed image region
y=int(py * self.bbox.top / full_height),
# Pixel width of the displayed image region
w=int(px * width / full_width),
# Pixel height of the displayed image region
h=int(py * height / full_height),
# z=-(2**30) - 1,
)
ft.extend(
split_lines(
to_formatted_text(
[
# Move cursor down and acoss by image height and width
("", "\n".join((height) * [" " * (width)])),
# Save position, then move back
("[ZeroWidthEscape]", "\x1b[s"),
# Move cursor up if there is more than one line to display
*(
[("[ZeroWidthEscape]", f"\x1b[{height-1}A")]
if height > 1
else []
),
("[ZeroWidthEscape]", f"\x1b[{width}D"),
# Place the image without moving cursor
("[ZeroWidthEscape]", passthrough(cmd)),
# Restore the last known cursor position (at the bottom)
("[ZeroWidthEscape]", "\x1b[u"),
]
)
)
)
return ft
key = (
width,
self.app.color_palette,
self.app.term_info.cell_size_px,
self.bbox,
)
return self._format_cache.get(key, render_lines)
def reset(self) -> None:
"""Hide and delete the kitty graphic from the terminal."""
self.hide()
self.delete()
super().reset()
def close(self) -> None:
"""Remove the displayed object entirely."""
super().close()
if not self.app.leave_graphics():
self.delete()
def find_route(from_: str, to: str) -> list | None:
"""Find the shortest conversion path between two formats."""
if from_ == to:
return [from_]
chains = []
def find(start: str, chain: list[str]) -> None:
if chain[0] == start:
chains.append(chain)
sources: dict[str, list[Converter]] = converters.get(chain[0], {})
for link in sources:
if link not in chain and any(
_FILTER_CACHE.get((conv,), conv.filter_)
for conv in sources.get(link, [])
):
find(start, [link, *chain])
find(from_, [to])
if chains:
# Find chain with shortest weighted length
return sorted(
chains,
key=lambda chain: sum(
[
min(
[
conv.weight
for conv in converters.get(step_b, {}).get(step_a, [])
if _FILTER_CACHE.get((conv,), conv.filter_)
]
)
for step_a, step_b in zip(chain, chain[1:])
]
),
)
else:
return None
def get_app() -> BaseApp:
"""Get the current active (running) Application."""
from euporie.core.app import BaseApp
session = _current_app_session.get()
if isinstance(session.app, BaseApp):
return session.app
# Use a baseapp as our "DummyApplication"
return BaseApp()
in_mplex = in_tmux | in_screen
The provided code snippet includes necessary dependencies for implementing the `select_graphic_control` function. Write a Python function `def select_graphic_control(format_: str) -> type[GraphicControl] | None` to solve the following problem:
Determine which graphic control to use.
Here is the function:
def select_graphic_control(format_: str) -> type[GraphicControl] | None:
"""Determine which graphic control to use."""
SelectedGraphicControl: type[GraphicControl] | None = None
app = get_app()
term_info = app.term_info
preferred_graphics_protocol = app.config.graphics
useable_graphics_controls: list[type[GraphicControl]] = []
_in_mplex = in_mplex()
force_graphics = app.config.force_graphics
if preferred_graphics_protocol != "none":
if (term_info.iterm_graphics_status.value or force_graphics) and find_route(
format_, "base64-png"
):
useable_graphics_controls.append(ItermGraphicControl)
if (
preferred_graphics_protocol == "iterm"
and ItermGraphicControl in useable_graphics_controls
# Iterm does not work in mplex without pass-through
and (not _in_mplex or (_in_mplex and app.config.mplex_graphics))
):
SelectedGraphicControl = ItermGraphicControl
elif (
(term_info.kitty_graphics_status.value or force_graphics)
and find_route(format_, "base64-png")
# Kitty does not work in mplex without pass-through
and (not _in_mplex or (_in_mplex and app.config.mplex_graphics))
):
useable_graphics_controls.append(KittyGraphicControl)
if (
preferred_graphics_protocol == "kitty"
and KittyGraphicControl in useable_graphics_controls
):
SelectedGraphicControl = KittyGraphicControl
# Tmux now supports sixels (>=3.4)
elif (term_info.sixel_graphics_status.value or force_graphics) and find_route(
format_, "sixel"
):
useable_graphics_controls.append(SixelGraphicControl)
if (
preferred_graphics_protocol == "sixel"
and SixelGraphicControl in useable_graphics_controls
):
SelectedGraphicControl = SixelGraphicControl
if SelectedGraphicControl is None and useable_graphics_controls:
SelectedGraphicControl = useable_graphics_controls[0]
return SelectedGraphicControl | Determine which graphic control to use. |
6,927 | from __future__ import annotations
import logging
import logging.config
import sys
import textwrap
from collections import deque
from io import StringIO
from pathlib import Path
from typing import TYPE_CHECKING, ClassVar
from prompt_toolkit.application.current import get_app_session
from prompt_toolkit.formatted_text.base import FormattedText
from prompt_toolkit.output.defaults import create_output
from prompt_toolkit.renderer import (
print_formatted_text as renderer_print_formatted_text,
)
from prompt_toolkit.shortcuts.utils import print_formatted_text
from prompt_toolkit.styles.pygments import style_from_pygments_cls
from prompt_toolkit.styles.style import Style, merge_styles
from pygments.styles import get_style_by_name
from euporie.core.config import add_setting
from euporie.core.ft.utils import indent, lex, wrap
from euporie.core.io import PseudoTTY
from euporie.core.style import LOG_STYLE
from euporie.core.utils import dict_merge
log = logging.getLogger(__name__)
The provided code snippet includes necessary dependencies for implementing the `add_log_level` function. Write a Python function `def add_log_level(name: str, number: int) -> None` to solve the following problem:
Add a new level to the logger.
Here is the function:
def add_log_level(name: str, number: int) -> None:
"""Add a new level to the logger."""
level_name = name.upper()
method_name = name.lower()
if not hasattr(logging, level_name):
def _log_for_level(
self: logging.Logger, message: str, *args: Any, **kwargs: Any
) -> None:
if self.isEnabledFor(number):
self._log(number, message, args, **kwargs)
def _log_to_root(message: str, *args: Any, **kwargs: Any) -> None:
logging.log(number, message, *args, **kwargs)
logging.addLevelName(number, level_name)
setattr(logging, level_name, number)
setattr(logging.getLoggerClass(), method_name, _log_for_level)
setattr(logging, method_name, _log_to_root) | Add a new level to the logger. |
6,928 | from __future__ import annotations
import logging
import logging.config
import sys
import textwrap
from collections import deque
from io import StringIO
from pathlib import Path
from typing import TYPE_CHECKING, ClassVar
from prompt_toolkit.application.current import get_app_session
from prompt_toolkit.formatted_text.base import FormattedText
from prompt_toolkit.output.defaults import create_output
from prompt_toolkit.renderer import (
print_formatted_text as renderer_print_formatted_text,
)
from prompt_toolkit.shortcuts.utils import print_formatted_text
from prompt_toolkit.styles.pygments import style_from_pygments_cls
from prompt_toolkit.styles.style import Style, merge_styles
from pygments.styles import get_style_by_name
from euporie.core.config import add_setting
from euporie.core.ft.utils import indent, lex, wrap
from euporie.core.io import PseudoTTY
from euporie.core.style import LOG_STYLE
from euporie.core.utils import dict_merge
LOG_QUEUE: deque = deque(maxlen=1000)
class FormattedTextHandler(logging.StreamHandler):
"""Format log records for display on the standard output."""
formatter: FtFormatter
def __init__(
self,
stream: str | TextIO | PseudoTTY | None = None,
share_stream: bool = True,
style: BaseStyle | None = None,
pygments_theme: str = "euporie",
) -> None:
"""Create a new log handler instance."""
# If a filename string is passed, open it as a stream
if isinstance(stream, str):
# We fake a TTY so we can output color
stream = PseudoTTY(open(stream, "a")) # noqa: SIM115,PTH123
super().__init__(stream)
self.share_stream = share_stream
self.style = style or merge_styles(
[
style_from_pygments_cls(get_style_by_name(pygments_theme)),
style or Style(LOG_STYLE),
]
)
self.output = create_output(stdout=self.stream)
def ft_format(self, record: logging.LogRecord) -> FormattedText:
"""Format the specified record."""
if self.formatter is not None:
return self.formatter.ft_format(record, width=self.output.get_size()[1])
else:
return FormattedText([])
def emit(self, record: logging.LogRecord) -> None:
"""Emit a formatted record."""
try:
msg = self.ft_format(record)
if self.share_stream:
print_formatted_text(
msg,
end="",
style=self.style,
output=self.output,
include_default_pygments_style=False,
)
else:
renderer_print_formatted_text(
output=self.output,
formatted_text=msg,
style=self.style,
)
except RecursionError:
raise
except Exception:
self.handleError(record)
class QueueHandler(logging.Handler):
"""This handler store logs events into a queue."""
formatter: FtFormatter
hook_id = 0
hooks: ClassVar[dict[int, Callable]] = {}
def __init__(
self,
*args: Any,
queue: deque,
style: Style | None = None,
**kwargs: Any,
) -> None:
"""Initialize an instance, using the passed queue."""
logging.Handler.__init__(self, *args, **kwargs)
self.queue = queue
self.style = style or Style(LOG_STYLE)
def emit(self, record: logging.LogRecord) -> None:
"""Queue unformatted records, as they will be formatted when accessed."""
message = self.formatter.ft_format(record)
self.queue.append(message)
for hook in self.hooks.values():
if callable(hook):
hook(message)
def hook(cls, hook: Callable) -> int:
"""Add a hook to run after each log entry.
Args:
hook: The hook function to add
Returns:
The hook id
"""
hook_id = cls.hook_id
cls.hook_id += 1
cls.hooks[hook_id] = hook
return hook_id
def unhook(cls, hook_id: int) -> None:
"""Remove a hook function.
Args:
hook_id: The ID of the hook function to remove
"""
if hook_id in cls.hooks:
del cls.hooks[hook_id]
class LogTabFormatter(FtFormatter):
"""Format log messages for display in the log view tab."""
def ft_format(
self, record: logging.LogRecord, width: int | None = None
) -> FormattedText:
"""Format a log record as formatted text."""
record = self.prepare(record)
output: StyleAndTextTuples = [
("", "["),
("class:pygments.literal.date", f"{record.asctime}"),
("", "] ["),
(f"class:log.level.{record.levelname}", f"{record.levelname}"),
("", "] ["),
("class:pygments.comment", f"{record.name}"),
("", "] "),
("class:log,msg", record.message),
("", "\n"),
]
if record.exc_text:
output += [*self.format_traceback(record.exc_text), ("", "\n")]
return FormattedText(output)
class StdoutFormatter(FtFormatter):
"""A log formatter for formatting log entries for display on the standard output."""
def __init__(self, *args: Any, **kwargs: Any) -> None:
"""Create a new formatter instance."""
super().__init__(*args, **kwargs)
self.last_date: str | None = None
def ft_format(
self, record: logging.LogRecord, width: int | None = None
) -> FormattedText:
"""Format log records for display on the standard output."""
if width is None:
width = get_app_session().output.get_size()[1]
record = self.prepare(record)
# path_name = Path(record.pathname).name
date = f"{record.asctime}"
if date == self.last_date:
date = " " * len(date)
else:
self.last_date = date
# ref = f"{path_name}:{record.lineno}"
ref = f"{record.name}.{record.funcName}:{record.lineno}"
msg_pad = len(date) + 10
msg_pad_1st_line = msg_pad + 1 + len(ref)
msg_lines = textwrap.wrap(
record.message,
width=width,
initial_indent=" " * msg_pad_1st_line,
subsequent_indent=" " * msg_pad,
)
output: StyleAndTextTuples = [
("class:pygments.literal.date", date),
("", " " * (9 - len(record.levelname))),
(f"class:log.level.{record.levelname}", record.levelname),
("", " "),
(
"class:pygments.text",
msg_lines[0].strip().ljust(width - msg_pad_1st_line),
),
("", " "),
("class:pygments.comment", ref),
]
for line in msg_lines[1:]:
output += [
("", "\n"),
("class:log,msg", line),
]
if record.exc_text:
output += indent(
wrap(
self.format_traceback(record.exc_text),
width=width - msg_pad,
margin=" ",
),
margin=" " * msg_pad,
)
output += [("", "\n")]
return FormattedText(output)
def handle_exception(
exc_type: type[BaseException],
exc_value: BaseException,
exc_traceback: TracebackType | None,
) -> Any:
"""Log unhandled exceptions and their tracebacks in the log.
Args:
exc_type: The type of the exception
exc_value: The exception instance
exc_traceback: The associated traceback
"""
# Check the exception is not a keyboard interrupt (Ctrl+C) - if so, so not log it
if issubclass(exc_type, KeyboardInterrupt):
sys.__excepthook__(exc_type, exc_value, exc_traceback)
return
# Log the exception
log.critical("Uncaught exception", exc_info=(exc_type, exc_value, exc_traceback))
def dict_merge(target_dict: dict, input_dict: dict) -> None:
"""Merge the second dictionary onto the first."""
for k in input_dict:
if k in target_dict:
if isinstance(target_dict[k], dict) and isinstance(input_dict[k], dict):
dict_merge(target_dict[k], input_dict[k])
elif isinstance(target_dict[k], list) and isinstance(input_dict[k], list):
target_dict[k] = [*target_dict[k], *input_dict[k]]
else:
target_dict[k] = input_dict[k]
else:
target_dict[k] = input_dict[k]
class Config:
"""A configuration store."""
settings: ClassVar[dict[str, Setting]] = {}
conf_file_name = "config.json"
def __init__(self) -> None:
"""Create a new configuration object instance."""
self.app_name: str = "base"
self.app_cls: type[ConfigurableApp] | None = None
def _save(self, setting: Setting) -> None:
"""Save settings to user's configuration file."""
json_data = self.load_config_file()
json_data.setdefault(self.app_name, {})[setting.name] = setting.value
if self.valid_user:
log.debug("Saving setting `%s`", setting)
with self.config_file_path.open("w") as f:
json.dump(json_data, f, indent=2)
def load(self, cls: type[ConfigurableApp]) -> None:
"""Load the command line, environment, and user configuration."""
from euporie.core.log import setup_logs
self.app_cls = cls
self.app_name = cls.name
log.debug("Loading config for %s", self.app_name)
user_conf_dir = Path(user_config_dir(__app_name__, appauthor=None))
user_conf_dir.mkdir(exist_ok=True, parents=True)
self.config_file_path = (user_conf_dir / self.conf_file_name).with_suffix(
".json"
)
self.valid_user = True
config_maps = {
# Load command line arguments
"command line arguments": self.load_args(),
# Load app specific env vars
"app-specific environment variable": self.load_env(app_name=self.app_name),
# Load global env vars
"global environment variable": self.load_env(),
# Load app specific user config
"app-specific user configuration": self.load_user(app_name=self.app_name),
# Load global user config
"user configuration": self.load_user(),
}
set_values = ChainMap(*config_maps.values())
for name, setting in Config.settings.items():
if setting.name in set_values:
# Set value without triggering hooks
setting._value = set_values[name]
setting.event += self._save
# Set-up logs
setup_logs(self)
# Save a list of unknown configuration options so we can warn about them once
# the logs are configured
for map_name, map_values in config_maps.items():
for option_name in map_values.keys() - Config.settings.keys():
if not isinstance(set_values[option_name], dict):
log.warning(
"Configuration option '%s' not recognised in %s",
option_name,
map_name,
)
def schema(self) -> dict[str, Any]:
"""Return a JSON schema for the config."""
return {
"title": "Euporie Configuration",
"description": "A configuration for euporie",
"type": "object",
"properties": {name: item.schema for name, item in self.settings.items()},
}
def load_parser(self) -> argparse.ArgumentParser:
"""Construct an :py:class:`ArgumentParser`."""
parser = ArgumentParser(
description=self.app_cls.__doc__,
epilog=__copyright__,
allow_abbrev=True,
formatter_class=argparse.MetavarTypeHelpFormatter,
)
# Add options to the relevant subparsers
for setting in self.settings.values():
args, kwargs = setting.parser_args
parser.add_argument(*args, **kwargs)
return parser
def load_args(self) -> dict[str, Any]:
"""Attempt to load configuration settings from commandline flags."""
result = {}
# Parse known arguments
namespace, remainder = self.load_parser().parse_known_intermixed_args()
# Update argv to leave the remaining arguments for subsequent apps
sys.argv[1:] = remainder
# Validate arguments
for name, value in vars(namespace).items():
if value is not None:
# Convert to json and back to attain json types
json_data = json.loads(_json_encoder.encode({name: value}))
try:
fastjsonschema.validate(self.schema, json_data)
except fastjsonschema.JsonSchemaValueException as error:
log.warning("Error in command line parameter `%s`: %s", name, error)
log.warning("%s: %s", name, value)
else:
result[name] = value
return result
def load_env(self, app_name: str = "") -> dict[str, Any]:
"""Attempt to load configuration settings from environment variables."""
result = {}
for name, setting in self.settings.items():
if app_name:
env = f"{__app_name__.upper()}_{self.app_name.upper()}_{setting.name.upper()}"
else:
env = f"{__app_name__.upper()}_{setting.name.upper()}"
if env in os.environ:
value = os.environ.get(env)
parsed_value: Any = value
# Attempt to parse the value as a literal
if value:
try:
parsed_value = literal_eval(value)
except (
ValueError,
TypeError,
SyntaxError,
MemoryError,
RecursionError,
):
pass
# Attempt to cast the value to the desired type
try:
parsed_value = setting.type(value)
except (ValueError, TypeError):
log.warning(
"Environment variable `%s` not understood" " - `%s` expected",
env,
setting.type.__name__,
)
else:
json_data = json.loads(_json_encoder.encode({name: parsed_value}))
try:
fastjsonschema.validate(self.schema, json_data)
except fastjsonschema.JsonSchemaValueException as error:
log.error("Error in environment variable: `%s`\n%s", env, error)
else:
result[name] = parsed_value
return result
def load_config_file(self) -> dict[str, Any]:
"""Attempt to load JSON configuration file."""
results = {}
assert isinstance(self.config_file_path, Path)
if self.valid_user and self.config_file_path.exists():
with self.config_file_path.open() as f:
try:
json_data = json.load(f)
except json.decoder.JSONDecodeError:
log.error(
"Could not parse the configuration file: %s\nIs it valid json?",
self.config_file_path,
)
self.valid_user = False
else:
results.update(json_data)
return results
def load_user(self, app_name: str = "") -> dict[str, Any]:
"""Attempt to load JSON configuration file."""
results = {}
# Load config file
json_data = self.load_config_file()
# Load section for the current app
if app_name:
json_data = json_data.get(self.app_name, {})
# Validate the configuration file
try:
# Validate a copy so the original data is not modified
fastjsonschema.validate(self.schema, dict(json_data))
except fastjsonschema.JsonSchemaValueException as error:
log.warning("Error in config file: `%s`: %s", self.config_file_pathi, error)
self.valid_user = False
else:
results.update(json_data)
return results
def get(self, name: str, default: Any = None) -> Any:
"""Access a configuration value, falling back to the default value if unset.
Args:
name: The name of the attribute to access.
default: The value to return if the name is not found
Returns:
The configuration variable value.
"""
if name in self.settings:
return self.settings[name].value
else:
return default
def get_item(self, name: str) -> Any:
"""Access a configuration item.
Args:
name: The name of the attribute to access.
Returns:
The configuration item.
"""
return self.settings.get(name)
def filter(self, name: str) -> Filter:
"""Return a :py:class:`Filter` for a configuration item."""
return Condition(partial(self.get, name))
def __getattr__(self, name: str) -> Any:
"""Enable access of config elements via dotted attributes.
Args:
name: The name of the attribute to access.
Returns:
The configuration variable value.
"""
return self.get(name)
def __setitem__(self, name: str, value: Any) -> None:
"""Set a configuration attribute.
Args:
name: The name of the attribute to set.
value: The value to give the attribute.
"""
setting = self.settings[name]
setting.value = value
The provided code snippet includes necessary dependencies for implementing the `setup_logs` function. Write a Python function `def setup_logs(config: Config | None = None) -> None` to solve the following problem:
Configure the logger for euporie.
Here is the function:
def setup_logs(config: Config | None = None) -> None:
"""Configure the logger for euporie."""
# Add custom log levels
# add_log_level("kernelio", logging.WARNING - 1)
# add_log_level("kernel", logging.INFO - 1)
# add_log_level("convert", logging.INFO - 2)
# add_log_level("ui", logging.INFO - 3)
# Default log config
log_config: dict[str, Any] = {
"version": 1,
"disable_existing_loggers": False,
"formatters": {
"file_format": {
"format": "{asctime}.{msecs:03.0f} {levelname:<7} [{name}.{funcName}:{lineno}] {message}",
"style": "{",
"datefmt": "%Y-%m-%d %H:%M:%S",
},
"stdout_format": {
"()": StdoutFormatter,
},
"log_tab_format": {
"()": LogTabFormatter,
},
},
"handlers": {
"stdout": {
"level": "INFO",
"()": FormattedTextHandler,
"formatter": "stdout_format",
"stream": sys.stdout,
},
"log_tab": {
"level": "INFO",
"()": QueueHandler,
"formatter": "log_tab_format",
"queue": LOG_QUEUE,
},
},
"loggers": {
"euporie": {
"level": "INFO",
"handlers": ["log_tab", "stdout"],
"propagate": False,
},
},
# Log everything to the internal logger
"root": {"handlers": ["log_tab"]},
}
if config is not None:
log_file = config.get("log_file", "")
log_file_is_stdout = log_file in {"-", "/dev/stdout"}
log_level = config.log_level.upper()
# Configure file handler
if log_file and not log_file_is_stdout:
log_config["handlers"]["file"] = {
"level": log_level,
"class": "logging.FileHandler",
"filename": Path(config.log_file).expanduser(),
"formatter": "file_format",
}
log_config["loggers"]["euporie"]["handlers"].append("file")
# Configure stdout handler
if log_file_is_stdout:
stdout_level = log_level
elif (app_cls := config.app_cls) is not None and (
log_stdout_level := app_cls.log_stdout_level
):
stdout_level = log_stdout_level.upper()
else:
stdout_level = "CRITICAL"
log_config["handlers"]["stdout"]["level"] = stdout_level
if syntax_theme := config.get("syntax_theme"):
log_config["handlers"]["stdout"]["pygments_theme"] = syntax_theme
# Configure euporie logger
log_config["loggers"]["euporie"]["level"] = config.log_level.upper()
# Update log_config based on additional config dict provided
if config.log_config:
import json
extra_config = json.loads(config.log_config)
dict_merge(log_config, extra_config)
# Configure the logger
# Pytype used TypedDicts to validate the dictionary structure, but I cannot get
# this to work for some reason...
logging.config.dictConfig(log_config) # type: ignore
# Capture warnings so they show up in the logs
logging.captureWarnings(True)
# Log uncaught exceptions
sys.excepthook = handle_exception | Configure the logger for euporie. |
6,929 | from __future__ import annotations
from enum import Enum
from functools import lru_cache, total_ordering
from typing import NamedTuple
from prompt_toolkit.cache import FastDictCache
class Mask:
"""A mask which allows selection of a subset of a grid.
Masks can be combined to construct more complex masks.
"""
def __init__(self, mask: dict[GridPart, DirectionFlags]) -> None:
"""Create a new grid mask.
Args:
mask: A dictionary mapping grid parts to a tuple of direction flags.
Not all :class:`GridPart`s need to be defined - any which are not
defined are assumed to be set entirely to :cont:`False`.
"""
self.mask = {part: mask.get(part, DirectionFlags()) for part in GridPart}
def __add__(self, other: Mask) -> Mask:
"""Add two masks, combining direction flags for each :class:`GridPart`.
Args:
other: Another mask to combine with this one
Returns:
A new combined mask.
"""
return Mask(
{
key: DirectionFlags(
*(self.mask[key][i] | other.mask[key][i] for i in range(4))
)
for key in GridPart
}
)
class LineStyle:
"""Define a line style which can be used to draw grids.
:class:`GridStyle`s can be created from a :class:`LineStyle` by accessing an
attribute with the name of a default mask from :class:`Masks`.
"""
_grid_cache: FastDictCache[tuple[LineStyle, Mask], GridStyle] = FastDictCache(
get_value=_lint_to_grid
)
def __init__(
self,
name: str,
rank: tuple[int, int],
parent: LineStyle | None = None,
visible: bool = True,
) -> None:
"""Create a new :class:`LineStyle`.
Args:
name: The name of the line style
rank: A ranking value - this is used when two adjoining cells in a table
have differing widths or styles to determine which should take precedence.
The style with the higher rank is used. The rank consists of a tuple
representing width and fanciness.
parent: The :class:`LineStyle` from which this style should inherit if any
characters are undefined.
visible: A flag to indicate if the line is blank
"""
self.name = name
self.rank = rank
self.children: dict[str, LineStyle] = {}
self.parent = parent
self.visible = visible
if parent:
parent.children[name] = self
def __getattr__(self, value: str) -> GridStyle:
"""Define attribute access.
Allows dynamic access to children and :class:`GridStyle` creation via attribute
access.
Args:
value: The attribute name to access
Returns:
The accessed attribute
Raises:
AttributeError: Raised if there is no such attribute
"""
if hasattr(Masks, value):
mask = getattr(Masks, value)
return self._grid_cache[self, mask]
else:
raise AttributeError(f"No such attribute `{value}`")
def __dir__(self) -> list[str]:
"""List the public attributes."""
return [x for x in Masks.__dict__ if not x.startswith("_")]
def __lt__(self, other: LineStyle) -> bool:
"""Allow :class:`LineStyle`s to be sorted according to their rank."""
if self.__class__ is other.__class__:
return self.rank < other.rank
elif other is None:
return None
return NotImplemented
def __repr__(self) -> str:
"""Represent :class:`LineStyle` instances as a string."""
return f"LineStyle({self.name})"
class GridStyle:
"""A collection of characters which can be used to draw a grid."""
class _BorderLineChars(NamedTuple):
LEFT: str
MID: str
SPLIT: str
RIGHT: str
_grid_cache: FastDictCache[tuple[GridStyle, GridStyle], GridStyle] = FastDictCache(get_value=_combine_grids)
def __init__(
self, line_style: LineStyle = NoLine, mask: Mask = Masks.grid
) -> None:
"""Create a new :py:class:`GridStyle` instance.
Args:
line_style: The line style to use to construct the grid
mask: A mask which can be used to exclude certain character from the grid
"""
self.grid = {
part: GridChar(
*((line_style if x else NoLine) for x in mask.mask[part])
)
for part in GridPart
}
self.mask = mask
def TOP(self) -> _BorderLineChars:
"""Allow dotted attribute access to the top grid row."""
return self._BorderLineChars(
get_grid_char(self.grid[GridPart.TOP_LEFT]),
get_grid_char(self.grid[GridPart.TOP_MID]),
get_grid_char(self.grid[GridPart.TOP_SPLIT]),
get_grid_char(self.grid[GridPart.TOP_RIGHT]),
)
def MID(self) -> _BorderLineChars:
"""Allow dotted attribute access to the mid grid row."""
return self._BorderLineChars(
get_grid_char(self.grid[GridPart.MID_LEFT]),
get_grid_char(self.grid[GridPart.MID_MID]),
get_grid_char(self.grid[GridPart.MID_SPLIT]),
get_grid_char(self.grid[GridPart.MID_RIGHT]),
)
def SPLIT(self) -> _BorderLineChars:
"""Allow dotted attribute access to the split grid row."""
return self._BorderLineChars(
get_grid_char(self.grid[GridPart.SPLIT_LEFT]),
get_grid_char(self.grid[GridPart.SPLIT_MID]),
get_grid_char(self.grid[GridPart.SPLIT_SPLIT]),
get_grid_char(self.grid[GridPart.SPLIT_RIGHT]),
)
def BOTTOM(self) -> _BorderLineChars:
"""Allow dotted attribute access to the bottom grid row."""
return self._BorderLineChars(
get_grid_char(self.grid[GridPart.BOTTOM_LEFT]),
get_grid_char(self.grid[GridPart.BOTTOM_MID]),
get_grid_char(self.grid[GridPart.BOTTOM_SPLIT]),
get_grid_char(self.grid[GridPart.BOTTOM_RIGHT]),
)
def HORIZONTAL(self) -> str:
"""For compatibility with :class:`prompt_toolkit.widgets.base.Border`."""
return self.SPLIT_MID
def VERTICAL(self) -> str:
"""For compatibility with :class:`prompt_toolkit.widgets.base.Border`."""
return self.MID_SPLIT
def __getattr__(self, value: str) -> str:
"""Allow the parts of the grid to be accessed as attributes by name."""
key = getattr(GridPart, value)
return get_grid_char(self.grid[key])
def __dir__(self) -> list:
"""Lit the public attributes of the grid style."""
return [x.name for x in GridPart] + ["TOP", "MID", "SPLIT", "BOTTOM"]
def __add__(self, other: GridStyle) -> GridStyle:
"""Combine two grid styles."""
return self._grid_cache[self, other]
def __repr__(self) -> str:
"""Return a string representation of the grid style."""
return "\n".join(
"".join(
get_grid_char(char_key)
for char_key in list(self.grid.values())[i * 4 : (i + 1) * 4]
)
for i in range(4)
)
The provided code snippet includes necessary dependencies for implementing the `_lint_to_grid` function. Write a Python function `def _lint_to_grid(line: LineStyle, mask: Mask) -> GridStyle` to solve the following problem:
Get a grid from a line and a mask.
Here is the function:
def _lint_to_grid(line: LineStyle, mask: Mask) -> GridStyle:
"""Get a grid from a line and a mask."""
return GridStyle(line, mask) | Get a grid from a line and a mask. |
6,930 | from __future__ import annotations
from enum import Enum
from functools import lru_cache, total_ordering
from typing import NamedTuple
from prompt_toolkit.cache import FastDictCache
class GridPart(Enum):
"""Define the component characters of a grid.
Character naming works as follows:
╭┈┈┈┈┈┈┈┈LEFT
┊ ╭┈┈┈┈┈┈MID
┊ ┊ ╭┈┈┈┈SPLIT
┊ ┊ ┊ ╭┈┈RIGHT
∨ ∨ ∨ v
TOP┈> ┏ ━ ┳ ┓
MID┈> ┃ ┃ ┃
SPLIT┈> ┣ ━ ╋ ┫
BOTTOM┈> ┗ ━ ┻ ┛
""" # noqa: RUF002
TOP_LEFT = 0
TOP_MID = 1
TOP_SPLIT = 2
TOP_RIGHT = 3
MID_LEFT = 4
MID_MID = 5
MID_SPLIT = 6
MID_RIGHT = 7
SPLIT_LEFT = 8
SPLIT_MID = 9
SPLIT_SPLIT = 10
SPLIT_RIGHT = 11
BOTTOM_LEFT = 12
BOTTOM_MID = 13
BOTTOM_SPLIT = 14
BOTTOM_RIGHT = 15
class GridChar(NamedTuple):
"""Repreentation of a grid node character.
The four compass points represent the line style joining from the given direction.
"""
north: LineStyle
east: LineStyle
south: LineStyle
west: LineStyle
class GridStyle:
"""A collection of characters which can be used to draw a grid."""
class _BorderLineChars(NamedTuple):
LEFT: str
MID: str
SPLIT: str
RIGHT: str
_grid_cache: FastDictCache[tuple[GridStyle, GridStyle], GridStyle] = FastDictCache(get_value=_combine_grids)
def __init__(
self, line_style: LineStyle = NoLine, mask: Mask = Masks.grid
) -> None:
"""Create a new :py:class:`GridStyle` instance.
Args:
line_style: The line style to use to construct the grid
mask: A mask which can be used to exclude certain character from the grid
"""
self.grid = {
part: GridChar(
*((line_style if x else NoLine) for x in mask.mask[part])
)
for part in GridPart
}
self.mask = mask
def TOP(self) -> _BorderLineChars:
"""Allow dotted attribute access to the top grid row."""
return self._BorderLineChars(
get_grid_char(self.grid[GridPart.TOP_LEFT]),
get_grid_char(self.grid[GridPart.TOP_MID]),
get_grid_char(self.grid[GridPart.TOP_SPLIT]),
get_grid_char(self.grid[GridPart.TOP_RIGHT]),
)
def MID(self) -> _BorderLineChars:
"""Allow dotted attribute access to the mid grid row."""
return self._BorderLineChars(
get_grid_char(self.grid[GridPart.MID_LEFT]),
get_grid_char(self.grid[GridPart.MID_MID]),
get_grid_char(self.grid[GridPart.MID_SPLIT]),
get_grid_char(self.grid[GridPart.MID_RIGHT]),
)
def SPLIT(self) -> _BorderLineChars:
"""Allow dotted attribute access to the split grid row."""
return self._BorderLineChars(
get_grid_char(self.grid[GridPart.SPLIT_LEFT]),
get_grid_char(self.grid[GridPart.SPLIT_MID]),
get_grid_char(self.grid[GridPart.SPLIT_SPLIT]),
get_grid_char(self.grid[GridPart.SPLIT_RIGHT]),
)
def BOTTOM(self) -> _BorderLineChars:
"""Allow dotted attribute access to the bottom grid row."""
return self._BorderLineChars(
get_grid_char(self.grid[GridPart.BOTTOM_LEFT]),
get_grid_char(self.grid[GridPart.BOTTOM_MID]),
get_grid_char(self.grid[GridPart.BOTTOM_SPLIT]),
get_grid_char(self.grid[GridPart.BOTTOM_RIGHT]),
)
def HORIZONTAL(self) -> str:
"""For compatibility with :class:`prompt_toolkit.widgets.base.Border`."""
return self.SPLIT_MID
def VERTICAL(self) -> str:
"""For compatibility with :class:`prompt_toolkit.widgets.base.Border`."""
return self.MID_SPLIT
def __getattr__(self, value: str) -> str:
"""Allow the parts of the grid to be accessed as attributes by name."""
key = getattr(GridPart, value)
return get_grid_char(self.grid[key])
def __dir__(self) -> list:
"""Lit the public attributes of the grid style."""
return [x.name for x in GridPart] + ["TOP", "MID", "SPLIT", "BOTTOM"]
def __add__(self, other: GridStyle) -> GridStyle:
"""Combine two grid styles."""
return self._grid_cache[self, other]
def __repr__(self) -> str:
"""Return a string representation of the grid style."""
return "\n".join(
"".join(
get_grid_char(char_key)
for char_key in list(self.grid.values())[i * 4 : (i + 1) * 4]
)
for i in range(4)
)
The provided code snippet includes necessary dependencies for implementing the `_combine_grids` function. Write a Python function `def _combine_grids(grid_a: GridStyle, grid_b: GridStyle) -> GridStyle` to solve the following problem:
Combine a pair of grids.
Here is the function:
def _combine_grids(grid_a: GridStyle, grid_b: GridStyle) -> GridStyle:
"""Combine a pair of grids."""
grid_style = GridStyle()
grid_style.grid = {}
for part in GridPart:
grid_style.grid[part] = GridChar(
*(max(grid_a.grid[part][i], grid_b.grid[part][i]) for i in range(4))
)
return grid_style | Combine a pair of grids. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.