feat(shell): upgrade Ctrl+P / pick to fzf-like interactive TUI
This commit is contained in:
1 parent
6d2bbe57ff
commit
9a0ebd874f
2 files changed
+322
-24
No files matched your search
@@ -16,19 +16,28 @@ import getpass
|
||||
import glob
|
||||
import hashlib
|
||||
from html.parser import HTMLParser
|
||||
from http import server as http_server
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import posixpath
|
||||
import re
|
||||
import secrets
|
||||
import select
|
||||
import shlex
|
||||
import shutil
|
||||
import ssl
|
||||
import stat
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
try:
|
||||
import termios
|
||||
import tty
|
||||
except ImportError:
|
||||
termios = tty = None
|
||||
import unicodedata
|
||||
import urllib.error
|
||||
import urllib.parse as url
|
||||
@@ -1909,25 +1918,40 @@ def _fuzzy_score(query, text):
|
||||
return None
|
||||
|
||||
|
||||
def _gather_pick_candidates(client, cwd, query=''):
|
||||
def _gather_pick_candidates(client, cwd, query='', *, cache=None):
|
||||
merged = {}
|
||||
if query.strip():
|
||||
try:
|
||||
for item in client.json('/_/api/v1/search/suggest?' + url.urlencode({'q': query.strip()})).get('items', []):
|
||||
p = item.get('path', '')
|
||||
if not isinstance(p, str) or not p.startswith('/') or any(unicodedata.category(c).startswith('C') for c in p):
|
||||
continue
|
||||
merged[p] = {'path': p, 'label': safe_text(item.get('label', '')), 'kind': item.get('kind', 'page')}
|
||||
except Failure:
|
||||
pass
|
||||
try:
|
||||
for item in client.listing(cwd).get('entries', []):
|
||||
q = query.strip()
|
||||
if q:
|
||||
suggest_cache = cache.setdefault('suggest', {}) if cache is not None else None
|
||||
if suggest_cache is not None and q in suggest_cache:
|
||||
suggest_rows = suggest_cache[q]
|
||||
else:
|
||||
try:
|
||||
suggest_rows = client.json('/_/api/v1/search/suggest?' + url.urlencode({'q': q})).get('items', [])
|
||||
except Failure:
|
||||
suggest_rows = []
|
||||
if suggest_cache is not None:
|
||||
suggest_cache[q] = suggest_rows
|
||||
for item in suggest_rows:
|
||||
p = item.get('path', '')
|
||||
if not isinstance(p, str) or not p.startswith('/') or any(unicodedata.category(c).startswith('C') for c in p):
|
||||
continue
|
||||
merged.setdefault(p, {'path': p, 'label': safe_text(item.get('name', '')), 'kind': item.get('kind', 'file')})
|
||||
except Failure:
|
||||
pass
|
||||
merged[p] = {'path': p, 'label': safe_text(item.get('label', '')), 'kind': item.get('kind', 'page')}
|
||||
list_cache = cache.setdefault('listing', {}) if cache is not None else None
|
||||
if list_cache is not None and cwd in list_cache:
|
||||
list_rows = list_cache[cwd]
|
||||
else:
|
||||
try:
|
||||
list_rows = client.listing(cwd).get('entries', [])
|
||||
except Failure:
|
||||
list_rows = []
|
||||
if list_cache is not None:
|
||||
list_cache[cwd] = list_rows
|
||||
for item in list_rows:
|
||||
p = item.get('path', '')
|
||||
if not isinstance(p, str) or not p.startswith('/') or any(unicodedata.category(c).startswith('C') for c in p):
|
||||
continue
|
||||
merged.setdefault(p, {'path': p, 'label': safe_text(item.get('name', '')), 'kind': item.get('kind', 'file')})
|
||||
scored = []
|
||||
for entry in merged.values():
|
||||
haystack = entry['path'] + ' ' + entry['label']
|
||||
@@ -1935,16 +1959,188 @@ def _gather_pick_candidates(client, cwd, query=''):
|
||||
if sc is not None:
|
||||
scored.append((sc, entry['path'], entry))
|
||||
scored.sort(key=lambda row: (-row[0], row[1]))
|
||||
return [row[2] for row in scored[:20]]
|
||||
limit = 50 if cache is not None else 20
|
||||
return [row[2] for row in scored[:limit]]
|
||||
|
||||
|
||||
def fuzzy_pick(client, profile, initial_query='', initial_line=''):
|
||||
if not sys.stdin.isatty():
|
||||
raise Failure('Interactive picker requires a TTY.')
|
||||
cwd = profile.data.get('cwd', '/')
|
||||
def _char_width(ch):
|
||||
if unicodedata.combining(ch):
|
||||
return 0
|
||||
return 2 if unicodedata.east_asian_width(ch) in ('F', 'W') else 1
|
||||
|
||||
|
||||
def _truncate_display(text, max_cols):
|
||||
cleaned = safe_text(text).replace('\n', ' ').replace('\t', ' ')
|
||||
if max_cols <= 0:
|
||||
return ''
|
||||
out = []
|
||||
cols = 0
|
||||
for idx, ch in enumerate(cleaned):
|
||||
w = _char_width(ch)
|
||||
if cols + w > max_cols:
|
||||
while out and cols + 1 > max_cols:
|
||||
cols -= _char_width(out.pop())
|
||||
if cols + 1 <= max_cols:
|
||||
out.append('…')
|
||||
return ''.join(out)
|
||||
out.append(ch)
|
||||
cols += w
|
||||
if idx + 1 < len(cleaned) and cols == max_cols and _char_width(cleaned[idx + 1]) > 0:
|
||||
while out and cols + 1 > max_cols:
|
||||
cols -= _char_width(out.pop())
|
||||
if cols + 1 <= max_cols:
|
||||
out.append('…')
|
||||
return ''.join(out)
|
||||
return ''.join(out)
|
||||
|
||||
|
||||
def _read_tui_key(fd):
|
||||
b = os.read(fd, 1)
|
||||
if not b:
|
||||
return 'CANCEL'
|
||||
ch = b[0]
|
||||
if ch == 0x1b:
|
||||
if not select.select([fd], [], [], 0.03)[0]:
|
||||
return 'ESC'
|
||||
nxt = os.read(fd, 1)
|
||||
if nxt in (b'[', b'O'):
|
||||
seq = nxt
|
||||
while len(seq) < 8 and select.select([fd], [], [], 0.03)[0]:
|
||||
part = os.read(fd, 1)
|
||||
seq += part
|
||||
if part[:1].isalpha() or part == b'~':
|
||||
break
|
||||
if seq in (b'[A', b'OA'):
|
||||
return 'UP'
|
||||
if seq in (b'[B', b'OB'):
|
||||
return 'DOWN'
|
||||
if seq == b'[5~':
|
||||
return 'PGUP'
|
||||
if seq == b'[6~':
|
||||
return 'PGDN'
|
||||
return 'NOOP'
|
||||
return 'NOOP'
|
||||
if ch in (0x0d, 0x0a):
|
||||
return 'ENTER'
|
||||
if ch in (0x7f, 0x08):
|
||||
return 'BACKSPACE'
|
||||
if ch in (0x03, 0x04):
|
||||
return 'CANCEL'
|
||||
if ch in (0x10, 0x0b):
|
||||
return 'UP'
|
||||
if ch in (0x0e,):
|
||||
return 'DOWN'
|
||||
if ch == 0x15:
|
||||
return 'CLEAR'
|
||||
if ch == 0x09:
|
||||
return 'TAB'
|
||||
if ch < 0x20:
|
||||
return 'NOOP'
|
||||
if ch >= 0x80:
|
||||
needed = 1 if (ch & 0xe0) == 0xc0 else 2 if (ch & 0xf0) == 0xe0 else 3 if (ch & 0xf8) == 0xf0 else 0
|
||||
buf = bytearray([ch])
|
||||
for _ in range(needed):
|
||||
if select.select([fd], [], [], 0.03)[0]:
|
||||
buf.extend(os.read(fd, 1))
|
||||
text = buf.decode('utf-8', errors='ignore')
|
||||
if not text or any(unicodedata.category(c).startswith('C') for c in text):
|
||||
return 'NOOP'
|
||||
return ('CHAR', text)
|
||||
return ('CHAR', chr(ch))
|
||||
|
||||
|
||||
def _run_tui_picker(client, cwd, initial_query='', *, key_reader=None, out=None, term_size=None):
|
||||
cur_cwd = cwd
|
||||
query = initial_query
|
||||
selected = 0
|
||||
top = 0
|
||||
cache = {}
|
||||
stream = out or sys.stdout
|
||||
while True:
|
||||
size = term_size() if term_size is not None else shutil.get_terminal_size((80, 24))
|
||||
cols = max(24, size.columns)
|
||||
rows = max(8, size.lines)
|
||||
items = _gather_pick_candidates(client, cur_cwd, query, cache=cache)
|
||||
if items:
|
||||
selected = max(0, min(selected, len(items) - 1))
|
||||
else:
|
||||
selected = 0
|
||||
top = 0
|
||||
height = max(4, rows - 5)
|
||||
if selected < top:
|
||||
top = selected
|
||||
elif selected >= top + height:
|
||||
top = selected - height + 1
|
||||
max_w = cols - 1
|
||||
lines = [
|
||||
_truncate_display(f'pages fuzzy pick cwd: {cur_cwd} [Enter: select | Tab: folder | Esc: cancel]', max_w),
|
||||
_truncate_display(f'> {query}', max_w),
|
||||
_truncate_display(f' {len(items)} matches', max_w),
|
||||
]
|
||||
if not items:
|
||||
lines.append(_truncate_display(' (no matching pages)', max_w))
|
||||
else:
|
||||
for idx in range(top, min(len(items), top + height)):
|
||||
item = items[idx]
|
||||
suffix = '/' if item['kind'] == 'folder' and not item['path'].endswith('/') else ''
|
||||
label = f" {item['label']}" if item['label'] and item['label'] != item['path'] else ''
|
||||
row_text = _truncate_display(f"{'>' if idx == selected else ' '} {item['path']}{suffix}{label} [{item['kind']}]", max_w)
|
||||
if idx == selected:
|
||||
lines.append('\x1b[7m' + row_text + '\x1b[0m')
|
||||
else:
|
||||
lines.append(row_text)
|
||||
stream.write('\x1b[H\x1b[J' + '\r\n'.join(lines))
|
||||
stream.flush()
|
||||
key = key_reader()
|
||||
if isinstance(key, tuple) and key[0] == 'CHAR':
|
||||
query += key[1]
|
||||
selected = 0
|
||||
top = 0
|
||||
elif key == 'BACKSPACE':
|
||||
if query:
|
||||
query = query[:-1]
|
||||
selected = 0
|
||||
top = 0
|
||||
elif key == 'CLEAR':
|
||||
query = ''
|
||||
selected = 0
|
||||
top = 0
|
||||
elif key == 'UP' and items:
|
||||
selected = max(0, selected - 1)
|
||||
elif key == 'DOWN' and items:
|
||||
selected = min(len(items) - 1, selected + 1)
|
||||
elif key == 'PGUP' and items:
|
||||
selected = max(0, selected - height)
|
||||
elif key == 'PGDN' and items:
|
||||
selected = min(len(items) - 1, selected + height)
|
||||
elif key == 'TAB' and items and items[selected]['kind'] == 'folder':
|
||||
cur_cwd = items[selected]['path']
|
||||
query = ''
|
||||
selected = 0
|
||||
top = 0
|
||||
elif key == 'ENTER':
|
||||
return items[selected]['path'] if items else None
|
||||
elif key in ('ESC', 'CANCEL'):
|
||||
return None
|
||||
|
||||
|
||||
def _tui_fuzzy_pick(client, cwd, initial_query=''):
|
||||
fd = sys.stdin.fileno()
|
||||
old = termios.tcgetattr(fd)
|
||||
sys.stdout.write('\x1b[?1049h\x1b[?25l')
|
||||
sys.stdout.flush()
|
||||
try:
|
||||
tty.setraw(fd)
|
||||
return _run_tui_picker(client, cwd, initial_query, key_reader=lambda: _read_tui_key(fd), out=sys.stdout)
|
||||
finally:
|
||||
termios.tcsetattr(fd, termios.TCSADRAIN, old)
|
||||
sys.stdout.write('\x1b[?25h\x1b[?1049l')
|
||||
sys.stdout.flush()
|
||||
|
||||
|
||||
def _line_fuzzy_pick(client, cwd, initial_query='', *, allow_retry=False):
|
||||
query = initial_query.strip()
|
||||
first = True
|
||||
chosen = None
|
||||
while True:
|
||||
if not first or not query:
|
||||
try:
|
||||
@@ -1958,7 +2154,7 @@ def fuzzy_pick(client, profile, initial_query='', initial_line=''):
|
||||
items = _gather_pick_candidates(client, cwd, query)
|
||||
if not items:
|
||||
print('No matching pages.')
|
||||
if initial_query and not initial_line:
|
||||
if initial_query and not allow_retry:
|
||||
return None
|
||||
query = ''
|
||||
continue
|
||||
@@ -1974,11 +2170,28 @@ def fuzzy_pick(client, profile, initial_query='', initial_line=''):
|
||||
if sel.isdigit():
|
||||
num = int(sel)
|
||||
if 1 <= num <= len(items):
|
||||
chosen = items[num - 1]['path']
|
||||
break
|
||||
return items[num - 1]['path']
|
||||
print('Selection out of range.')
|
||||
continue
|
||||
query = sel
|
||||
|
||||
|
||||
def fuzzy_pick(client, profile, initial_query='', initial_line=''):
|
||||
if not sys.stdin.isatty():
|
||||
raise Failure('Interactive picker requires a TTY.')
|
||||
cwd = profile.data.get('cwd', '/')
|
||||
use_tui = (
|
||||
termios is not None and tty is not None
|
||||
and sys.stdin.isatty() and sys.stdout.isatty()
|
||||
and os.environ.get('TERM', '').lower() not in ('', 'dumb')
|
||||
)
|
||||
chosen = (
|
||||
_tui_fuzzy_pick(client, cwd, initial_query)
|
||||
if use_tui else
|
||||
_line_fuzzy_pick(client, cwd, initial_query, allow_retry=bool(initial_line))
|
||||
)
|
||||
if not chosen:
|
||||
return None
|
||||
if initial_line:
|
||||
return initial_line + shlex.quote(chosen)
|
||||
try:
|
||||
|
||||
Reference in new issue
Block a user