Suggestions and colours on the shell's input line, drawn by the terminal; the engine's contract as built
Drawn when a pane is painted and nowhere else: nothing is written to the pane and the terminal's model of the screen is not touched. The input line is found among the cells the shell integration marked; the painter gets the pane's own lines with copies of the few rows that are drawn differently. - The rest of the line, dimmed after the cursor, from the terminal's own history of commands it saw run (its own file, the person's alone; nothing that starts with a space, was not found or came from a private pane). Right or End takes it, Alt+Right one word, as if typed. - With the AI's autocomplete on, LLeMbas is asked after a pause when the history has nothing, off the window's thread, and its answer shows in the same place. - The command line in colours of the colour scheme's palette: the command when it exists, options, strings, variables, operators, comments, paths that exist. Existence is looked up only for a shell on this machine. - A word from the terminal at the cursor's row for a moment, in place of a dialog. - Off under a full-screen program, without shell integration, for a line of more than three rows, under an overlay, and by its options and switches. The layer, to the engine's contract as built: answers and stop go as lines (/approve, /deny, /always, /stop); the display is started so that the pane stays to say why it could not; every pane is told where the status records of this terminal are, each terminal keeping its own. The autocomplete drawn by the shell integration is now autocomplete = 'shell'. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
12 files changed
+1452
-36
No files matched your search
@@ -66,7 +66,8 @@ M.COLORS = {
|
||||
ghost = 8, -- a suggestion after the cursor
|
||||
notice = 3, -- a word from the terminal at the cursor's row
|
||||
command = 2, -- a command that exists
|
||||
unknown = 1, -- a command that does not
|
||||
unknown = false, -- a command that is not found: left alone (the terminal does not
|
||||
-- know the shell's aliases and functions); give it a colour to mark such words
|
||||
option = false, -- false: left as the shell drew it
|
||||
string = 3,
|
||||
variable = 6,
|
||||
@@ -133,7 +134,10 @@ function M.defaults()
|
||||
-- Drawn by the terminal on the shell's input line (needs the shell integration):
|
||||
suggestions = true, -- the rest of the line from your own command history, dimmed
|
||||
highlight = true, -- the command line in colours
|
||||
autocomplete = false, -- AI: the rest of the line from LLeMbas, when history has none
|
||||
-- AI: the rest of the line from LLeMbas, when the history has none. true: drawn by the
|
||||
-- terminal like every suggestion. 'shell': by the shell integration instead (zsh draws
|
||||
-- it itself, bash completes on Ctrl+X Ctrl+A), as before the terminal drew its own.
|
||||
autocomplete = false,
|
||||
-- The terminal's own history of commands it saw run, for the suggestions.
|
||||
history = {
|
||||
enabled = true,
|
||||
@@ -407,6 +411,8 @@ local function merge_into(base, over, path, warnings)
|
||||
elseif path == 'colors.' then
|
||||
-- checked as a whole afterwards (M.options)
|
||||
base[k] = v
|
||||
elseif path == '' and k == 'autocomplete' and v == 'shell' then
|
||||
base[k] = v
|
||||
elseif path == 'keys.' then
|
||||
-- a key: false turns it off, a table { key =, mods = } sets it
|
||||
if v == false then
|
||||
@@ -1151,8 +1157,25 @@ function M.display_line(name, arg)
|
||||
return nil
|
||||
end
|
||||
|
||||
-- One key each: allow once, allow always, deny; and what stops a turn.
|
||||
M.DISPLAY_KEYS = { approve = 'y', always = 'a', deny = 'n', stop = '\3' }
|
||||
-- What answers an approval and what stops a turn, each a line of its own:
|
||||
-- unambiguous, where a single key counts only while something is asked.
|
||||
M.DISPLAY_KEYS = { approve = '/approve\r', always = '/always\r', deny = '/deny\r', stop = '/stop\r' }
|
||||
|
||||
-- The display ends at once when it cannot start (not logged in, one runs for
|
||||
-- this window already), and a pane that closes at once says nothing. So on
|
||||
-- systems with a shell it is started through this, which keeps the pane with
|
||||
-- the display's own sentence until Enter. The command's words are handed over
|
||||
-- as arguments, never as text of the script.
|
||||
M.DISPLAY_HOLD = '"$@"; s=$?; [ "$s" -eq 0 ] && exit 0; '
|
||||
.. [[printf '\n[LLeMbas ended (status %s). Press Enter to close this pane.] ' "$s"; read -r _]]
|
||||
|
||||
function M.held(args)
|
||||
local out = { '/bin/sh', '-c', M.DISPLAY_HOLD, 'llembas-display' }
|
||||
for _, a in ipairs(args) do
|
||||
out[#out + 1] = a
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
-- THE commands of the terminal's two models, in one place.
|
||||
function M.models_args(cli)
|
||||
@@ -1344,6 +1367,22 @@ function M.status_dir(getenv, home)
|
||||
return nil
|
||||
end
|
||||
|
||||
-- The status directory of one run of the terminal: two terminals number
|
||||
-- their panes alike, so each keeps its records apart.
|
||||
function M.status_dir_of(base, pid)
|
||||
if type(base) ~= 'string' or type(pid) ~= 'number' then
|
||||
return base
|
||||
end
|
||||
return string.format('%s/status-%d', base, pid)
|
||||
end
|
||||
|
||||
-- The process id in the name of such a directory; nil for any other name.
|
||||
function M.status_dir_pid(path)
|
||||
local base = path:match('([^/\\]+)$') or path
|
||||
local pid = base:match('^status%-(%d+)$')
|
||||
return pid and tonumber(pid) or nil
|
||||
end
|
||||
|
||||
function M.status_file_name(pane_id)
|
||||
return string.format('pane-%d.status', pane_id)
|
||||
end
|
||||
|
||||
@@ -369,6 +369,8 @@ local function display_of(pane)
|
||||
return by_id[id], pane_session(by_id[id])
|
||||
end
|
||||
|
||||
local sweep_status
|
||||
|
||||
local function is_local(pane)
|
||||
local ok, name = pcall(function()
|
||||
return pane:get_domain_name()
|
||||
@@ -376,6 +378,50 @@ local function is_local(pane)
|
||||
return not ok or name == 'local'
|
||||
end
|
||||
|
||||
-- Where the panes' status records of this run of the terminal are.
|
||||
local function status_dir()
|
||||
local explicit = os.getenv 'LLEMBAS_TTY_STATUS_DIR'
|
||||
if type(explicit) == 'string' and explicit:sub(1, 1) == '/' then
|
||||
return explicit
|
||||
end
|
||||
local base = core.status_dir(os.getenv, wezterm.home_dir)
|
||||
local pid
|
||||
pcall(function()
|
||||
pid = wezterm.procinfo.pid()
|
||||
end)
|
||||
return core.status_dir_of(base, pid)
|
||||
end
|
||||
|
||||
-- Records of terminals that are gone: their directories are removed (the
|
||||
-- records in them, then the directory), when a display is about to start.
|
||||
sweep_status = function()
|
||||
local base = core.status_dir(os.getenv, wezterm.home_dir)
|
||||
if not base or is_windows() then
|
||||
return
|
||||
end
|
||||
local ok, entries = pcall(wezterm.read_dir, base)
|
||||
if not ok or type(entries) ~= 'table' then
|
||||
return
|
||||
end
|
||||
for _, dir in ipairs(entries) do
|
||||
local pid = core.status_dir_pid(dir)
|
||||
if pid then
|
||||
local alive = io.open(string.format('/proc/%d/stat', pid), 'r')
|
||||
if alive then
|
||||
alive:close()
|
||||
elseif io.open('/proc/self/stat', 'r') then
|
||||
local ok2, files = pcall(wezterm.read_dir, dir)
|
||||
for _, f in ipairs(ok2 and type(files) == 'table' and files or {}) do
|
||||
if (f:match('([^/]+)$') or ''):match('^pane%-%d+%.status') then
|
||||
os.remove(f)
|
||||
end
|
||||
end
|
||||
os.remove(dir)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- The mode a display is started in: what the person last chose, else the option.
|
||||
local function wanted_mode()
|
||||
local chosen = global('choice').mode
|
||||
@@ -402,10 +448,11 @@ local function start_display(pane, cli, context_path)
|
||||
new = fresh['t' .. tostring(id)] == true,
|
||||
})
|
||||
fresh['t' .. tostring(id)] = false
|
||||
sweep_status()
|
||||
local display = pane:split {
|
||||
direction = 'Right',
|
||||
size = opts.display.width,
|
||||
args = args,
|
||||
args = is_windows() and args or core.held(args),
|
||||
cwd = pane_cwd(pane),
|
||||
}
|
||||
if display then
|
||||
@@ -981,7 +1028,7 @@ end
|
||||
-- write it itself (a shell on another machine). Only with AI on: its one
|
||||
-- reader is LLeMbas.
|
||||
local function store_status(pane, rec)
|
||||
local dir = core.status_dir(os.getenv, wezterm.home_dir)
|
||||
local dir = status_dir()
|
||||
if not dir then
|
||||
return
|
||||
end
|
||||
@@ -995,10 +1042,15 @@ local function store_status(pane, rec)
|
||||
end
|
||||
end
|
||||
local tmp = path .. '.tty'
|
||||
if write_private(tmp, core.status_text(rec)) then
|
||||
if not os.rename(tmp, path) then
|
||||
os.remove(tmp)
|
||||
end
|
||||
local text = core.status_text(rec)
|
||||
local written = write_private(tmp, text)
|
||||
if not written and not is_windows() then
|
||||
-- no shell of this machine has made the directory yet
|
||||
wezterm.run_child_process { 'mkdir', '-p', '-m', '700', dir }
|
||||
written = write_private(tmp, text)
|
||||
end
|
||||
if written and not os.rename(tmp, path) then
|
||||
os.remove(tmp)
|
||||
end
|
||||
end
|
||||
|
||||
@@ -1201,7 +1253,7 @@ function M.apply(config, options)
|
||||
end
|
||||
config.keys = keys
|
||||
|
||||
if opts.autocomplete and opts.ai then
|
||||
if opts.autocomplete == 'shell' and opts.ai then
|
||||
-- The shipped shell integration completes the prompt only when it sees this.
|
||||
local env = config.set_environment_variables or {}
|
||||
env.LLEMBAS_TTY_AUTOCOMPLETE = '1'
|
||||
@@ -1212,6 +1264,17 @@ function M.apply(config, options)
|
||||
config.set_environment_variables = env
|
||||
end
|
||||
|
||||
-- Every pane is told where the status records of this terminal are, so that
|
||||
-- the shell integration and LLeMbas agree on it.
|
||||
local dir = status_dir()
|
||||
if dir then
|
||||
local env = config.set_environment_variables or {}
|
||||
if env.LLEMBAS_TTY_STATUS_DIR == nil then
|
||||
env.LLEMBAS_TTY_STATUS_DIR = dir
|
||||
end
|
||||
config.set_environment_variables = env
|
||||
end
|
||||
|
||||
push_native()
|
||||
register_events()
|
||||
return config
|
||||
|
||||
+70
-22
@@ -158,6 +158,7 @@ test('options: defaults', function()
|
||||
eq(o.context.alt_screen, false, 'alt screen')
|
||||
eq(o.colors.ghost, 8, 'a colour of the scheme, not one of ours')
|
||||
eq(o.colors.option, false, 'options are left as the shell drew them')
|
||||
eq(o.colors.unknown, false, 'and so is a command the terminal does not find')
|
||||
end)
|
||||
|
||||
test('options: merge, turn off, clamp', function()
|
||||
@@ -552,8 +553,12 @@ test('the display: its command, its lines and keys', function()
|
||||
eq(core.display_line('mode', 'edit'), nil, 'no edit mode')
|
||||
eq(core.display_line 'new', '/new\r', 'new')
|
||||
eq(core.display_line 'quit', nil, 'nothing else')
|
||||
eq(core.DISPLAY_KEYS.approve .. core.DISPLAY_KEYS.always .. core.DISPLAY_KEYS.deny, 'yan', 'one key each')
|
||||
eq(core.DISPLAY_KEYS.stop, '\3', 'Ctrl+C stops the turn')
|
||||
eq(core.DISPLAY_KEYS.approve .. core.DISPLAY_KEYS.always .. core.DISPLAY_KEYS.deny, '/approve\r/always\r/deny\r', 'a line each')
|
||||
eq(core.DISPLAY_KEYS.stop, '/stop\r', 'what stops the turn')
|
||||
local held = core.held { 'lembas', 'terminal', '; rm -rf /' }
|
||||
eq(held[1] .. ' ' .. held[2], '/bin/sh -c', 'through a shell that holds the pane')
|
||||
eq(held[7], '; rm -rf /', 'the words as arguments, never as text of the script')
|
||||
eq(#held, 7, 'all of them')
|
||||
eq(core.is_model_ref 'provider/model-1.5:latest@x', true, 'a ref')
|
||||
eq(core.is_model_ref(string.rep('a', 200)), false, 'too long')
|
||||
eq(core.is_model_ref 'a b', false, 'two words')
|
||||
@@ -634,6 +639,11 @@ test('status records', function()
|
||||
eq(core.status_dir(env {}, '/h'), '/h/.local/state/llembas-tty', 'home')
|
||||
eq(core.status_dir(env {}, nil), nil, 'nowhere')
|
||||
eq(core.status_file_name(12), 'pane-12.status', 'the file')
|
||||
eq(core.status_dir_of('/r/llembas-tty', 4242), '/r/llembas-tty/status-4242', 'of one run of the terminal')
|
||||
eq(core.status_dir_of('/r/llembas-tty', nil), '/r/llembas-tty', 'when it does not know its own process')
|
||||
eq(core.status_dir_pid '/r/llembas-tty/status-4242', 4242, 'whose it is')
|
||||
eq(core.status_dir_pid '/r/llembas-tty/sock', nil, 'any other name is not one')
|
||||
eq(core.status_dir_pid '/r/llembas-tty/status-x', nil, 'nor this')
|
||||
end)
|
||||
|
||||
----------------------------------------------------------------------------
|
||||
@@ -722,6 +732,15 @@ local function context_files(dir)
|
||||
return list
|
||||
end
|
||||
|
||||
-- The display's own command in a split: what follows the shell that holds the pane open.
|
||||
local function dargs(split)
|
||||
local out = {}
|
||||
for i = 5, #split.args do
|
||||
out[#out + 1] = split.args[i]
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
local function spawned(w, what)
|
||||
local n = 0
|
||||
for _, args in ipairs(w.spawned) do
|
||||
@@ -758,7 +777,8 @@ test('apply: keys, events, and nothing else happens', function()
|
||||
eq(config.keys[3].action.args, 'llembas-cli', 'the CLI whole')
|
||||
eq(config.keys[4].action.args, 'llembas-ai', 'the switch')
|
||||
eq(#w.spawned, 0, 'no process started by applying')
|
||||
eq(config.set_environment_variables, nil, 'no environment touched')
|
||||
check(config.set_environment_variables.LLEMBAS_TTY_STATUS_DIR:sub(1, 1) == '/', 'every pane is told where the status records are')
|
||||
eq(next(config.set_environment_variables, 'LLEMBAS_TTY_STATUS_DIR'), nil, 'and nothing else is put in its environment')
|
||||
for _, name in ipairs { 'update-status', 'format-tab-title', 'augment-command-palette', 'user-var-changed', 'llembas-ask', 'llembas-ai' } do
|
||||
check(w.handlers[name] ~= nil, 'handler for ' .. name)
|
||||
end
|
||||
@@ -824,13 +844,18 @@ end)
|
||||
test('apply: autocomplete exports the switch for the shell integration', function()
|
||||
local dir = fresh_dir 'ac'
|
||||
with_cli(dir)
|
||||
local _, w, config = layer({}, { autocomplete = true }, { set_environment_variables = { MINE = '1' } })
|
||||
local _, w, config = layer({}, { autocomplete = 'shell' }, { set_environment_variables = { MINE = '1' } })
|
||||
eq(config.set_environment_variables.LLEMBAS_TTY_AUTOCOMPLETE, '1', 'switch')
|
||||
eq(config.set_environment_variables.LLEMBAS_TTY_CLI, dir .. '/bin/lembas', 'the CLI found')
|
||||
eq(config.set_environment_variables.MINE, '1', "the person's own stays")
|
||||
eq(#w.spawned, 0, 'still no process')
|
||||
local _, _, config2 = layer({}, { autocomplete = true, ai = false })
|
||||
eq(config2.set_environment_variables, nil, 'AI off: not exported')
|
||||
local l2, _, config2 = layer({}, { autocomplete = 'shell', ai = false })
|
||||
eq(config2.set_environment_variables.LLEMBAS_TTY_AUTOCOMPLETE, nil, 'AI off: not exported')
|
||||
eq(l2.is_on 'autocomplete', false, "the shell's own is not the terminal's")
|
||||
local _, _, config3 = layer({}, { autocomplete = true })
|
||||
eq(config3.set_environment_variables.LLEMBAS_TTY_AUTOCOMPLETE, nil, 'drawn by the terminal: the shell integration stays out of it')
|
||||
local _, w4 = layer({}, { autocomplete = 'zsh' })
|
||||
check(#w4.logs == 1, 'anything else is a mistake, said')
|
||||
end)
|
||||
|
||||
test('AI off: every key but the switch does nothing, and says so once', function()
|
||||
@@ -862,7 +887,7 @@ test('AI off: every key but the switch does nothing, and says so once', function
|
||||
w.emit('llembas-ai', win, pane)
|
||||
eq(l.is_on 'ai', true, 'on')
|
||||
w.emit('llembas-approve', win, pane)
|
||||
eq(display.sent[1][2], 'y', 'and the keys work')
|
||||
eq(display.sent[1][2], '/approve\r', 'and the keys work')
|
||||
w.emit('llembas-ai', win, pane)
|
||||
eq(l.is_on 'ai', false, 'off again')
|
||||
w.emit('llembas-deny', win, pane)
|
||||
@@ -973,15 +998,18 @@ test('ask: the display starts to the right, with a context file, and the focus s
|
||||
eq(s.direction, 'Right', 'to the right')
|
||||
eq(s.size, 0.33, 'a third')
|
||||
eq(s.cwd, '/home/u/proj', "in the pane's directory")
|
||||
eq(s.args[1], dir .. '/bin/lembas', 'the CLI')
|
||||
eq(s.args[2], 'terminal', 'as the display, never its own interface')
|
||||
eq(s.args[3], '--window', 'the conversation of this tab')
|
||||
check(s.args[4]:match('^t%d+%-4$') ~= nil, 'named by this run of the terminal and the tab: ' .. s.args[4])
|
||||
eq(s.args[5] .. ' ' .. s.args[6], '--pane 7', "the person's pane")
|
||||
eq(s.args[7], '--terminal-context', 'flag')
|
||||
eq(s.args[8], files[1], 'file')
|
||||
eq(s.args[9] .. ' ' .. s.args[10], '--mode manual', 'the mode')
|
||||
eq(#s.args, 10, 'the question is not on the command line')
|
||||
eq(s.args[1] .. ' ' .. s.args[2], '/bin/sh -c', 'held open when the display cannot start, to say why')
|
||||
eq(s.args[3], core.DISPLAY_HOLD, 'by a script that is always the same')
|
||||
local a = dargs(s)
|
||||
eq(a[1], dir .. '/bin/lembas', 'the CLI')
|
||||
eq(a[2], 'terminal', 'as the display, never its own interface')
|
||||
eq(a[3], '--window', 'the conversation of this tab')
|
||||
check(a[4]:match('^t%d+%-4$') ~= nil, 'named by this run of the terminal and the tab: ' .. a[4])
|
||||
eq(a[5] .. ' ' .. a[6], '--pane 7', "the person's pane")
|
||||
eq(a[7], '--terminal-context', 'flag')
|
||||
eq(a[8], files[1], 'file')
|
||||
eq(a[9] .. ' ' .. a[10], '--mode manual', 'the mode')
|
||||
eq(#a, 10, 'the question is not on the command line')
|
||||
eq(pane.activated, 1, 'the focus goes back to the person\'s pane')
|
||||
local new = pane.last_split
|
||||
eq(#new.sent, 0, 'nothing sent before the display is ready')
|
||||
@@ -1001,7 +1029,7 @@ test('ask: the display starts to the right, with a context file, and the focus s
|
||||
eq(#pane2.splits, 1, 'one display for the tab')
|
||||
w.emit('user-var-changed', win, pane2.last_split, 'lembas_state', 'idle')
|
||||
eq(pane2.last_split.sent[1][2], '\27[200~second\27[201~\r', 'the newest question is the one that waits')
|
||||
check(pane2.splits[1].args[4] ~= s.args[4], 'another tab is another conversation')
|
||||
check(dargs(pane2.splits[1])[4] ~= a[4], 'another tab is another conversation')
|
||||
end)
|
||||
|
||||
test('ask: into the display the tab already has', function()
|
||||
@@ -1118,8 +1146,9 @@ test('ask: a private pane gives nothing, and the question still goes', function(
|
||||
eq(pane.read_zones, nil, 'zones not read')
|
||||
eq(pane.read_screen, nil, 'screen not read')
|
||||
eq(#pane.splits, 1, 'the display still starts')
|
||||
eq(table.concat(pane.splits[1].args, ' ', 2, 6), 'terminal --window ' .. pane.splits[1].args[4] .. ' --pane 4', 'with no context')
|
||||
eq(pane.splits[1].args[7], '--mode', 'no context flag')
|
||||
local pa = dargs(pane.splits[1])
|
||||
eq(table.concat(pa, ' ', 2, 6), 'terminal --window ' .. pa[4] .. ' --pane 4', 'with no context')
|
||||
eq(pa[7], '--mode', 'no context flag')
|
||||
eq(win.actions[#win.actions].action.action, 'InputSelector', 'and the person is told')
|
||||
w.emit('llembas-private', win, pane)
|
||||
eq(l.is_private(4), false, 'off again')
|
||||
@@ -1237,7 +1266,7 @@ test('approve, deny, always, stop: sent to the display while the person stays in
|
||||
w.emit('llembas-approve', win, pane)
|
||||
w.emit('llembas-deny', win, pane)
|
||||
w.emit('llembas-always', win, pane)
|
||||
eq(display.sent[1][2] .. display.sent[2][2] .. display.sent[3][2], 'yna', 'one key each')
|
||||
eq(display.sent[1][2] .. display.sent[2][2] .. display.sent[3][2], '/approve\r/deny\r/always\r', 'a line each, each one write')
|
||||
eq(#pane.sent, 0, "nothing into the person's pane")
|
||||
eq(pane.activated, nil, 'and the focus is not moved')
|
||||
display.vars.lembas_state = 'tools'
|
||||
@@ -1245,7 +1274,7 @@ test('approve, deny, always, stop: sent to the display while the person stays in
|
||||
eq(#display.sent, 3, 'nothing waits: nothing sent')
|
||||
eq(native.last 'notice'[3], 'LLeMbas is not waiting for an answer.', 'said')
|
||||
w.emit('llembas-stop', win, pane)
|
||||
eq(display.sent[4][2], '\3', 'stop')
|
||||
eq(display.sent[4][2], '/stop\r', 'stop')
|
||||
-- no display in the tab
|
||||
local alone = fake.pane { id = 5 }
|
||||
fake.tab({ alone }, 9)
|
||||
@@ -1315,7 +1344,7 @@ test('show and hide the display', function()
|
||||
fake.tab({ pane }, 2)
|
||||
w.emit('llembas-display', win, pane)
|
||||
eq(#pane.splits, 1, 'none yet: one is started')
|
||||
eq(pane.splits[1].args[2], 'terminal', 'the display')
|
||||
eq(dargs(pane.splits[1])[2], 'terminal', 'the display')
|
||||
eq(pane.activated, 1, 'the focus stays')
|
||||
local display = pane.last_split
|
||||
w.emit('llembas-display', win, pane)
|
||||
@@ -1482,6 +1511,25 @@ test('status record by user variable: the file is kept for a shell that could no
|
||||
env.LLEMBAS_TTY_STATUS_DIR = false
|
||||
end)
|
||||
|
||||
test('status records of terminals that are gone are removed when a display starts', function()
|
||||
local dir = fresh_dir 'statussweep'
|
||||
with_cli(dir)
|
||||
env.XDG_RUNTIME_DIR = dir .. '/rt'
|
||||
local base = dir .. '/rt/llembas-tty'
|
||||
sh(string.format("mkdir -p '%s/status-999999999' '%s/status-1' '%s/other'", base, base, base))
|
||||
write_file(base .. '/status-999999999/pane-3.status', 'x')
|
||||
write_file(base .. '/status-1/pane-0.status', 'x')
|
||||
write_file(base .. '/other/pane-0.status', 'x')
|
||||
local _, w = new_layer {}
|
||||
local pane = fake.pane { id = 1, zones = ZONES }
|
||||
fake.tab { pane }
|
||||
w.emit('llembas-ask-line', fake.window(), pane, 'q')
|
||||
eq(read_file(base .. '/status-999999999/pane-3.status'), nil, 'a terminal that is gone: its records go')
|
||||
eq(sh(string.format("ls -1 '%s' | tr '\\n' ' '", base)), 'other status-1', 'and its directory; a living process and other names stay')
|
||||
check(read_file(base .. '/status-1/pane-0.status') ~= nil, 'the records of a process that lives stay')
|
||||
env.XDG_RUNTIME_DIR = false
|
||||
end)
|
||||
|
||||
test('status record: private panes, AI off, history off', function()
|
||||
local dir = fresh_dir 'status2'
|
||||
env.LLEMBAS_TTY_STATUS_DIR = dir .. '/run'
|
||||
|
||||
@@ -102,6 +102,36 @@ return config
|
||||
LUA
|
||||
own="$(clean "$TTY" show-keys --lua 2>"$work/keys-err.txt")"
|
||||
expect "a person's own file in our directory is read, and require 'llembas' works there" "$own" "F9"
|
||||
# The terminal's own drawing part is there for the layer (wezterm.llembas), takes what the
|
||||
# layer tells it, and the layer applied over it still binds its keys.
|
||||
cat > "$work/cfg/llembas-tty/llembas-tty.lua" <<'LUA'
|
||||
local wezterm = require 'wezterm'
|
||||
local config = wezterm.config_builder()
|
||||
local n = wezterm.llembas
|
||||
local out = { 'module=' .. type(n) }
|
||||
if type(n) == 'table' then
|
||||
for _, name in ipairs { 'ask_line', 'configure', 'notice', 'set_private', 'command_ended', 'clear_history' } do
|
||||
out[#out + 1] = name .. '=' .. type(n[name])
|
||||
end
|
||||
local ok, err = pcall(n.configure, {
|
||||
suggestions = true, highlight = true, ai_complete = false, cli = '', history = true, history_max = 10,
|
||||
colors = { ghost = 8, command = '#00ff00', unknown = false },
|
||||
})
|
||||
out[#out + 1] = 'configure=' .. tostring(ok) .. (ok and '' or (' ' .. tostring(err)))
|
||||
local ok2 = pcall(n.set_private, 3, true)
|
||||
out[#out + 1] = 'set_private=' .. tostring(ok2)
|
||||
end
|
||||
require('llembas').apply(config, { autocomplete = true })
|
||||
local f = io.open(wezterm.home_dir .. '/native.txt', 'w')
|
||||
f:write(table.concat(out, ' '))
|
||||
f:close()
|
||||
return config
|
||||
LUA
|
||||
native_keys="$(clean "$TTY" show-keys --lua 2>"$work/keys-err.txt")"
|
||||
native="$(cat "$work/home/native.txt" 2>/dev/null)"
|
||||
expect "wezterm.llembas is there, with every function the layer uses" "$native" '^module=table ask_line=function configure=function notice=function set_private=function command_ended=function clear_history=function configure=true set_private=true$'
|
||||
expect "the layer applies over it" "$native_keys" "llembas-ask"
|
||||
if [ -e "$work/home/.local/share/llembas-tty/command-history" ]; then bad "a command history was written though no command ran"; else ok "no command history is written before a command ran"; fi
|
||||
else
|
||||
bad "show-keys did not run: $(head -5 "$work/keys-err.txt")"
|
||||
fi
|
||||
|
||||
@@ -0,0 +1,181 @@
|
||||
//! LLeMbas TTY: the rest of a line asked of LLeMbas, for the suggestion after
|
||||
//! the cursor when the AI's autocomplete is on.
|
||||
//!
|
||||
//! The line so far goes to `lembas complete --shell …` on its standard
|
||||
//! input, off the window's own thread, after a pause in the typing; a request
|
||||
//! that is no longer wanted is stopped. What comes back is a model's text: it
|
||||
//! is cleaned to one plain line (`llembas_line::suggest`) and only ever
|
||||
//! offered, never run.
|
||||
|
||||
use super::state;
|
||||
use llembas_line::suggest;
|
||||
use mux::pane::{CachePolicy, Pane, PaneId};
|
||||
use mux::{Mux, MuxNotification};
|
||||
use parking_lot::Mutex;
|
||||
use std::collections::HashMap;
|
||||
use std::io::{Read, Write};
|
||||
use std::process::{Command, Stdio};
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// The pause in the typing before LLeMbas is asked.
|
||||
const PAUSE: Duration = Duration::from_millis(350);
|
||||
/// How long an answer is waited for.
|
||||
const PATIENCE: Duration = Duration::from_secs(5);
|
||||
/// The fewest characters a line must have to be asked about.
|
||||
const MIN_CHARS: usize = 3;
|
||||
const MAX_BYTES: usize = 2000;
|
||||
|
||||
#[derive(Default)]
|
||||
struct Ai {
|
||||
next_id: u64,
|
||||
/// The request that is wanted now: the pane, the line, its number.
|
||||
wanted: Option<(PaneId, String, u64)>,
|
||||
/// The last answer for a pane: the line it was for, and the rest (or that
|
||||
/// there was none).
|
||||
answers: HashMap<PaneId, (String, Option<String>)>,
|
||||
}
|
||||
|
||||
lazy_static::lazy_static! {
|
||||
static ref AI: Mutex<Ai> = Mutex::new(Ai::default());
|
||||
}
|
||||
|
||||
/// The shell of a pane by its name, as `lembas complete --shell` takes it.
|
||||
fn shell_of(pane: &Arc<dyn Pane>) -> &'static str {
|
||||
let name = pane
|
||||
.get_foreground_process_name(CachePolicy::AllowStale)
|
||||
.unwrap_or_default();
|
||||
let base = name
|
||||
.rsplit(|c: char| c == '/' || c == '\\')
|
||||
.next()
|
||||
.unwrap_or("");
|
||||
match base.trim_start_matches('-') {
|
||||
"zsh" => "zsh",
|
||||
"fish" => "fish",
|
||||
_ => "bash",
|
||||
}
|
||||
}
|
||||
|
||||
fn still_wanted(id: u64) -> bool {
|
||||
matches!(&AI.lock().wanted, Some((_, _, wanted)) if *wanted == id)
|
||||
}
|
||||
|
||||
fn finish(id: u64, pane_id: PaneId, typed: String, rest: Option<String>) {
|
||||
let mut ai = AI.lock();
|
||||
if matches!(&ai.wanted, Some((_, _, wanted)) if *wanted == id) {
|
||||
ai.wanted = None;
|
||||
}
|
||||
if ai.answers.len() > 256 {
|
||||
ai.answers.clear();
|
||||
}
|
||||
ai.answers.insert(pane_id, (typed, rest));
|
||||
drop(ai);
|
||||
state::changed();
|
||||
Mux::notify_from_any_thread(MuxNotification::PaneOutput(pane_id));
|
||||
}
|
||||
|
||||
fn ask(
|
||||
id: u64,
|
||||
pane_id: PaneId,
|
||||
typed: String,
|
||||
cli: String,
|
||||
shell: &'static str,
|
||||
cwd: Option<String>,
|
||||
) {
|
||||
std::thread::sleep(PAUSE);
|
||||
if !still_wanted(id) {
|
||||
return;
|
||||
}
|
||||
let mut command = Command::new(&cli);
|
||||
command.arg("complete").arg("--shell").arg(shell);
|
||||
if let Some(cwd) = &cwd {
|
||||
command.arg("--cwd").arg(cwd);
|
||||
}
|
||||
command
|
||||
.arg("--timeout-ms")
|
||||
.arg("2500")
|
||||
.env("LLEMBAS_TTY", config::llembas_tty_version())
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::null());
|
||||
let mut child = match command.spawn() {
|
||||
Ok(child) => child,
|
||||
Err(_) => {
|
||||
finish(id, pane_id, typed, None);
|
||||
return;
|
||||
}
|
||||
};
|
||||
if let Some(mut stdin) = child.stdin.take() {
|
||||
let _ = stdin.write_all(typed.as_bytes());
|
||||
}
|
||||
let started = Instant::now();
|
||||
let ok = loop {
|
||||
match child.try_wait() {
|
||||
Ok(Some(status)) => break status.success(),
|
||||
Ok(None) => {}
|
||||
Err(_) => break false,
|
||||
}
|
||||
let wanted = still_wanted(id);
|
||||
if !wanted || started.elapsed() > PATIENCE {
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
if wanted {
|
||||
finish(id, pane_id, typed, None);
|
||||
}
|
||||
return;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(25));
|
||||
};
|
||||
let mut answer = String::new();
|
||||
if ok {
|
||||
if let Some(out) = child.stdout.take() {
|
||||
let _ = out.take(8192).read_to_string(&mut answer);
|
||||
}
|
||||
}
|
||||
let rest = suggest::clean_completion(&answer, &typed);
|
||||
finish(id, pane_id, typed, rest);
|
||||
}
|
||||
|
||||
/// The rest of the line, when LLeMbas has answered for exactly this line.
|
||||
/// Otherwise `None`, and LLeMbas is asked (once for a line): when the answer
|
||||
/// comes the pane is drawn again.
|
||||
pub fn suggestion(
|
||||
pane: &Arc<dyn Pane>,
|
||||
typed: &str,
|
||||
cli: &str,
|
||||
cwd: Option<String>,
|
||||
) -> Option<String> {
|
||||
if typed.starts_with(' ') || typed.len() > MAX_BYTES || typed.chars().count() < MIN_CHARS {
|
||||
return None;
|
||||
}
|
||||
let pane_id = pane.pane_id();
|
||||
let mut ai = AI.lock();
|
||||
if let Some((line, rest)) = ai.answers.get(&pane_id) {
|
||||
if line == typed {
|
||||
return rest.clone();
|
||||
}
|
||||
}
|
||||
if let Some((p, line, _)) = &ai.wanted {
|
||||
if *p == pane_id && line == typed {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
ai.next_id += 1;
|
||||
let id = ai.next_id;
|
||||
ai.wanted = Some((pane_id, typed.to_string(), id));
|
||||
drop(ai);
|
||||
|
||||
let shell = shell_of(pane);
|
||||
let typed = typed.to_string();
|
||||
let cli = cli.to_string();
|
||||
let spawned = std::thread::Builder::new()
|
||||
.name("llembas-complete".to_string())
|
||||
.spawn(move || ask(id, pane_id, typed, cli, shell, cwd));
|
||||
if let Err(err) = spawned {
|
||||
log::warn!(
|
||||
"LLeMbas: could not start a thread to ask for a completion: {:#}",
|
||||
err
|
||||
);
|
||||
}
|
||||
None
|
||||
}
|
||||
@@ -0,0 +1,694 @@
|
||||
//! LLeMbas TTY: what the terminal draws on the shell's input line.
|
||||
//!
|
||||
//! - the rest of the line, dimmed after the cursor: from the terminal's own
|
||||
//! history of commands, or from LLeMbas when the AI's autocomplete is on;
|
||||
//! - the command line in colours;
|
||||
//! - a word from the terminal at the cursor's row, for a moment.
|
||||
//!
|
||||
//! All of it is drawn at the moment a pane is painted and nowhere else:
|
||||
//! nothing is written to the pane, and the terminal's own model of the screen
|
||||
//! is not touched. The pane's lines are handed to the painter as they are,
|
||||
//! except for the few rows that are drawn differently, which are copies. The
|
||||
//! same way the terminal's quick select marks its matches.
|
||||
//!
|
||||
//! It needs the shell integration (which marks the cells of the input line)
|
||||
//! and is off for a pane while a full-screen program has it.
|
||||
//!
|
||||
//! What a line of text means is `llembas_line` (the input line among the
|
||||
//! cells, the parts of a command line, the history); this file fetches the
|
||||
//! cells and places the result.
|
||||
|
||||
use super::{complete, state};
|
||||
use llembas_line::suggest;
|
||||
use llembas_line::tokens::{self, Kind, Role};
|
||||
use llembas_line::zone::{self, Zone};
|
||||
use mux::pane::{CachePolicy, Pane, PaneId, WithPaneLines};
|
||||
use mux::renderable::{RenderableDimensions, StableCursorPosition};
|
||||
use mux::Mux;
|
||||
use parking_lot::Mutex;
|
||||
use std::collections::HashMap;
|
||||
use std::io::Write;
|
||||
use std::ops::Range;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
use termwiz::cell::{CellAttributes, Intensity, SemanticType};
|
||||
use termwiz::color::ColorAttribute;
|
||||
use termwiz::surface::{SequenceNo, SEQ_ZERO};
|
||||
use wezterm_term::{Line, StableRowIndex};
|
||||
|
||||
/// An input line of more rows than this is left alone.
|
||||
const MAX_ROWS: usize = 3;
|
||||
/// How long it is remembered whether a command exists.
|
||||
const COMMAND_MEMORY: Duration = Duration::from_secs(20);
|
||||
|
||||
/// What is drawn differently on one row.
|
||||
#[derive(Debug, Clone)]
|
||||
struct RowPlan {
|
||||
row: StableRowIndex,
|
||||
/// The text colour of some cells: first column, columns, colour.
|
||||
colors: Vec<(usize, usize, ColorAttribute)>,
|
||||
/// Text placed from a column on.
|
||||
texts: Vec<(usize, String, CellAttributes)>,
|
||||
}
|
||||
|
||||
/// What is drawn differently in a pane.
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct Plan {
|
||||
/// By row, each row once.
|
||||
rows: Vec<RowPlan>,
|
||||
/// The rest of the line that is offered after the cursor, all of it.
|
||||
pub suggestion: Option<String>,
|
||||
}
|
||||
|
||||
impl Plan {
|
||||
fn row_mut(&mut self, row: StableRowIndex) -> &mut RowPlan {
|
||||
let at = match self.rows.iter().position(|r| r.row == row) {
|
||||
Some(at) => at,
|
||||
None => {
|
||||
self.rows.push(RowPlan {
|
||||
row,
|
||||
colors: Vec::new(),
|
||||
texts: Vec::new(),
|
||||
});
|
||||
self.rows.len() - 1
|
||||
}
|
||||
};
|
||||
&mut self.rows[at]
|
||||
}
|
||||
}
|
||||
|
||||
/// What a plan was worked out for. While it is the same, so is the plan.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
struct PlanKey {
|
||||
seqno: SequenceNo,
|
||||
x: usize,
|
||||
y: StableRowIndex,
|
||||
cols: usize,
|
||||
top: StableRowIndex,
|
||||
active: bool,
|
||||
generation: u64,
|
||||
}
|
||||
|
||||
lazy_static::lazy_static! {
|
||||
static ref PLANS: Mutex<HashMap<PaneId, (PlanKey, Option<Arc<Plan>>)>> =
|
||||
Mutex::new(HashMap::new());
|
||||
/// Whether a command exists, and when that was looked up.
|
||||
static ref COMMANDS: Mutex<HashMap<String, (bool, Instant)>> = Mutex::new(HashMap::new());
|
||||
}
|
||||
|
||||
/// The columns a character takes.
|
||||
fn char_width(c: char) -> usize {
|
||||
let mut buf = [0u8; 4];
|
||||
wezterm_term::unicode_column_width(c.encode_utf8(&mut buf), None)
|
||||
}
|
||||
|
||||
fn text_width(text: &str) -> usize {
|
||||
text.chars().map(char_width).sum()
|
||||
}
|
||||
|
||||
/// The cells of a line, for `llembas_line::zone`.
|
||||
fn row_of(line: &Line) -> zone::Row {
|
||||
line.visible_cells()
|
||||
.map(|cell| zone::Cell {
|
||||
col: cell.cell_index(),
|
||||
width: cell.width(),
|
||||
text: cell.str().to_string(),
|
||||
input: cell.attrs().semantic_type() == SemanticType::Input,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The column after the last cell of a line that shows something.
|
||||
fn used_cols(line: &Line) -> usize {
|
||||
let mut used = 0;
|
||||
for cell in line.visible_cells() {
|
||||
if !cell.str().trim().is_empty() {
|
||||
used = cell.cell_index() + cell.width().max(1);
|
||||
}
|
||||
}
|
||||
used
|
||||
}
|
||||
|
||||
/// The blank columns of a line from column `from` on, up to the first cell
|
||||
/// that shows something.
|
||||
fn blank_room(line: &Line, from: usize, cols: usize) -> usize {
|
||||
if from >= cols {
|
||||
return 0;
|
||||
}
|
||||
let mut end = cols;
|
||||
for cell in line.visible_cells() {
|
||||
if cell.cell_index() >= from && !cell.str().trim().is_empty() {
|
||||
end = cell.cell_index().min(cols);
|
||||
break;
|
||||
}
|
||||
}
|
||||
end.saturating_sub(from)
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn this_host() -> Option<String> {
|
||||
let mut buf = [0u8; 256];
|
||||
let rc = unsafe { libc::gethostname(buf.as_mut_ptr() as *mut libc::c_char, buf.len() - 1) };
|
||||
if rc != 0 {
|
||||
return None;
|
||||
}
|
||||
let len = buf.iter().position(|b| *b == 0).unwrap_or(buf.len());
|
||||
Some(String::from_utf8_lossy(&buf[..len]).to_lowercase())
|
||||
}
|
||||
|
||||
#[cfg(not(unix))]
|
||||
fn this_host() -> Option<String> {
|
||||
None
|
||||
}
|
||||
|
||||
/// Is `host` (of a pane's directory, as its shell reported it) this machine?
|
||||
fn is_this_host(host: &str) -> bool {
|
||||
let host = host.to_lowercase();
|
||||
if host.is_empty() || host == "localhost" {
|
||||
return true;
|
||||
}
|
||||
match this_host() {
|
||||
Some(mine) => {
|
||||
let short = |s: &str| s.split('.').next().unwrap_or("").to_string();
|
||||
mine == host || short(&mine) == short(&host)
|
||||
}
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// What can be looked up for a pane whose shell is on this machine: whether a
|
||||
/// command exists and whether a path does. `None` for a shell somewhere else
|
||||
/// (a pane of another domain, or `ssh` inside a pane), where this machine's
|
||||
/// files say nothing.
|
||||
struct Lookups {
|
||||
cwd: Option<PathBuf>,
|
||||
}
|
||||
|
||||
impl Lookups {
|
||||
fn for_pane(pane: &Arc<dyn Pane>) -> Option<Lookups> {
|
||||
let mux = Mux::try_get()?;
|
||||
let domain = mux.get_domain(pane.domain_id())?;
|
||||
if domain.domain_name() != "local" {
|
||||
return None;
|
||||
}
|
||||
let cwd = match pane.get_current_working_dir(CachePolicy::AllowStale) {
|
||||
Some(url) => {
|
||||
if !is_this_host(url.host_str().unwrap_or("")) {
|
||||
return None;
|
||||
}
|
||||
url.to_file_path().ok()
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
Some(Lookups { cwd })
|
||||
}
|
||||
|
||||
/// A word as a path of this machine; `None` when it cannot be one.
|
||||
fn resolve(&self, word: &str) -> Option<PathBuf> {
|
||||
if word.is_empty() || word.len() > 512 {
|
||||
return None;
|
||||
}
|
||||
if word == "~" {
|
||||
return Some(config::HOME_DIR.clone());
|
||||
}
|
||||
if let Some(rest) = word.strip_prefix("~/") {
|
||||
return Some(config::HOME_DIR.join(rest));
|
||||
}
|
||||
if word.starts_with('~') {
|
||||
return None;
|
||||
}
|
||||
let path = Path::new(word);
|
||||
if path.is_absolute() {
|
||||
return Some(path.to_path_buf());
|
||||
}
|
||||
self.cwd.as_ref().map(|cwd| cwd.join(path))
|
||||
}
|
||||
|
||||
fn path_exists(&self, word: &str) -> bool {
|
||||
match self.resolve(word) {
|
||||
Some(path) => path.exists(),
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn command_exists(&self, word: &str) -> bool {
|
||||
if word.is_empty() {
|
||||
return false;
|
||||
}
|
||||
if tokens::is_builtin(word) {
|
||||
return true;
|
||||
}
|
||||
if word.contains('/') {
|
||||
return match self.resolve(word) {
|
||||
Some(path) => is_program(&path),
|
||||
None => false,
|
||||
};
|
||||
}
|
||||
let now = Instant::now();
|
||||
let mut known = COMMANDS.lock();
|
||||
if let Some((exists, at)) = known.get(word) {
|
||||
if now.duration_since(*at) < COMMAND_MEMORY {
|
||||
return *exists;
|
||||
}
|
||||
}
|
||||
let exists = match std::env::var_os("PATH") {
|
||||
Some(path) => std::env::split_paths(&path).any(|dir| is_program(&dir.join(word))),
|
||||
None => false,
|
||||
};
|
||||
if known.len() > 1024 {
|
||||
known.clear();
|
||||
}
|
||||
known.insert(word.to_string(), (exists, now));
|
||||
exists
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn is_program(path: &Path) -> bool {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
match std::fs::metadata(path) {
|
||||
Ok(meta) => meta.is_file() && meta.permissions().mode() & 0o111 != 0,
|
||||
Err(_) => false,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(unix))]
|
||||
fn is_program(path: &Path) -> bool {
|
||||
path.is_file()
|
||||
}
|
||||
|
||||
/// The colours of the input line.
|
||||
fn highlight(
|
||||
pane: &Arc<dyn Pane>,
|
||||
colors: &state::Colors,
|
||||
zone: &Zone,
|
||||
top: StableRowIndex,
|
||||
plan: &mut Plan,
|
||||
) {
|
||||
let parsed = tokens::parse(&zone.text);
|
||||
if parsed.tokens.is_empty() {
|
||||
return;
|
||||
}
|
||||
let mut token_colors: Vec<state::Color> = parsed
|
||||
.tokens
|
||||
.iter()
|
||||
.map(|token| match token.kind {
|
||||
Kind::Option => colors.option,
|
||||
Kind::String => colors.string,
|
||||
Kind::Variable => colors.variable,
|
||||
Kind::Operator => colors.operator,
|
||||
Kind::Comment => colors.comment,
|
||||
// decided below, by what the word turns out to be
|
||||
Kind::Command | Kind::Word => None,
|
||||
})
|
||||
.collect();
|
||||
|
||||
// Whether a command exists, whether a path does: only where this
|
||||
// machine's files can say.
|
||||
if let Some(lookups) = Lookups::for_pane(pane) {
|
||||
for word in &parsed.words {
|
||||
let value = match &word.value {
|
||||
Some(value) => value,
|
||||
None => continue,
|
||||
};
|
||||
let (kind, color) = match word.role {
|
||||
Role::Command => (
|
||||
Kind::Command,
|
||||
if lookups.command_exists(value) {
|
||||
colors.command
|
||||
} else {
|
||||
colors.unknown
|
||||
},
|
||||
),
|
||||
Role::Argument | Role::Target => {
|
||||
if !lookups.path_exists(value) {
|
||||
continue;
|
||||
}
|
||||
(Kind::Word, colors.path)
|
||||
}
|
||||
Role::Option | Role::Assignment => continue,
|
||||
};
|
||||
for (i, token) in parsed.tokens.iter().enumerate() {
|
||||
if token.kind == kind && token.start >= word.start && token.end <= word.end {
|
||||
token_colors[i] = color;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut t = 0;
|
||||
for piece in &zone.pieces {
|
||||
while t < parsed.tokens.len() && parsed.tokens[t].end <= piece.start {
|
||||
t += 1;
|
||||
}
|
||||
if t >= parsed.tokens.len() {
|
||||
break;
|
||||
}
|
||||
let token = &parsed.tokens[t];
|
||||
if piece.start < token.start {
|
||||
continue;
|
||||
}
|
||||
if let Some(color) = token_colors[t] {
|
||||
plan.row_mut(top + piece.row as StableRowIndex)
|
||||
.colors
|
||||
.push((piece.col, piece.width, color));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The rest of the line, offered after the cursor.
|
||||
fn ghost(
|
||||
pane: &Arc<dyn Pane>,
|
||||
options: &state::Options,
|
||||
zone: &Zone,
|
||||
line: &Line,
|
||||
cursor: &StableCursorPosition,
|
||||
cols: usize,
|
||||
plan: &mut Plan,
|
||||
) {
|
||||
if !zone.at_end() {
|
||||
return;
|
||||
}
|
||||
let typed = zone.typed();
|
||||
if typed.trim().is_empty() {
|
||||
return;
|
||||
}
|
||||
let pane_id = pane.pane_id();
|
||||
let mut found: Option<(String, suggest::Source)> = None;
|
||||
if options.suggestions {
|
||||
if let Some(rest) = state::history_suggest(typed) {
|
||||
found = Some((rest, suggest::Source::History));
|
||||
}
|
||||
}
|
||||
// LLeMbas is asked only when the history has nothing, never for a private
|
||||
// pane, and only for a shell on this machine.
|
||||
if found.is_none()
|
||||
&& options.ai_complete
|
||||
&& !options.cli.is_empty()
|
||||
&& !state::is_private(pane_id)
|
||||
{
|
||||
if let Some(lookups) = Lookups::for_pane(pane) {
|
||||
let cwd = lookups
|
||||
.cwd
|
||||
.as_ref()
|
||||
.and_then(|cwd| cwd.to_str())
|
||||
.map(|cwd| cwd.to_string());
|
||||
if let Some(rest) = complete::suggestion(pane, typed, &options.cli, cwd) {
|
||||
found = Some((rest, suggest::Source::Ai));
|
||||
}
|
||||
}
|
||||
}
|
||||
let (rest, source) = match found {
|
||||
Some(found) => found,
|
||||
None => return,
|
||||
};
|
||||
let rest = match suggest::clean_rest(&rest) {
|
||||
Some(rest) => rest,
|
||||
None => return,
|
||||
};
|
||||
let shown = suggest::fit(&rest, blank_room(line, cursor.x, cols), &char_width);
|
||||
if shown.is_empty() {
|
||||
return;
|
||||
}
|
||||
let mut attr = CellAttributes::default();
|
||||
match options.colors.ghost {
|
||||
Some(color) => {
|
||||
attr.set_foreground(color);
|
||||
}
|
||||
None => {
|
||||
attr.set_intensity(Intensity::Half);
|
||||
}
|
||||
}
|
||||
// what LLeMbas offered is told apart from what the history did
|
||||
if source == suggest::Source::Ai {
|
||||
attr.set_italic(true);
|
||||
}
|
||||
plan.row_mut(cursor.y).texts.push((cursor.x, shown, attr));
|
||||
plan.suggestion = Some(rest);
|
||||
}
|
||||
|
||||
/// A word from the terminal, at the right of a row.
|
||||
fn place_notice(
|
||||
text: &str,
|
||||
line: Option<&Line>,
|
||||
row: StableRowIndex,
|
||||
taken: usize,
|
||||
cols: usize,
|
||||
colors: &state::Colors,
|
||||
plan: &mut Plan,
|
||||
) {
|
||||
let mut attr = CellAttributes::default();
|
||||
attr.set_italic(true);
|
||||
if let Some(color) = colors.notice {
|
||||
attr.set_foreground(color);
|
||||
}
|
||||
let used = line.map(used_cols).unwrap_or(0).max(taken);
|
||||
let free = cols.saturating_sub(used + 2);
|
||||
let wanted = text_width(text);
|
||||
let room = if free >= wanted.min(16) {
|
||||
free
|
||||
} else {
|
||||
// no room beside what the row shows: over its end, set apart
|
||||
attr.set_reverse(true);
|
||||
cols.saturating_sub(1)
|
||||
};
|
||||
let shown = suggest::fit(text, room, &char_width);
|
||||
if shown.is_empty() {
|
||||
return;
|
||||
}
|
||||
let col = cols.saturating_sub(text_width(&shown));
|
||||
plan.row_mut(row).texts.push((col, shown, attr));
|
||||
}
|
||||
|
||||
fn compute(
|
||||
pane: &Arc<dyn Pane>,
|
||||
active: bool,
|
||||
options: &state::Options,
|
||||
notice: Option<String>,
|
||||
cursor: &StableCursorPosition,
|
||||
dims: &RenderableDimensions,
|
||||
) -> Option<Plan> {
|
||||
let mut plan = Plan::default();
|
||||
let alt = pane.is_alt_screen_active();
|
||||
let bottom = dims.physical_top + (dims.viewport_rows as StableRowIndex - 1).max(0);
|
||||
let around = MAX_ROWS as StableRowIndex;
|
||||
|
||||
let mut cursor_line: Option<Line> = None;
|
||||
let mut taken = 0;
|
||||
if !alt {
|
||||
let first = (cursor.y - around).max(dims.scrollback_top);
|
||||
let (top, lines) = pane.get_lines(first..cursor.y + around + 1);
|
||||
let at = cursor.y - top;
|
||||
if at >= 0 && (at as usize) < lines.len() {
|
||||
let at = at as usize;
|
||||
if options.suggestions || options.highlight || options.ai_complete {
|
||||
let rows: Vec<zone::Row> = lines.iter().map(row_of).collect();
|
||||
if let Some(zone) = zone::input_zone(&rows, at, cursor.x, dims.cols, MAX_ROWS) {
|
||||
if options.highlight {
|
||||
highlight(pane, &options.colors, &zone, top, &mut plan);
|
||||
}
|
||||
if active && (options.suggestions || options.ai_complete) {
|
||||
ghost(
|
||||
pane, options, &zone, &lines[at], cursor, dims.cols, &mut plan,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(row) = plan.rows.iter().find(|r| r.row == cursor.y) {
|
||||
for (col, text, _) in &row.texts {
|
||||
taken = taken.max(col + text_width(text));
|
||||
}
|
||||
}
|
||||
taken = taken.max(cursor.x + 1);
|
||||
cursor_line = Some(lines[at].clone());
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(text) = notice {
|
||||
if alt || cursor_line.is_none() {
|
||||
let (top, lines) = pane.get_lines(bottom..bottom + 1);
|
||||
let line = if top == bottom { lines.first() } else { None };
|
||||
place_notice(
|
||||
&text,
|
||||
line,
|
||||
bottom,
|
||||
0,
|
||||
dims.cols,
|
||||
&options.colors,
|
||||
&mut plan,
|
||||
);
|
||||
} else {
|
||||
place_notice(
|
||||
&text,
|
||||
cursor_line.as_ref(),
|
||||
cursor.y,
|
||||
taken,
|
||||
dims.cols,
|
||||
&options.colors,
|
||||
&mut plan,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if plan.rows.is_empty() {
|
||||
return None;
|
||||
}
|
||||
plan.rows.sort_by_key(|r| r.row);
|
||||
Some(plan)
|
||||
}
|
||||
|
||||
/// What is drawn differently in this pane now; `None` for nothing, which is
|
||||
/// the answer for every pane until the layer turned something on.
|
||||
pub fn plan_for(pane: &Arc<dyn Pane>, active: bool) -> Option<Arc<Plan>> {
|
||||
let options = state::options();
|
||||
let pane_id = pane.pane_id();
|
||||
let notice = state::notice(pane_id);
|
||||
if !(options.suggestions || options.highlight || options.ai_complete) && notice.is_none() {
|
||||
return None;
|
||||
}
|
||||
// The pane itself, never something drawn over it (search, copy mode, the
|
||||
// ask line): those draw their own.
|
||||
let real = Mux::try_get()?.get_pane(pane_id)?;
|
||||
if Arc::as_ptr(&real) as *const () != Arc::as_ptr(pane) as *const () {
|
||||
return None;
|
||||
}
|
||||
|
||||
let cursor = pane.get_cursor_position();
|
||||
let dims = pane.get_dimensions();
|
||||
let key = PlanKey {
|
||||
seqno: pane.get_current_seqno(),
|
||||
x: cursor.x,
|
||||
y: cursor.y,
|
||||
cols: dims.cols,
|
||||
top: dims.physical_top,
|
||||
active,
|
||||
generation: state::generation(),
|
||||
};
|
||||
if let Some((known, plan)) = PLANS.lock().get(&pane_id) {
|
||||
if *known == key {
|
||||
return plan.clone();
|
||||
}
|
||||
}
|
||||
let plan = compute(pane, active, &options, notice, &cursor, &dims).map(Arc::new);
|
||||
let mut plans = PLANS.lock();
|
||||
if plans.len() > 256 {
|
||||
plans.clear();
|
||||
}
|
||||
plans.insert(pane_id, (key, plan.clone()));
|
||||
plan
|
||||
}
|
||||
|
||||
/// Hand a pane's lines to the painter, with what the terminal draws on them.
|
||||
/// Called where a pane is painted, in place of the pane's own `with_lines_mut`.
|
||||
pub fn with_lines_mut(
|
||||
pane: &Arc<dyn Pane>,
|
||||
active: bool,
|
||||
lines: Range<StableRowIndex>,
|
||||
with_lines: &mut dyn WithPaneLines,
|
||||
) {
|
||||
let plan = match plan_for(pane, active) {
|
||||
Some(plan) => plan,
|
||||
None => {
|
||||
pane.with_lines_mut(lines, with_lines);
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
struct Decorated<'a> {
|
||||
with_lines: &'a mut dyn WithPaneLines,
|
||||
plan: Arc<Plan>,
|
||||
}
|
||||
|
||||
impl<'a> WithPaneLines for Decorated<'a> {
|
||||
fn with_lines_mut(&mut self, first_row: StableRowIndex, lines: &mut [&mut Line]) {
|
||||
// Copies of the rows that are drawn differently; every other row
|
||||
// is handed on as it is.
|
||||
let mut changed: Vec<(usize, Line)> = Vec::new();
|
||||
for row in &self.plan.rows {
|
||||
let offset = row.row - first_row;
|
||||
if offset < 0 || offset as usize >= lines.len() {
|
||||
continue;
|
||||
}
|
||||
let idx = offset as usize;
|
||||
let mut line: Line = (*lines[idx]).clone();
|
||||
if !row.colors.is_empty() {
|
||||
let cells = line.cells_mut_for_attr_changes_only();
|
||||
for (col, width, color) in &row.colors {
|
||||
for c in *col..(*col + *width) {
|
||||
if let Some(cell) = cells.get_mut(c) {
|
||||
cell.attrs_mut().set_foreground(*color);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for (col, text, attr) in &row.texts {
|
||||
line.overlay_text_with_attribute(*col, text, attr.clone(), SEQ_ZERO);
|
||||
}
|
||||
line.clear_appdata();
|
||||
changed.push((idx, line));
|
||||
}
|
||||
if changed.is_empty() {
|
||||
self.with_lines.with_lines_mut(first_row, lines);
|
||||
return;
|
||||
}
|
||||
let mut ours = changed
|
||||
.iter_mut()
|
||||
.map(|(idx, line)| (*idx, line))
|
||||
.peekable();
|
||||
let mut refs: Vec<&mut Line> = Vec::with_capacity(lines.len());
|
||||
for (idx, line) in lines.iter_mut().enumerate() {
|
||||
let replaced = match ours.peek() {
|
||||
Some((at, _)) => *at == idx,
|
||||
None => false,
|
||||
};
|
||||
if replaced {
|
||||
if let Some((_, line)) = ours.next() {
|
||||
refs.push(line);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
refs.push(&mut **line);
|
||||
}
|
||||
self.with_lines.with_lines_mut(first_row, &mut refs);
|
||||
}
|
||||
}
|
||||
|
||||
pane.with_lines_mut(lines, &mut Decorated { with_lines, plan });
|
||||
}
|
||||
|
||||
/// A key that takes the suggestion shown after the cursor: Right or End takes
|
||||
/// all of it, Alt+Right one word. What is taken is sent to the shell as if it
|
||||
/// were typed; nothing runs. `false` when there is no suggestion, or the key
|
||||
/// is another: then the key goes where it always went.
|
||||
pub fn take_suggestion(
|
||||
pane: &Arc<dyn Pane>,
|
||||
key: &::window::KeyCode,
|
||||
mods: ::window::Modifiers,
|
||||
) -> bool {
|
||||
use ::window::{KeyCode, Modifiers};
|
||||
let mods = mods.remove_positional_mods();
|
||||
let arrow = matches!(key, KeyCode::RightArrow);
|
||||
let whole = (arrow || matches!(key, KeyCode::End)) && mods == Modifiers::NONE;
|
||||
let word = arrow && mods == Modifiers::ALT;
|
||||
if !whole && !word {
|
||||
return false;
|
||||
}
|
||||
let plan = match plan_for(pane, true) {
|
||||
Some(plan) => plan,
|
||||
None => return false,
|
||||
};
|
||||
let rest = match &plan.suggestion {
|
||||
Some(rest) => rest,
|
||||
None => return false,
|
||||
};
|
||||
let text = if whole {
|
||||
rest.as_str()
|
||||
} else {
|
||||
suggest::first_word(rest)
|
||||
};
|
||||
if text.is_empty() {
|
||||
return false;
|
||||
}
|
||||
pane.writer().write_all(text.as_bytes()).is_ok()
|
||||
}
|
||||
@@ -9,7 +9,9 @@ use crate::scripting::guiwin::GuiWin;
|
||||
use crate::termwindow::TermWindowNotif;
|
||||
use config::lua::get_or_create_sub_module;
|
||||
use mlua::{Lua, Table, UserDataRef, Value};
|
||||
use mux::{Mux, MuxNotification};
|
||||
use mux_lua::MuxPane;
|
||||
use std::time::Duration;
|
||||
use termwiz::color::ColorAttribute;
|
||||
use window::WindowOps;
|
||||
|
||||
@@ -106,5 +108,67 @@ pub fn register(lua: &Lua) -> anyhow::Result<()> {
|
||||
)?,
|
||||
)?;
|
||||
|
||||
// notice(pane, text): a word for the person at the cursor's row of the
|
||||
// pane, for a moment. It takes no key and nothing has to be dismissed.
|
||||
module.set(
|
||||
"notice",
|
||||
lua.create_function(|_, (pane, text): (UserDataRef<MuxPane>, String)| {
|
||||
let pane_id = pane.0;
|
||||
let text: String = text.chars().filter(|c| !c.is_control()).take(200).collect();
|
||||
state::set_notice(pane_id, text);
|
||||
Mux::notify_from_any_thread(MuxNotification::PaneOutput(pane_id));
|
||||
// and the pane is drawn again when its time is over
|
||||
promise::spawn::spawn(async move {
|
||||
smol::Timer::after(state::NOTICE_TIME + Duration::from_millis(50)).await;
|
||||
state::changed();
|
||||
Mux::notify_from_any_thread(MuxNotification::PaneOutput(pane_id));
|
||||
})
|
||||
.detach();
|
||||
Ok(true)
|
||||
})?,
|
||||
)?;
|
||||
|
||||
// set_private(pane id, on): a private pane's commands are not remembered
|
||||
// and nothing of it is sent to LLeMbas for a completion.
|
||||
module.set(
|
||||
"set_private",
|
||||
lua.create_function(|_, (pane_id, on): (usize, bool)| {
|
||||
state::set_private(pane_id, on);
|
||||
Ok(())
|
||||
})?,
|
||||
)?;
|
||||
|
||||
// command_ended(pane, exit status or -1, directory): the shell said that a
|
||||
// command ended in this pane. The terminal remembers it for its suggestions.
|
||||
module.set(
|
||||
"command_ended",
|
||||
lua.create_function(
|
||||
|_, (pane, exit, cwd): (UserDataRef<MuxPane>, i64, Option<String>)| {
|
||||
let exit = if (0..=255).contains(&exit) {
|
||||
exit as i32
|
||||
} else {
|
||||
llembas_line::history::NO_EXIT
|
||||
};
|
||||
let cwd: String = cwd
|
||||
.unwrap_or_default()
|
||||
.chars()
|
||||
.filter(|c| !c.is_control())
|
||||
.take(1024)
|
||||
.collect();
|
||||
super::record::command_ended(pane.0, exit, cwd);
|
||||
Ok(())
|
||||
},
|
||||
)?,
|
||||
)?;
|
||||
|
||||
// clear_history(): forget every command the terminal remembered.
|
||||
module.set(
|
||||
"clear_history",
|
||||
lua.create_function(|_, _: ()| {
|
||||
state::history_clear();
|
||||
Ok(())
|
||||
})?,
|
||||
)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -4,6 +4,11 @@
|
||||
//! What Lua cannot do is draw on a pane or take its keys, and that is here:
|
||||
//!
|
||||
//! - [`ask`]: the ask line, in place of the shell's own line;
|
||||
//! - [`decorate`]: what is drawn on the shell's input line when a pane is
|
||||
//! painted - the suggestion after the cursor, the colours of the command
|
||||
//! line, a word from the terminal - and the key that takes a suggestion;
|
||||
//! - [`record`]: remembering a command that ran, for the suggestions;
|
||||
//! - [`complete`]: asking LLeMbas for the rest of a line;
|
||||
//! - [`lua`]: `wezterm.llembas`, through which the layer asks for it;
|
||||
//! - [`state`]: what the layer said is on, and what outlives one pane.
|
||||
//!
|
||||
@@ -13,8 +18,12 @@
|
||||
//! are. The files here are the thin part between it and the terminal.
|
||||
//!
|
||||
//! Nothing here starts a process, reads a pane or writes a file until the
|
||||
//! layer asks, and the layer asks only when the person pressed a key.
|
||||
//! layer said what is on. With nothing on (no layer, or a terminal started
|
||||
//! with `--skip-config`) a pane is painted exactly as upstream paints it.
|
||||
|
||||
pub mod ask;
|
||||
pub mod complete;
|
||||
pub mod decorate;
|
||||
pub mod lua;
|
||||
pub mod record;
|
||||
pub mod state;
|
||||
@@ -0,0 +1,112 @@
|
||||
//! LLeMbas TTY: remembering a command that ran, for the suggestions.
|
||||
//!
|
||||
//! The shell integration says that a command ended (the pane's status record,
|
||||
//! which the layer reads). The command's text is then read from the pane's
|
||||
//! own screen: the input line the shell marked. Nothing typed is followed,
|
||||
//! so nothing typed while a program asked for a password can be taken: such
|
||||
//! text is never on the screen.
|
||||
|
||||
use super::state;
|
||||
use llembas_line::history::Entry;
|
||||
use mux::pane::{Pane, PaneId};
|
||||
use mux::Mux;
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
||||
use termwiz::cell::SemanticType;
|
||||
use wezterm_term::{SemanticZone, StableRowIndex};
|
||||
|
||||
/// An input line of more rows than this is no command to remember.
|
||||
const MAX_ROWS: StableRowIndex = 8;
|
||||
|
||||
/// The columns of a zone on one of its rows.
|
||||
fn cols_for_row(zone: &SemanticZone, row: StableRowIndex) -> std::ops::Range<usize> {
|
||||
if row < zone.start_y || row > zone.end_y {
|
||||
0..0
|
||||
} else if zone.start_y == zone.end_y {
|
||||
zone.start_x.min(zone.end_x)..zone.start_x.max(zone.end_x).saturating_add(1)
|
||||
} else if row == zone.end_y {
|
||||
0..zone.end_x.saturating_add(1)
|
||||
} else if row == zone.start_y {
|
||||
zone.start_x..usize::MAX
|
||||
} else {
|
||||
0..usize::MAX
|
||||
}
|
||||
}
|
||||
|
||||
/// The text of a zone: its rows joined, with a line break where a row ended
|
||||
/// and was not carried on by wrapping.
|
||||
fn zone_text(pane: &Arc<dyn Pane>, zone: &SemanticZone) -> String {
|
||||
let (top, lines) = pane.get_lines(zone.start_y..zone.end_y + 1);
|
||||
let mut text = String::new();
|
||||
let mut wrapped = true;
|
||||
for (i, line) in lines.iter().enumerate() {
|
||||
let row = top + i as StableRowIndex;
|
||||
let cols = cols_for_row(zone, row);
|
||||
if cols.start >= cols.end {
|
||||
continue;
|
||||
}
|
||||
if !wrapped && !text.is_empty() {
|
||||
text.push('\n');
|
||||
}
|
||||
text.push_str(&line.columns_as_str(cols));
|
||||
wrapped = line.last_cell_was_wrapped();
|
||||
}
|
||||
text.trim_end().to_string()
|
||||
}
|
||||
|
||||
fn remember(pane_id: PaneId, exit: i32, cwd: String) {
|
||||
if !state::options().history || state::is_private(pane_id) {
|
||||
return;
|
||||
}
|
||||
let pane = match Mux::try_get().and_then(|mux| mux.get_pane(pane_id)) {
|
||||
Some(pane) => pane,
|
||||
None => return,
|
||||
};
|
||||
if pane.is_alt_screen_active() {
|
||||
return;
|
||||
}
|
||||
let zones = match pane.get_semantic_zones() {
|
||||
Ok(zones) => zones,
|
||||
Err(_) => return,
|
||||
};
|
||||
// The command that ended is the last input line that something follows:
|
||||
// its output, or the next prompt. (An input line that nothing follows is
|
||||
// one still being typed.)
|
||||
let mut found = None;
|
||||
for (i, zone) in zones.iter().enumerate().rev() {
|
||||
if zone.semantic_type == SemanticType::Input && i + 1 < zones.len() {
|
||||
found = Some(*zone);
|
||||
break;
|
||||
}
|
||||
}
|
||||
let zone = match found {
|
||||
Some(zone) => zone,
|
||||
None => return,
|
||||
};
|
||||
if zone.end_y - zone.start_y >= MAX_ROWS
|
||||
|| !state::first_time(pane_id, zone.start_y, zone.start_x)
|
||||
{
|
||||
return;
|
||||
}
|
||||
let command = zone_text(&pane, &zone);
|
||||
let time = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.map(|d| d.as_secs())
|
||||
.unwrap_or(0);
|
||||
state::history_add(Entry {
|
||||
command,
|
||||
exit,
|
||||
cwd,
|
||||
time,
|
||||
});
|
||||
}
|
||||
|
||||
/// A command ended in this pane. Its text is read a moment later, when the
|
||||
/// shell has drawn its next prompt, so that the line is seen to be complete.
|
||||
pub fn command_ended(pane_id: PaneId, exit: i32, cwd: String) {
|
||||
promise::spawn::spawn(async move {
|
||||
smol::Timer::after(Duration::from_millis(150)).await;
|
||||
remember(pane_id, exit, cwd);
|
||||
})
|
||||
.detach();
|
||||
}
|
||||
@@ -1,7 +1,17 @@
|
||||
//! LLeMbas TTY: what the layer said is on, and what outlives one pane.
|
||||
|
||||
use llembas_line::history::{self, Entry, History};
|
||||
use mux::pane::PaneId;
|
||||
use parking_lot::Mutex;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::path::PathBuf;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::time::{Duration, Instant};
|
||||
use termwiz::color::ColorAttribute;
|
||||
use wezterm_term::StableRowIndex;
|
||||
|
||||
/// How long a word from the terminal stays at the cursor's row.
|
||||
pub const NOTICE_TIME: Duration = Duration::from_secs(4);
|
||||
|
||||
/// A colour of the layer's options: `None` leaves a cell as it was.
|
||||
pub type Color = Option<ColorAttribute>;
|
||||
@@ -33,7 +43,7 @@ impl Default for Colors {
|
||||
ghost: palette(8),
|
||||
notice: palette(3),
|
||||
command: palette(2),
|
||||
unknown: palette(1),
|
||||
unknown: None,
|
||||
option: None,
|
||||
string: palette(3),
|
||||
variable: palette(6),
|
||||
@@ -58,10 +68,37 @@ pub struct Options {
|
||||
pub colors: Colors,
|
||||
}
|
||||
|
||||
/// The terminal's own history of commands, once it was needed.
|
||||
struct Commands {
|
||||
history: History,
|
||||
max: usize,
|
||||
}
|
||||
|
||||
lazy_static::lazy_static! {
|
||||
static ref OPTIONS: Mutex<Options> = Mutex::new(Options::default());
|
||||
/// Earlier questions of the ask line, for this run of the terminal only.
|
||||
static ref QUESTIONS: Mutex<Vec<String>> = Mutex::new(Vec::new());
|
||||
/// Panes the person marked private: nothing of them is remembered or sent.
|
||||
static ref PRIVATE: Mutex<HashSet<PaneId>> = Mutex::new(HashSet::new());
|
||||
/// A word for the person at the cursor's row of a pane, and until when.
|
||||
static ref NOTICES: Mutex<HashMap<PaneId, (String, Instant)>> = Mutex::new(HashMap::new());
|
||||
static ref COMMANDS: Mutex<Option<Commands>> = Mutex::new(None);
|
||||
/// Where the command last remembered for a pane stood on its screen.
|
||||
static ref REMEMBERED: Mutex<HashMap<PaneId, (StableRowIndex, usize)>> =
|
||||
Mutex::new(HashMap::new());
|
||||
}
|
||||
|
||||
/// Goes up whenever something changed that what is drawn depends on and the
|
||||
/// pane's own content does not show: an option, a notice, the history, an
|
||||
/// answer that arrived.
|
||||
static GENERATION: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
pub fn generation() -> u64 {
|
||||
GENERATION.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
pub fn changed() {
|
||||
GENERATION.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
pub fn options() -> Options {
|
||||
@@ -70,6 +107,7 @@ pub fn options() -> Options {
|
||||
|
||||
pub fn set_options(options: Options) {
|
||||
*OPTIONS.lock() = options;
|
||||
changed();
|
||||
}
|
||||
|
||||
pub fn questions() -> Vec<String> {
|
||||
@@ -79,3 +117,122 @@ pub fn questions() -> Vec<String> {
|
||||
pub fn remember_question(line: &str) {
|
||||
llembas_line::editor::remember(&mut QUESTIONS.lock(), line);
|
||||
}
|
||||
|
||||
pub fn set_private(pane_id: PaneId, on: bool) {
|
||||
let mut private = PRIVATE.lock();
|
||||
if on {
|
||||
private.insert(pane_id);
|
||||
} else {
|
||||
private.remove(&pane_id);
|
||||
}
|
||||
drop(private);
|
||||
changed();
|
||||
}
|
||||
|
||||
pub fn is_private(pane_id: PaneId) -> bool {
|
||||
PRIVATE.lock().contains(&pane_id)
|
||||
}
|
||||
|
||||
pub fn set_notice(pane_id: PaneId, text: String) {
|
||||
NOTICES
|
||||
.lock()
|
||||
.insert(pane_id, (text, Instant::now() + NOTICE_TIME));
|
||||
changed();
|
||||
}
|
||||
|
||||
/// The word for a pane, while its time lasts.
|
||||
pub fn notice(pane_id: PaneId) -> Option<String> {
|
||||
let mut notices = NOTICES.lock();
|
||||
let live = match notices.get(&pane_id) {
|
||||
Some((text, until)) if Instant::now() < *until => Some(text.clone()),
|
||||
Some(_) => None,
|
||||
None => return None,
|
||||
};
|
||||
if live.is_none() {
|
||||
notices.remove(&pane_id);
|
||||
}
|
||||
live
|
||||
}
|
||||
|
||||
/// The file of the terminal's own command history: in its own data
|
||||
/// directory, the person's alone.
|
||||
pub fn history_path() -> PathBuf {
|
||||
config::DATA_DIR.join("command-history")
|
||||
}
|
||||
|
||||
/// Run `f` on the history, reading the file the first time and whenever the
|
||||
/// size it is kept at changed.
|
||||
fn with_commands<R>(f: impl FnOnce(&mut History) -> R) -> R {
|
||||
let max = OPTIONS.lock().history_max;
|
||||
let mut commands = COMMANDS.lock();
|
||||
let stale = match commands.as_ref() {
|
||||
Some(c) => c.max != max,
|
||||
None => true,
|
||||
};
|
||||
if stale {
|
||||
let history = match history::load(&history_path(), max) {
|
||||
Ok(history) => history,
|
||||
Err(err) => {
|
||||
log::warn!("LLeMbas: the command history could not be read: {:#}", err);
|
||||
History::new(max)
|
||||
}
|
||||
};
|
||||
*commands = Some(Commands { history, max });
|
||||
}
|
||||
match commands.as_mut() {
|
||||
Some(c) => f(&mut c.history),
|
||||
None => f(&mut History::new(0)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The rest of the newest command that starts with what is typed.
|
||||
pub fn history_suggest(typed: &str) -> Option<String> {
|
||||
with_commands(|history| history.suggest(typed).map(|rest| rest.to_string()))
|
||||
}
|
||||
|
||||
/// Remember a command that ran, in memory and in the file.
|
||||
pub fn history_add(entry: Entry) {
|
||||
let kept = with_commands(|history| {
|
||||
if history.add(entry.clone()) {
|
||||
history.entries().last().cloned()
|
||||
} else {
|
||||
None
|
||||
}
|
||||
});
|
||||
if let Some(kept) = kept {
|
||||
if let Err(err) = history::append(&history_path(), &kept) {
|
||||
log::warn!(
|
||||
"LLeMbas: the command history could not be written: {:#}",
|
||||
err
|
||||
);
|
||||
}
|
||||
changed();
|
||||
}
|
||||
}
|
||||
|
||||
/// Forget every command: in memory, and the file.
|
||||
pub fn history_clear() {
|
||||
with_commands(|history| history.clear());
|
||||
if let Err(err) = history::remove(&history_path()) {
|
||||
log::warn!(
|
||||
"LLeMbas: the command history could not be removed: {:#}",
|
||||
err
|
||||
);
|
||||
}
|
||||
changed();
|
||||
}
|
||||
|
||||
/// Is this the first time the command at this place of the pane's screen is
|
||||
/// remembered? (The shell says once that a command ended; this guards against
|
||||
/// taking the command before it a second time.)
|
||||
pub fn first_time(pane_id: PaneId, row: StableRowIndex, col: usize) -> bool {
|
||||
let mut remembered = REMEMBERED.lock();
|
||||
if remembered.get(&pane_id) == Some(&(row, col)) {
|
||||
return false;
|
||||
}
|
||||
if remembered.len() > 512 {
|
||||
remembered.clear();
|
||||
}
|
||||
remembered.insert(pane_id, (row, col));
|
||||
true
|
||||
}
|
||||
@@ -333,6 +333,17 @@ impl super::TermWindow {
|
||||
_ => OnlyKeyBindings::No,
|
||||
};
|
||||
|
||||
// LLeMbas TTY: a key that no binding took may take the suggestion
|
||||
// shown after the cursor (Right, End, Alt+Right); otherwise it goes on
|
||||
// to the pane as always
|
||||
if is_down
|
||||
&& only_key_bindings == OnlyKeyBindings::No
|
||||
&& crate::llembas::decorate::take_suggestion(pane, keycode, raw_modifiers)
|
||||
{
|
||||
context.invalidate();
|
||||
return true;
|
||||
}
|
||||
|
||||
if only_key_bindings == OnlyKeyBindings::No {
|
||||
let config = &self.config;
|
||||
|
||||
|
||||
@@ -565,7 +565,15 @@ impl crate::TermWindow {
|
||||
}
|
||||
}
|
||||
|
||||
pos.pane.with_lines_mut(stable_range.clone(), &mut render);
|
||||
// LLeMbas TTY: the pane's lines go to the painter through what the
|
||||
// terminal draws on the shell's input line (a suggestion, colours);
|
||||
// with none of that on, this is the pane's own with_lines_mut
|
||||
crate::llembas::decorate::with_lines_mut(
|
||||
&pos.pane,
|
||||
pos.is_active,
|
||||
stable_range.clone(),
|
||||
&mut render,
|
||||
);
|
||||
if let Some(error) = render.error.take() {
|
||||
return Err(error).context("error while calling with_lines_mut");
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user