add enhancements to CLI command-line completion and history

- Added support for pyreadline3 so that Window users can benefit.
- Added the !search command to search the history for a matching string:
~~~
!search puppies
[20] puppies at the food bowl -Ak_lms
[54] house overrun by hungry puppies -C20 -s100
~~~
- Added the !clear command to clear the in-memory and on-disk
  command history.
This commit is contained in:
Lincoln Stein
2022-10-04 14:57:48 -04:00
parent 18e667f98e
commit d16f0c8a8f
5 changed files with 61 additions and 13 deletions

View File

@ -17,8 +17,11 @@ from ldm.dream.args import Args
try:
import readline
readline_available = True
except:
readline_available = False
except (ImportError,ModuleNotFoundError):
try:
import pyreadline3
except (ImportError,ModuleNotFoundError):
readline_available = False
IMG_EXTENSIONS = ('.png','.jpg','.jpeg')
COMMANDS = (
@ -47,7 +50,7 @@ COMMANDS = (
'--skip_normalize','-x',
'--log_tokenization','-t',
'--hires_fix',
'!fix','!fetch','!history',
'!fix','!fetch','!history','!search','!clear',
)
IMG_PATH_COMMANDS = (
'--outdir[=\s]',
@ -62,7 +65,7 @@ IMG_FILE_COMMANDS=(
)
path_regexp = '('+'|'.join(IMG_PATH_COMMANDS+IMG_FILE_COMMANDS) + ')\s*\S*$'
class Completer:
class Completer(object):
def __init__(self, options):
self.options = sorted(options)
self.seeds = set()
@ -111,6 +114,19 @@ class Completer:
if not self.auto_history_active:
readline.add_history(line)
def clear_history(self):
'''
Pass clear_history() thru to readline
'''
readline.clear_history()
def search_history(self,match:str):
'''
Like show_history() but only shows items that
contain the match string.
'''
self.show_history(match)
def remove_history_item(self,pos):
readline.remove_history_item(pos)
@ -137,7 +153,7 @@ class Completer:
def get_history_item(self,index):
return readline.get_history_item(index)
def show_history(self):
def show_history(self,match=None):
'''
Print the session history using the pydoc pager
'''
@ -149,7 +165,10 @@ class Completer:
return
for i in range(0,h_len):
lines.append(f'[{i+1}] {self.get_history_item(i+1)}')
line = self.get_history_item(i+1)
if match and match not in line:
continue
lines.append(f'[{i+1}] {line}')
pydoc.pager('\n'.join(lines))
def set_line(self,line)->None:
@ -235,6 +254,9 @@ class DummyCompleter(Completer):
def add_history(self,line):
self.history.append(line)
def clear_history(self):
self.history = list()
def get_current_history_length(self):
return len(self.history)