| 1 |
from dataclasses import dataclass |
| 2 |
from inspect import getsource |
| 3 |
from pathlib import Path |
| 4 |
from typing import cast, List, Union |
| 5 |
from html import escape as html_escape |
| 6 |
import re |
| 7 |
|
| 8 |
from prompt_toolkit.keys import KEY_ALIASES |
| 9 |
from prompt_toolkit.key_binding import KeyBindingsBase |
| 10 |
from prompt_toolkit.filters import Filter, Condition |
| 11 |
from prompt_toolkit.shortcuts import PromptSession |
| 12 |
|
| 13 |
from IPython.terminal.shortcuts import create_ipython_shortcuts, create_identifier |
| 14 |
from IPython.terminal.shortcuts.filters import KEYBINDING_FILTERS |
| 15 |
|
| 16 |
|
| 17 |
@dataclass |
| 18 |
class Shortcut: |
| 19 |
#: a sequence of keys (each element on the list corresponds to pressing one or more keys) |
| 20 |
keys_sequence: List[str] |
| 21 |
filter: str |
| 22 |
|
| 23 |
|
| 24 |
@dataclass |
| 25 |
class Handler: |
| 26 |
description: str |
| 27 |
identifier: str |
| 28 |
|
| 29 |
|
| 30 |
@dataclass |
| 31 |
class Binding: |
| 32 |
handler: Handler |
| 33 |
shortcut: Shortcut |
| 34 |
|
| 35 |
|
| 36 |
class _NestedFilter(Filter): |
| 37 |
"""Protocol reflecting non-public prompt_toolkit's `_AndList` and `_OrList`.""" |
| 38 |
|
| 39 |
filters: List[Filter] |
| 40 |
|
| 41 |
|
| 42 |
class _Invert(Filter): |
| 43 |
"""Protocol reflecting non-public prompt_toolkit's `_Invert`.""" |
| 44 |
|
| 45 |
filter: Filter |
| 46 |
|
| 47 |
|
| 48 |
conjunctions_labels = {"_AndList": "&", "_OrList": "|"} |
| 49 |
|
| 50 |
ATOMIC_CLASSES = {"Never", "Always", "Condition"} |
| 51 |
|
| 52 |
|
| 53 |
HUMAN_NAMES_FOR_FILTERS = { |
| 54 |
filter_: name for name, filter_ in KEYBINDING_FILTERS.items() |
| 55 |
} |
| 56 |
|
| 57 |
|
| 58 |
def format_filter( |
| 59 |
filter_: Union[Filter, _NestedFilter, Condition, _Invert], |
| 60 |
is_top_level=True, |
| 61 |
skip=None, |
| 62 |
) -> str: |
| 63 |
"""Create easily readable description of the filter.""" |
| 64 |
s = filter_.__class__.__name__ |
| 65 |
if s == "Condition": |
| 66 |
func = cast(Condition, filter_).func |
| 67 |
if filter_ in HUMAN_NAMES_FOR_FILTERS: |
| 68 |
return HUMAN_NAMES_FOR_FILTERS[filter_] |
| 69 |
name = func.__name__ |
| 70 |
if name == "<lambda>": |
| 71 |
source = getsource(func) |
| 72 |
return source.split("=")[0].strip() |
| 73 |
return func.__name__ |
| 74 |
elif s == "_Invert": |
| 75 |
operand = cast(_Invert, filter_).filter |
| 76 |
if operand.__class__.__name__ in ATOMIC_CLASSES: |
| 77 |
return f"~{format_filter(operand, is_top_level=False)}" |
| 78 |
return f"~({format_filter(operand, is_top_level=False)})" |
| 79 |
elif s in conjunctions_labels: |
| 80 |
filters = cast(_NestedFilter, filter_).filters |
| 81 |
if filter_ in HUMAN_NAMES_FOR_FILTERS: |
| 82 |
return HUMAN_NAMES_FOR_FILTERS[filter_] |
| 83 |
conjunction = conjunctions_labels[s] |
| 84 |
glue = f" {conjunction} " |
| 85 |
result = glue.join(format_filter(x, is_top_level=False) for x in filters) |
| 86 |
if len(filters) > 1 and not is_top_level: |
| 87 |
result = f"({result})" |
| 88 |
return result |
| 89 |
elif s in ["Never", "Always"]: |
| 90 |
return s.lower() |
| 91 |
elif s == "PassThrough": |
| 92 |
return "pass_through" |
| 93 |
else: |
| 94 |
raise ValueError(f"Unknown filter type: {filter_}") |
| 95 |
|
| 96 |
|
| 97 |
def sentencize(s) -> str: |
| 98 |
"""Extract first sentence""" |
| 99 |
s = re.split(r"\.\W", s.replace("\n", " ").strip()) |
| 100 |
s = s[0] if len(s) else "" |
| 101 |
if not s.endswith("."): |
| 102 |
s += "." |
| 103 |
try: |
| 104 |
return " ".join(s.split()) |
| 105 |
except AttributeError: |
| 106 |
return s |
| 107 |
|
| 108 |
|
| 109 |
class _DummyTerminal: |
| 110 |
"""Used as a buffer to get prompt_toolkit bindings""" |
| 111 |
|
| 112 |
handle_return = None |
| 113 |
input_transformer_manager = None |
| 114 |
display_completions = None |
| 115 |
editing_mode = "emacs" |
| 116 |
auto_suggest = None |
| 117 |
|
| 118 |
|
| 119 |
def bindings_from_prompt_toolkit(prompt_bindings: KeyBindingsBase) -> List[Binding]: |
| 120 |
"""Collect bindings to a simple format that does not depend on prompt-toolkit internals""" |
| 121 |
bindings: List[Binding] = [] |
| 122 |
|
| 123 |
for kb in prompt_bindings.bindings: |
| 124 |
bindings.append( |
| 125 |
Binding( |
| 126 |
handler=Handler( |
| 127 |
description=kb.handler.__doc__ or "", |
| 128 |
identifier=create_identifier(kb.handler), |
| 129 |
), |
| 130 |
shortcut=Shortcut( |
| 131 |
keys_sequence=[ |
| 132 |
str(k.value) if hasattr(k, "value") else k for k in kb.keys |
| 133 |
], |
| 134 |
filter=format_filter(kb.filter, skip={"has_focus_filter"}), |
| 135 |
), |
| 136 |
) |
| 137 |
) |
| 138 |
return bindings |
| 139 |
|
| 140 |
|
| 141 |
INDISTINGUISHABLE_KEYS = {**KEY_ALIASES, **{v: k for k, v in KEY_ALIASES.items()}} |
| 142 |
|
| 143 |
|
| 144 |
def format_prompt_keys(keys: str, add_alternatives=True) -> str: |
| 145 |
"""Format prompt toolkit key with modifier into an RST representation.""" |
| 146 |
|
| 147 |
def to_rst(key): |
| 148 |
escaped = key.replace("\\", "\\\\") |
| 149 |
return f":kbd:`{escaped}`" |
| 150 |
|
| 151 |
keys_to_press: List[str] |
| 152 |
|
| 153 |
prefixes = { |
| 154 |
"c-s-": [to_rst("ctrl"), to_rst("shift")], |
| 155 |
"s-c-": [to_rst("ctrl"), to_rst("shift")], |
| 156 |
"c-": [to_rst("ctrl")], |
| 157 |
"s-": [to_rst("shift")], |
| 158 |
} |
| 159 |
|
| 160 |
for prefix, modifiers in prefixes.items(): |
| 161 |
if keys.startswith(prefix): |
| 162 |
remainder = keys[len(prefix) :] |
| 163 |
keys_to_press = [*modifiers, to_rst(remainder)] |
| 164 |
break |
| 165 |
else: |
| 166 |
keys_to_press = [to_rst(keys)] |
| 167 |
|
| 168 |
result = " + ".join(keys_to_press) |
| 169 |
|
| 170 |
if keys in INDISTINGUISHABLE_KEYS and add_alternatives: |
| 171 |
alternative = INDISTINGUISHABLE_KEYS[keys] |
| 172 |
|
| 173 |
result = ( |
| 174 |
result |
| 175 |
+ " (or " |
| 176 |
+ format_prompt_keys(alternative, add_alternatives=False) |
| 177 |
+ ")" |
| 178 |
) |
| 179 |
|
| 180 |
return result |
| 181 |
|
| 182 |
|
| 183 |
if __name__ == "__main__": |
| 184 |
here = Path(__file__).parent |
| 185 |
dest = here / "source" / "config" / "shortcuts" |
| 186 |
|
| 187 |
ipy_bindings = create_ipython_shortcuts(_DummyTerminal()) |
| 188 |
|
| 189 |
session = PromptSession(key_bindings=ipy_bindings) |
| 190 |
prompt_bindings = session.app.key_bindings |
| 191 |
|
| 192 |
assert prompt_bindings |
| 193 |
# Ensure that we collected the default shortcuts |
| 194 |
assert len(prompt_bindings.bindings) > len(ipy_bindings.bindings) |
| 195 |
|
| 196 |
bindings = bindings_from_prompt_toolkit(prompt_bindings) |
| 197 |
|
| 198 |
def sort_key(binding: Binding): |
| 199 |
return binding.handler.identifier, binding.shortcut.filter |
| 200 |
|
| 201 |
filters = [] |
| 202 |
with (dest / "table.tsv").open("w", encoding="utf-8") as csv: |
| 203 |
for binding in sorted(bindings, key=sort_key): |
| 204 |
sequence = ", ".join( |
| 205 |
[format_prompt_keys(keys) for keys in binding.shortcut.keys_sequence] |
| 206 |
) |
| 207 |
if binding.shortcut.filter == "always": |
| 208 |
condition_label = "-" |
| 209 |
else: |
| 210 |
# we cannot fit all the columns as the filters got too complex over time |
| 211 |
condition_label = "ⓘ" |
| 212 |
|
| 213 |
csv.write( |
| 214 |
"\t".join( |
| 215 |
[ |
| 216 |
sequence, |
| 217 |
sentencize(binding.handler.description) |
| 218 |
+ f" :raw-html:`<br>` `{binding.handler.identifier}`", |
| 219 |
f':raw-html:`<span title="{html_escape(binding.shortcut.filter)}" style="cursor: help">{condition_label}</span>`', |
| 220 |
] |
| 221 |
) |
| 222 |
+ "\n" |
| 223 |
) |