summaryrefslogtreecommitdiffstats
path: root/examples/prompts/autocorrection.py
diff options
context:
space:
mode:
authorDaniel Baumann <daniel.baumann@progress-linux.org>2024-04-15 16:35:31 +0000
committerDaniel Baumann <daniel.baumann@progress-linux.org>2024-04-15 16:35:31 +0000
commit4f1a3b5f9ad05aa7b08715d48909a2b06ee2fcb1 (patch)
treee5dee7be2f0d963da4faad6517278d03783e3adc /examples/prompts/autocorrection.py
parentInitial commit. (diff)
downloadprompt-toolkit-4f1a3b5f9ad05aa7b08715d48909a2b06ee2fcb1.tar.xz
prompt-toolkit-4f1a3b5f9ad05aa7b08715d48909a2b06ee2fcb1.zip
Adding upstream version 3.0.43.upstream/3.0.43
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to 'examples/prompts/autocorrection.py')
-rwxr-xr-xexamples/prompts/autocorrection.py44
1 files changed, 44 insertions, 0 deletions
diff --git a/examples/prompts/autocorrection.py b/examples/prompts/autocorrection.py
new file mode 100755
index 0000000..6378132
--- /dev/null
+++ b/examples/prompts/autocorrection.py
@@ -0,0 +1,44 @@
+#!/usr/bin/env python
+"""
+Example of implementing auto correction while typing.
+
+The word "impotr" will be corrected when the user types a space afterwards.
+"""
+from prompt_toolkit import prompt
+from prompt_toolkit.key_binding import KeyBindings
+
+# Database of words to be replaced by typing.
+corrections = {
+ "impotr": "import",
+ "wolrd": "world",
+}
+
+
+def main():
+ # We start with a `KeyBindings` for our extra key bindings.
+ bindings = KeyBindings()
+
+ # We add a custom key binding to space.
+ @bindings.add(" ")
+ def _(event):
+ """
+ When space is pressed, we check the word before the cursor, and
+ autocorrect that.
+ """
+ b = event.app.current_buffer
+ w = b.document.get_word_before_cursor()
+
+ if w is not None:
+ if w in corrections:
+ b.delete_before_cursor(count=len(w))
+ b.insert_text(corrections[w])
+
+ b.insert_text(" ")
+
+ # Read input.
+ text = prompt("Say something: ", key_bindings=bindings)
+ print("You said: %s" % text)
+
+
+if __name__ == "__main__":
+ main()