From b0912d31f1a2cfea93a5588898cae0c652cd89d4 Mon Sep 17 00:00:00 2001
From: Marcus Müller <marcus@hostalia.de>
Date: Mon, 20 Nov 2017 13:42:30 +0100
Subject: Adding readline capabilities to gr_modtool

* main advantage: better line editing
* tab-completion for gr_modtool add
---
 gr-utils/python/modtool/util_functions.py | 27 +++++++++++++++++++++++++++
 1 file changed, 27 insertions(+)

(limited to 'gr-utils/python/modtool/util_functions.py')

diff --git a/gr-utils/python/modtool/util_functions.py b/gr-utils/python/modtool/util_functions.py
index 47799ac461..6bb95f3d67 100644
--- a/gr-utils/python/modtool/util_functions.py
+++ b/gr-utils/python/modtool/util_functions.py
@@ -22,6 +22,7 @@
 
 import re
 import sys
+import readline
 
 # None of these must depend on other modtool stuff!
 
@@ -144,3 +145,29 @@ def ask_yes_no(question, default):
         return default
     else:
         return not default
+
+class SequenceCompleter(object):
+    """ A simple completer function wrapper to be used with readline, e.g.
+    option_iterable = ("search", "seek", "destroy")
+    readline.set_completer(SequenceCompleter(option_iterable).completefunc)
+    """
+
+    def __init__(self, sequence):
+        self._seq = sequence
+        self._tmp_matches = []
+
+    def completefunc(self, text, state):
+        if not text and state < len(self._seq):
+            return self._seq[state]
+        if not state:
+            self._tmp_matches = filter(lambda candidate: candidate.startswith(text), self._seq)
+        if state < len(self._tmp_matches):
+            return self._tmp_matches[state]
+
+    def __enter__(self):
+        self._old_completer = readline.get_completer()
+        readline.set_completer(self.completefunc)
+        readline.parse_and_bind("tab: complete")
+
+    def __exit__(self):
+        readline.set_completer(self._old_completer)
-- 
cgit v1.2.3