experimental: renderer
All checks were successful
NeoVim tests / plenary-tests (push) Successful in 10s

This commit is contained in:
Jonathan Apodaca 2025-02-19 23:16:26 -07:00
parent de01a95cdc
commit a485094e90
10 changed files with 2255 additions and 27 deletions

196
README.md
View File

@ -6,6 +6,8 @@ This is meant to be used as a **library**, not a plugin. On its own, `u.nvim` do
## Features ## Features
- **Rendering System**: a utility that can declaratively render NeoVim-specific hyperscript into a buffer, supporting creating/managine extmarks, highlights, and key-event handling (requires NeoVim >0.11)
- **Signals**: a simple dependency tracking system that pairs well with the rendering utilities for creating reactive/interactive UIs in NeoVim.
- **Range Utility**: Get context-aware selections with ease. Replace regions with new text. Think of it as a programmatic way to work with visual selections (or regions of text). - **Range Utility**: Get context-aware selections with ease. Replace regions with new text. Think of it as a programmatic way to work with visual selections (or regions of text).
- **Code Writer**: Write code with automatic indentation and formatting. - **Code Writer**: Write code with automatic indentation and formatting.
- **Operator Key Mapping**: Flexible key mapping that works with the selected text. - **Operator Key Mapping**: Flexible key mapping that works with the selected text.
@ -20,7 +22,196 @@ lazy.nvim:
{ 'jrop/u.nvim', lazy = true } { 'jrop/u.nvim', lazy = true }
``` ```
## Usage ## Signal and Rendering Usage
### Overview
The Signal and Rendering mechanisms are two subsystems of u.nvim, that, while
simplistic, [compose](./examples/counter.lua) together
[powerfully](./examples/picker.lua) to create a system for interactive and
responsive user interfaces. Here is a quick example that show-cases how easy it
is to dive in to make any buffer an interactive UI:
<details>
<summary>Example Code: counter.lua</summary>
```lua
local tracker = require 'u.tracker'
local Buffer = require 'u.buffer'
local h = require('u.renderer').h
-- Create an buffer for the UI
vim.cmd.vnew()
local ui_buf = Buffer.current()
ui_buf:set_tmp_options()
local s_count = tracker.create_signal(0)
-- Effect: Render
-- Setup the effect for rendering the UI whenever dependencies are updated
tracker.create_effect(function()
-- Calling `Signal:get()` in an effect registers the given signal as a
-- dependency of the current effect. Whenever that signal (or any other
-- dependency) changes, the effect will rerun. In this particular case,
-- rendering the UI is an effect that depends on one signal.
local count = s_count:get()
-- Markup is hyperscript, which is just 1) text, and 2) tags (i.e.,
-- constructed with `h(...)` calls). To help organize the markup, text and
-- tags can be nested in tables at any depth. Line breaks must be specified
-- manually, with '\n'.
ui_buf:render {
'Reactive Counter Example\n',
'========================\n\n',
{ 'Counter: ', tostring(count), '\n' },
'\n',
{
h('text', {
hl = 'DiffDelete',
on_key = {
['\r'] = function()
-- Update the contents of the s_count signal, notifying any
-- dependencies (in this case, the render effect):
s_count:update(function(n) return n - 1 end)
-- Also equivalent: s_count:set(s_count:get() - 1)
return ''
end,
},
}, ' Decrement '),
' ',
h('text', {
hl = 'DiffAdd',
on_key = {
['\r'] = function()
-- Update the contents of the s_count signal, notifying any
-- dependencies (in this case, the render effect):
s_count:update(function(n) return n + 1 end)
-- Also equivalent: s_count:set(s_count:get() + 1)
return ''
end,
},
}, ' Increment '),
},
'\n',
'\n',
{ 'Press <CR> on each "button" above to increment/decrement the counter.' },
}
end)
```
</details>
### `u.tracker`
The `u.tracker` module provides a simple API for creating reactive variables. These can be composed in Effects and Memos utilizing Execution Contexts that track what signals are used by effects/memos.
```lua
local tracker = require('u.tracker')
local s_number = tracker.Signal:new(0)
-- auto-compute the double of the number each time it changes:
local s_doubled = tracker.create_memo(function() return s_number:get() * 2 end)
tracker.create_effect(function()
local n = s_doubled:get()
-- ...
-- whenever s_doubled changes, this function gets run
end)
```
**Note**: circular dependencies are **not** supported.
### `u.renderer`
The renderer library renders hyperscript into a buffer. Each render performs a
minimal set of changes in order to transform the current buffer text into the
desired state.
**Hyperscript** is just 1) _text_ 2) `<text>` tags, which can be nested in 3) Lua tables for readability:
```lua
local h = require('u.renderer').h
-- Hyperscript can be organized into tables:
{
"Hello, ",
{
"I am ", { "a" }, " nested table.",
},
'\n', -- newlines must be explicitly specified
-- booleans/nil are ignored:
some_conditional_flag and 'This text only shows when the flag is true',
-- e.g., use the above to show newlines in lists:
idx > 1 and '\n',
-- <text> tags are specified like so:
-- h('text', attributes, children)
h('text', {}, "I am a text node."),
-- <text> tags can be highlighted:
h('text', { hl = 'Comment' }, "I am highlighted."),
-- <text> tags can respond to key events:
h('text', {
hl = 'Keyword',
on_key = {
-- Utilizes vim.on_key, under the hood:
["\r"] = function()
print("Hello World")
-- In NeoVim >0.11, you can return '' to swallow the event:
return ''
end,
},
}, "I am a text node."),
}
```
Managing complex tables of hyperscript can be done more ergonomically using the
`TreeBuilder` helper class:
```lua
local TreeBuilder = require('u.renderer').TreeBuilder
-- ...
renderer:render(
TreeBuilder.new()
-- text:
:put('some text')
-- hyperscript tables:
:put({ 'some text', 'more hyperscript' })
-- hyperscript tags:
:put_h('text', { --[[attributes]] }, { --[[children]] })
-- callbacks:
--- @param tb TreeBuilder
:nest(function(tb)
tb:put('some text')
end)
:tree()
)
```
**Rendering**: The renderer library provides a `render` function that takes hyperscript in, and converts it to formatted buffer text:
```lua
local Renderer = require('u.renderer').Renderer
local renderer = Renderer:new(0 --[[buffer number]])
renderer:render {
-- ...hyperscript...
}
-- or, if you already have a buffer:
local Buffer = require('u.buffer')
local buf = Buffer.current()
buf:render {
-- ...hyperscript...
}
```
## Range Usage
### A note on indices ### A note on indices
@ -136,7 +327,8 @@ cw:write('}')
#### Custom Text Objects #### Custom Text Objects
Simply by returning a `Range` or a `Pos`, you can easily and quickly define your own text objects: Simply by returning a `Range` or a `Pos`, you can easily and quickly define
your own text objects:
```lua ```lua
local utils = require 'u.utils' local utils = require 'u.utils'

65
examples/counter.lua Normal file
View File

@ -0,0 +1,65 @@
local tracker = require 'u.tracker'
local Buffer = require 'u.buffer'
local h = require('u.renderer').h
-- Create an buffer for the UI
vim.cmd.vnew()
local ui_buf = Buffer.current()
ui_buf:set_tmp_options()
local s_count = tracker.create_signal(0, 'counter_signal')
-- Effect: Render
-- Setup the effect for rendering the UI whenever dependencies are updated
tracker.create_effect(function()
-- Calling `Signal:get()` in an effect registers the given signal as a
-- dependency of the current effect. Whenever that signal (or any other
-- dependency) changes, the effect will rerun. In this particular case,
-- rendering the UI is an effect that depends on one signal.
local count = s_count:get()
-- Markup is hyperscript, which is just 1) text, and 2) tags (i.e.,
-- constructed with `h(...)` calls). To help organize the markup, text and
-- tags can be nested in tables at any depth. Line breaks must be specified
-- manually, with '\n'.
ui_buf:render {
'Reactive Counter Example\n',
'========================\n\n',
{ 'Counter: ', tostring(count), '\n' },
'\n',
{
h('text', {
hl = 'DiffDelete',
on_key = {
['\r'] = function()
-- Update the contents of the s_count signal, notifying any
-- dependencies (in this case, the render effect):
s_count:update(function(n) return n - 1 end)
-- Also equivalent: s_count:set(s_count:get() - 1)
return ''
end,
},
}, ' Decrement '),
' ',
h('text', {
hl = 'DiffAdd',
on_key = {
['\r'] = function()
-- Update the contents of the s_count signal, notifying any
-- dependencies (in this case, the render effect):
s_count:update(function(n) return n + 1 end)
-- Also equivalent: s_count:set(s_count:get() + 1)
return ''
end,
},
}, ' Increment '),
},
'\n',
'\n',
{ 'Press <CR> on each "button" above to increment/decrement the counter.' },
}
end)

874
examples/picker.lua Normal file
View File

@ -0,0 +1,874 @@
local utils = require 'u.utils'
local Buffer = require 'u.buffer'
local Renderer = require('u.renderer').Renderer
local h = require('u.renderer').h
local TreeBuilder = require('u.renderer').TreeBuilder
local tracker = require 'u.tracker'
local M = {}
local S_EDITOR_DIMENSIONS = tracker.create_signal(utils.get_editor_dimensions(), 's:editor_dimensions')
vim.api.nvim_create_autocmd('VimResized', {
callback = function()
local new_dim = utils.get_editor_dimensions()
S_EDITOR_DIMENSIONS:set(new_dim)
end,
})
--- @param low number
---@param x number
---@param high number
local function clamp(low, x, high)
x = math.max(low, x)
x = math.min(x, high)
return x
end
--- @generic T
--- @param arr `T`[]
--- @return T[]
local function shallow_copy_arr(arr) return vim.iter(arr):totable() end
--------------------------------------------------------------------------------
-- BEGIN create_picker
--
-- This is the star of the show (in this file, anyway).
-- In summary, the outline of this function is:
-- 1. Setup signals/memos for computing the picker size, and window positions
-- 2. Create the two windows:
-- a. The picker input. This is where the filter is typed
-- b. The picker list. This is where the items are displayed
-- 3. Setup event handlers that respond to user input
-- 4. Render the list. After all the prework above, this is probably the
-- shortest portion of this function.
--------------------------------------------------------------------------------
--- @alias SelectController {
--- get_items: fun(): T[];
--- set_items: fun(items: T[]);
--- set_filter_text: fun(filter_text: string);
--- get_selected_indices: fun(): number[];
--- get_selected_items: fun(): T[];
--- set_selected_indices: fun(indicies: number[], ephemeral?: boolean);
--- close: fun();
--- }
--- @alias SelectOpts<T> {
--- items: `T`[];
--- multi?: boolean;
--- format_item?: fun(item: T[]): Tree;
--- on_finish?: fun(items: T[], indicies: number[]);
--- on_selection_changed?: fun(items: T[], indicies: number[]);
--- mappings?: table<string, fun(select: SelectController)>;
--- }
--- @generic T
--- @param opts SelectOpts<T>
function M.create_picker(opts)
local is_in_insert_mode = vim.api.nvim_get_mode().mode:sub(1, 1) == 'i'
local stopinsert = not is_in_insert_mode
if opts.multi == nil then opts.multi = false end
local H = {}
--- Runs a function `fn`, and if it fails, cleans up the UI by calling
--- `H.finish`
---
--- @generic T
--- @param fn fun(): `T`
--- @return T
local function safe_run(fn, ...)
local ok, result_or_error = pcall(fn, ...)
if not ok then
pcall(H.finish, true, result_or_error)
error(result_or_error .. '\n' .. debug.traceback())
end
return result_or_error
end
--- Creates a function that safely calls the given function, cleaning up the
--- UI if it ever fails
---
--- @generic T
--- @param fn `T`
--- @return T
local function safe_wrap(fn)
return function(...) return safe_run(fn, ...) end
end
--
-- Compute the positions of the input bar and the list:
--
-- Reactively compute the space available for the picker based on the size of
-- the editor
local s_editor_dimensions = S_EDITOR_DIMENSIONS:clone()
local s_picker_space_available = tracker.create_memo(safe_wrap(function()
local editor_dim = s_editor_dimensions:get()
local width = math.floor(editor_dim.width * 0.75)
local height = math.floor(editor_dim.height * 0.75)
local row = math.floor((editor_dim.height - height) / 2)
local col = math.floor((editor_dim.width - width) / 2)
return { width = width, height = height, row = row, col = col }
end))
-- Reactively compute the size of the prompt (input) bar
local s_w_input_coords = tracker.create_memo(safe_wrap(function()
local picker_coords = s_picker_space_available:get()
return {
width = picker_coords.width,
height = 1,
row = picker_coords.row,
col = picker_coords.col,
}
end))
-- Reactively compute the size of the list view
local s_w_list_coords = tracker.create_memo(safe_wrap(function()
local picker_coords = s_picker_space_available:get()
return {
width = picker_coords.width,
height = picker_coords.height - 3,
row = picker_coords.row + 3,
col = picker_coords.col,
}
end))
--
-- Create resources (i.e., windows):
--
local w_input_cfg = {
width = s_w_input_coords:get().width,
height = s_w_input_coords:get().height,
row = s_w_input_coords:get().row,
col = s_w_input_coords:get().col,
relative = 'editor',
focusable = true,
border = 'rounded',
}
local w_input_buf = Buffer.create(false, true)
local w_input = vim.api.nvim_open_win(w_input_buf.buf, false, w_input_cfg)
vim.wo[w_input].number = false
vim.wo[w_input].relativenumber = false
-- The following option is a signal to other plugins like 'cmp' to not mess
-- with this buffer:
vim.bo[w_input_buf.buf].buftype = 'prompt'
vim.fn.prompt_setprompt(w_input_buf.buf, '')
vim.api.nvim_set_current_win(w_input)
tracker.create_effect(safe_wrap(function()
-- update window position/size every time the editor is resized:
w_input_cfg = vim.tbl_deep_extend('force', w_input_cfg, s_w_input_coords:get())
vim.api.nvim_win_set_config(w_input, w_input_cfg)
end))
local w_list_cfg = {
width = s_w_list_coords:get().width,
height = s_w_list_coords:get().height,
row = s_w_list_coords:get().row,
col = s_w_list_coords:get().col,
relative = 'editor',
focusable = true,
border = 'rounded',
}
local w_list_buf = Buffer.create(false, true)
local w_list = vim.api.nvim_open_win(w_list_buf.buf, false, w_list_cfg)
vim.wo[w_list].number = false
vim.wo[w_list].relativenumber = false
vim.wo[w_list].scrolloff = 0
tracker.create_effect(safe_wrap(function()
-- update window position/size every time the editor is resized:
w_list_cfg = vim.tbl_deep_extend('force', w_list_cfg, s_w_list_coords:get())
vim.api.nvim_win_set_config(w_list, w_list_cfg)
end))
-- Now that we have created the window with the prompt in it, start insert
-- mode so that the user can type immediately:
vim.cmd.startinsert()
--
-- State:
--
local s_items_raw = tracker.create_signal(opts.items, 's:items')
local s_items = s_items_raw:debounce(100)
local s_selected_indices = tracker.create_signal({}, 's:selected_indices')
local s_top_offset = tracker.create_signal(0, 's:top_offset')
local s_cursor_index = tracker.create_signal(1, 's:cursor_index')
local s_filter_text_undebounced = tracker.create_signal('', 's:filter_text')
w_input_buf:autocmd('TextChangedI', {
callback = safe_wrap(function() s_filter_text_undebounced:set(vim.api.nvim_get_current_line()) end),
})
local s_filter_text = s_filter_text_undebounced:debounce(50)
--
-- Derived State:
--
local s_formatted_items = tracker.create_memo(function()
local function _format_item(item) return opts.format_item and opts.format_item(item) or tostring(item) end
local items = s_items:get()
return vim.iter(items):map(function(item) return { item = item, formatted = _format_item(item) } end):totable()
end)
-- When the filter text changes, update the filtered items:
local s_filtered_items = tracker.create_memo(
safe_wrap(function()
local formatted_items = s_formatted_items:get()
local filter_text = vim.trim(s_filter_text:get())
local filter_pattern = (#formatted_items > 250 and #filter_text <= 3) and (filter_text:gsub('%.', '%%.'))
or vim.iter(vim.split(filter_text, '')):map(function(c) return c .. '.*' end):join ''
local new_filtered_items = vim
.iter(formatted_items)
:enumerate()
:map(function(i, inf) return { orig_idx = i, item = inf.item, formatted = inf.formatted } end)
:filter(function(inf)
if filter_text == '' then return true end
local formatted_as_string = Renderer.markup_to_string { tree = inf.formatted }
local match = string.match(Renderer.markup_to_string { tree = formatted_as_string }, filter_pattern)
return match ~= nil
end)
:totable()
-- Don't do the levenshtein-sort if there are over 250 items:
if #new_filtered_items <= 250 then
table.sort(new_filtered_items, function(a_inf, b_inf)
local a = Renderer.markup_to_string { markup = a_inf.formatted }
local b = Renderer.markup_to_string { markup = b_inf.formatted }
if a == b then return false end
local lev_a = utils.levenshtein(vim.split(filter_text, ''), vim.split(a, ''))
local lev_b = utils.levenshtein(vim.split(filter_text, ''), vim.split(b, ''))
return #lev_a < #lev_b
end)
end
s_top_offset:set(0)
s_cursor_index:set(1)
return new_filtered_items
end),
'e:(filter_text=>filtered_items)'
)
-- Visible items, are _just_ the items that fit into the current viewport.
-- This is an optimization so that we are not rendering thousands of lines of
-- items on each state-change.
local s_visible_items = tracker.create_memo(
safe_wrap(function()
return vim
.iter(s_filtered_items:get())
:enumerate()
:skip(s_top_offset:get())
:take(s_w_list_coords:get().height)
:map(
function(i, inf)
return {
filtered_idx = i,
orig_idx = inf.orig_idx,
item = inf.item,
formatted = inf.formatted,
}
end
)
:totable()
end),
'm:visible_items'
)
-- Track selection information:
local s_selection_info = tracker.create_memo(
safe_wrap(function()
local items = s_items:get()
local selected_indices = s_selected_indices:get()
--- @type { orig_idx: number; item: T }[]
local filtered_items = s_filtered_items:get()
local cursor_index = s_cursor_index:get()
local indices = shallow_copy_arr(selected_indices) -- shallow copy
if #indices == 0 and #filtered_items > 0 then indices = { filtered_items[cursor_index].orig_idx } end
return {
items = vim.iter(indices):map(function(i) return items[i] end):totable(),
indices = indices,
}
end),
'm:selection_info'
)
--- When it is time to close the picker, this is the main cleanup routine
--- that runs in all cases:
---
--- @param esc? boolean Whether the user pressed <Esc> or not
--- @param err? any Any error that occurred
function H.finish(esc, err)
-- s_editor_dimensions is the only signal that is cloned from a global,
-- one. It is therefore the only one that needs to be manually disposed.
-- The other ones should get cleaned up by the GC
s_editor_dimensions:dispose()
-- If we happen to have any async state-changes coming down the pipeline,
-- we can say right now that we are done rendering new UI (to avoid
-- "invalid window ID" errors):
H.unsubscribe_render_effect()
-- buftype=prompt buffers are not "temporary", so delete the buffer manually:
vim.api.nvim_buf_delete(w_input_buf.buf, { force = true })
-- The following is not needed, since the buffer is deleted above:
-- vim.api.nvim_win_close(w_input, false)
vim.api.nvim_win_close(w_list, false)
if stopinsert then vim.cmd.stopinsert() end
local inf = s_selection_info:get()
if not err and opts.on_finish then
-- If on_finish opens another picker, the closing of this one can happen
-- in _too_ quick succession, so put a small delay in there.
--
-- TODO: figure out _why_ this is actually happening, and then a better
-- way to handle this.
vim.defer_fn(function()
if esc then
opts.on_finish({}, {})
else
opts.on_finish(inf.items, inf.indices)
end
end, 100)
end
end
-- On selection info changed:
tracker.create_effect(
safe_wrap(function()
local inf = s_selection_info:get()
if opts.on_selection_changed then opts.on_selection_changed(inf.items, inf.indices) end
end),
'e:selection_changed'
)
--
-- Public API (i.e., `controller`):
-- We will fill in the methods further down, but we need this variable in scope so that it can be
-- closed over by some of the event handlers:
--
local controller = {}
--
-- Events
--
vim.keymap.set('i', '<Esc>', function() H.finish(true) end, { buffer = w_input_buf.buf })
vim.keymap.set('i', '<CR>', function() H.finish() end, { buffer = w_input_buf.buf })
local function action_next_line()
local max_line = #s_filtered_items:get()
local next_cursor_index = clamp(1, s_cursor_index:get() + 1, max_line)
if next_cursor_index - s_top_offset:get() > s_w_list_coords:get().height then
s_top_offset:set(s_top_offset:get() + 1)
end
s_cursor_index:set(next_cursor_index)
end
vim.keymap.set('i', '<C-n>', safe_wrap(action_next_line), { buffer = w_input_buf.buf, desc = 'Picker: next' })
vim.keymap.set(
'i',
'<C-p>',
safe_wrap(function()
local max_line = #s_filtered_items:get()
local next_cursor_index = clamp(1, s_cursor_index:get() - 1, max_line)
if next_cursor_index - s_top_offset:get() < 1 then s_top_offset:set(s_top_offset:get() - 1) end
s_cursor_index:set(next_cursor_index)
end),
{ buffer = w_input_buf.buf, desc = 'Picker: previous' }
)
vim.keymap.set(
'i',
'<Tab>',
safe_wrap(function()
if not opts.multi then return end
local index = s_filtered_items:get()[s_cursor_index:get()].orig_idx
if vim.tbl_contains(s_selected_indices:get(), index) then
s_selected_indices:set(vim.iter(s_selected_indices:get()):filter(function(i) return i ~= index end):totable())
else
local new_selected_indices = shallow_copy_arr(s_selected_indices:get())
table.insert(new_selected_indices, index)
s_selected_indices:set(new_selected_indices)
end
action_next_line()
end),
{ buffer = w_input_buf.buf }
)
for key, fn in pairs(opts.mappings or {}) do
vim.keymap.set('i', key, safe_wrap(function() return fn(controller) end), { buffer = w_input_buf.buf })
end
-- Render:
H.unsubscribe_render_effect = tracker.create_effect(
safe_wrap(function()
local selected_indices = s_selected_indices:get()
local top_offset = s_top_offset:get()
local cursor_index = s_cursor_index:get()
--- @type { filtered_idx: number; orig_idx: number; item: T; formatted: string }[]
local visible_items = s_visible_items:get()
-- The above has to run in the execution context for the signaling to work, but
-- the following cannot run in a NeoVim loop-callback:
vim.schedule(function()
w_list_buf:render(TreeBuilder.new()
:nest(function(tb)
for loop_idx, inf in ipairs(visible_items) do
local is_cur_line = inf.filtered_idx == cursor_index
local is_selected = vim.tbl_contains(selected_indices, inf.orig_idx)
tb:put(loop_idx > 1 and '\n')
tb:put(is_cur_line and h('text', { hl = 'Structure' }, '') or ' ')
tb:put(is_selected and h('text', { hl = 'Comment' }, '* ') or ' ')
tb:put(inf.formatted)
end
end)
:tree())
-- set the window viewport to have the first line in view:
pcall(vim.api.nvim_win_call, w_list, function() vim.fn.winrestview { topline = 1 } end)
pcall(vim.api.nvim_win_set_cursor, w_list, { cursor_index - top_offset, 0 })
end)
end),
'e:render'
)
--
-- Populate the public API:
--
function controller.get_items()
return safe_run(function() return s_items_raw:get() end)
end
---@param items T[]
function controller.set_items(items)
return safe_run(function() s_items_raw:set(items) end)
end
function controller.set_filter_text(filter_text)
return safe_run(function()
vim.api.nvim_win_call(w_input, function() vim.api.nvim_set_current_line(filter_text) end)
end)
end
function controller.get_selected_indices()
return safe_run(function() return s_selection_info:get().indices end)
end
function controller.get_selected_items()
return safe_run(function() return s_selection_info:get().items end)
end
--- @param indicies number[]
---@param ephemeral? boolean
function controller.set_selected_indices(indicies, ephemeral)
return safe_run(function()
if ephemeral == nil then ephemeral = false end
if ephemeral and #indicies == 1 then
local matching_filtered_item_idx, _ = vim
.iter(s_filtered_items:get())
:enumerate()
:find(function(_idx, inf) return inf.orig_idx == indicies[1] end)
if matching_filtered_item_idx ~= nil then s_cursor_index:set(indicies[1]) end
else
if not opts.multi then
local err = 'Cannot set multiple selected indices on a single-select picker'
H.finish(true, err)
error(err)
end
s_selected_indices:set(indicies)
end
end)
end
function controller.close()
return safe_run(function() H.finish(true) end)
end
return controller --[[@as SelectController]]
end
--------------------------------------------------------------------------------
-- END create_picker
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- vim.ui.select override
--------------------------------------------------------------------------------
local ORIGINAL_UI_SELECT
function M.register_ui_select()
ORIGINAL_UI_SELECT = vim.ui.select
--- @generic T
--- @param items `T`[]
--- @param opts { prompt?: string, kind?: any, format_item?: fun(item: T):string }
--- @param cb fun(item: T|nil):any
function vim.ui.select(items, opts, cb)
M.create_picker {
items = items,
format_item = function(item)
local s = opts.format_item and opts.format_item(item) or tostring(item)
s = s:gsub('<', '&lt;')
return s
end,
on_finish = function(sel_items)
if #sel_items == 0 then cb(nil) end
cb(sel_items[#sel_items])
end,
}
end
end
function M.unregister_ui_select() vim.ui.select = ORIGINAL_UI_SELECT end
--------------------------------------------------------------------------------
-- Built-in pickers
-- 1. files
-- 2. buffers
-- 3. code-symbols
--------------------------------------------------------------------------------
--- @param opts? { limit?: number }
function M.files(opts)
opts = opts or {}
opts.limit = opts.limit or 10000
local cmd = {}
if vim.fn.executable 'rg' then
cmd = {
'rg',
'--color=never',
'--files',
'--hidden',
'--follow',
'-g',
'!.git',
'-g',
'!node_modules',
'-g',
'!target',
}
elseif vim.fn.executable 'fd' then
cmd = {
'fd',
'--color=never',
'--type',
'f',
'--hidden',
'--follow',
'--exclude',
'.git',
'--exclude',
'node_modules',
'--exclude',
'target',
}
elseif vim.fn.executable 'find' then
cmd = {
'find',
'-type',
'f',
'-not',
'-path',
"'*/.git/*'",
'-not',
'-path',
"'*/node_modules/*'",
'-not',
'-path',
"'*/target/*'",
'-printf',
"'%P\n'",
}
end
if #cmd == 0 then
vim.notify('rg/fd/find executable not found: cannot list files', vim.log.levels.ERROR)
return
end
-- Keep track of the job that will list files independent from the picker. We
-- will stream lines from this process to the picker as they come in:
local job_inf = { id = 0, proc_lines = {}, notified_over_limit = false }
-- Initially, create the picker with no items:
local picker = M.create_picker {
multi = true,
items = {},
--- @params items string[]
on_finish = function(items)
pcall(vim.fn.jobstop, job_inf.id)
if #items == 0 then return end
if #items == 1 then
vim.cmd.edit(items[1])
else
-- populate quickfix:
vim.fn.setqflist(vim
.iter(items)
:map(
function(item)
return {
filename = item,
lnum = 1,
col = 1,
}
end
)
:totable())
vim.cmd.copen()
end
end,
mappings = {
['<C-t>'] = function(sel)
sel.close()
--- @type string[]
local items = sel.get_selected_items()
-- open in new tab:
for _, item in ipairs(items) do
vim.cmd.tabnew(item)
end
end,
['<C-v>'] = function(sel)
sel.close()
--- @type string[]
local items = sel.get_selected_items()
-- open in vertical split:
for _, item in ipairs(items) do
vim.cmd.vsplit(item)
end
end,
['<C-s>'] = function(sel)
sel.close()
--- @type string[]
local items = sel.get_selected_items()
-- open in horizontal split:
for _, item in ipairs(items) do
vim.cmd.split(item)
end
end,
},
}
-- Kick off the process that lists the files. As lines come in, send them to
-- the picker:
job_inf.id = vim.fn.jobstart(cmd, {
--- @param data string[]
on_stdout = vim.schedule_wrap(function(_chanid, data, _name)
local lines = job_inf.proc_lines
local function set_lines_as_items_state()
picker.set_items(vim
.iter(lines)
:enumerate()
:filter(function(idx, item)
-- Filter out an incomplete last line:
local is_last_line = idx == #lines
if is_last_line and item == '' then return false end
return true
end)
:map(function(_, item) return item end)
:totable())
end
-- It's just not a good idea to process large lists with Lua. The default
-- limit is 10,000 items, and even crunching through this is iffy on a
-- fast laptop. Show a warning and truncate the list in this case.
if #lines >= opts.limit then
if not job_inf.notified_over_limit then
vim.notify('Picker list is too large (truncating list to ' .. opts.limit .. ' items)', vim.log.levels.WARN)
job_inf.notified_over_limit = true
end
return
end
-- :help channel-lines
local eof = #data == 1 and data[1] == ''
if eof then set_lines_as_items_state() end
-- Complete the previous line:
if #lines > 0 then lines[#lines] = lines[#lines] .. table.remove(data, 1) end
for _, l in ipairs(data) do
table.insert(lines, l)
end
set_lines_as_items_state()
end),
})
end
function M.buffers()
local cwd = vim.fn.getcwd(0, 0)
-- ensure that `cwd` ends with a trailing slash:
if cwd[#cwd] ~= '/' then cwd = cwd .. '/' end
--- @type { name: string; changed: number; bufnr: number }[]
local bufs = vim.fn.getbufinfo { buflisted = 1 }
M.create_picker {
multi = true,
items = bufs,
--- @param item { name: string; changed: number; bufnr: number }
format_item = function(item)
local item_name = item.name
if item_name == '' then item_name = '[No Name]' end
-- trim leading `cwd` from the buffer name:
if item_name:sub(1, #cwd) == cwd then item_name = item_name:sub(#cwd + 1) end
return TreeBuilder.new()
:put(item.changed == 1 and '[+] ' or ' ')
:put(item_name)
:tree()
end,
--- @params items { bufnr: number }[]
on_finish = function(items)
if #items == 0 then return end
if #items == 1 then
vim.cmd.buffer(items[1].bufnr)
else
-- populate quickfix:
vim.fn.setqflist(vim
.iter(items)
:map(
function(item)
return {
bufnr = item.bufnr,
filename = item.name,
lnum = 1,
col = 1,
}
end
)
:totable())
vim.cmd.copen()
end
end,
mappings = {
['<C-t>'] = function(sel)
sel.close()
--- @type { bufnr: number }[]
local items = sel.get_selected_items()
-- open in new tab:
for _, item in ipairs(items) do
vim.cmd.tabnew()
vim.cmd.buffer(item.bufnr)
end
end,
['<C-v>'] = function(sel)
sel.close()
--- @type { bufnr: number }[]
local items = sel.get_selected_items()
-- open in new vertial split:
for _, item in ipairs(items) do
vim.cmd.vsplit()
vim.cmd.buffer(item.bufnr)
end
end,
['<C-s>'] = function(sel)
sel.close()
--- @type { bufnr: number }[]
local items = sel.get_selected_items()
-- open in horizontal split:
for _, item in ipairs(items) do
vim.cmd.split()
vim.cmd.buffer(item.bufnr)
end
end,
['<C-x>'] = function(sel)
local selected_items = sel.get_selected_items()
for _, item in ipairs(selected_items) do
-- delete the buffer
vim.cmd.bdelete(item.bufnr)
end
sel.set_selected_indices {}
sel.set_items(
vim
.iter(sel.get_items())
:filter(function(item) return not vim.tbl_contains(selected_items, item) end)
:totable()
)
end,
},
}
end
local IS_CODE_SYMBOL_RUNNING = false
function M.lsp_code_symbols()
if IS_CODE_SYMBOL_RUNNING then return end
IS_CODE_SYMBOL_RUNNING = true
-- Avoid callback-hell with a wizard-based "steps"-system. Define each "step"
-- sequentially in the code, and wire up the callbacks to call the next step:
-- a simple, yet powerful, and easy to understand pattern/approach.
local STEPS = {}
--- @param info vim.lsp.LocationOpts.OnList
function STEPS._1_on_symbols(info)
M.create_picker {
items = info.items,
--- @param item { text: string }
format_item = function(item)
local s = item.text:gsub('<', '&lt;')
return s
end,
on_finish = STEPS._2_on_symbol_picked,
}
end
--- @param items { filename: string, lnum: integer, col: integer }[]
function STEPS._2_on_symbol_picked(items)
if #items == 0 then return STEPS._finally() end
local item = items[1]
-- Jump to the file/buffer:
local buf = vim.iter(vim.fn.getbufinfo { buflisted = 1 }):find(function(b) return b.name == item.filename end)
if buf ~= nil then
vim.api.nvim_win_set_buf(0, buf.bufnr)
else
vim.cmd.edit(item.filename)
end
-- Jump to the specific location:
vim.api.nvim_win_set_cursor(0, { item.lnum, item.col - 1 })
vim.cmd.normal 'zz'
STEPS._finally()
end
function STEPS._finally() IS_CODE_SYMBOL_RUNNING = false end
-- Kick off the async operation:
vim.lsp.buf.document_symbol { on_list = STEPS._1_on_symbols }
end
function M.setup()
utils.ucmd('Files', M.files)
utils.ucmd('Buffers', M.buffers)
utils.ucmd('Lspcodesymbols', M.lsp_code_symbols)
M.register_ui_select()
end
return M

View File

@ -1,16 +1,21 @@
local Range = require 'u.range' local Range = require 'u.range'
local Renderer = require 'u.renderer'.Renderer
---@class Buffer ---@class Buffer
---@field buf number ---@field buf number
---@field private renderer Renderer
local Buffer = {} local Buffer = {}
---@param buf? number ---@param buf? number
---@return Buffer ---@return Buffer
function Buffer.from_nr(buf) function Buffer.from_nr(buf)
if buf == nil or buf == 0 then buf = vim.api.nvim_get_current_buf() end if buf == nil or buf == 0 then buf = vim.api.nvim_get_current_buf() end
local b = { buf = buf }
setmetatable(b, { __index = Buffer }) local renderer = Renderer.new(buf)
return b return setmetatable({
buf = buf,
renderer = renderer,
}, { __index = Buffer })
end end
---@return Buffer ---@return Buffer
@ -69,4 +74,13 @@ function Buffer:text_object(txt_obj, opts)
return Range.from_text_object(txt_obj, opts) return Range.from_text_object(txt_obj, opts)
end end
--- @param event string|string[]
--- @param opts vim.api.keyset.create_autocmd
function Buffer:autocmd(event, opts)
vim.api.nvim_create_autocmd(event, vim.tbl_extend('force', opts, { buffer = self.buf }))
end
--- @param tree Tree
function Buffer:render(tree) return self.renderer:render(tree) end
return Buffer return Buffer

View File

@ -1,9 +1,9 @@
local Pos = require 'u.pos' local Pos = require 'u.pos'
local State = require 'u.state' local State = require 'u.state'
local orig_on_yank = vim.highlight.on_yank local orig_on_yank = (vim.hl or vim.highlight).on_yank
local on_yank_enabled = true; local on_yank_enabled = true;
(vim.highlight --[[@as any]]).on_yank = function(opts) ((vim.hl or vim.highlight) --[[@as any]]).on_yank = function(opts)
if not on_yank_enabled then return end if not on_yank_enabled then return end
return orig_on_yank(opts) return orig_on_yank(opts)
end end
@ -493,7 +493,7 @@ function Range:highlight(group, opts)
State.run(self.start.buf, function(s) State.run(self.start.buf, function(s)
if not in_macro then s:track_winview() end if not in_macro then s:track_winview() end
vim.highlight.range( (vim.hl or vim.highlight).range(
self.start.buf, self.start.buf,
ns, ns,
group, group,

432
lua/u/renderer.lua Normal file
View File

@ -0,0 +1,432 @@
local utils = require 'u.utils'
local M = {}
--- @alias Tag { kind: 'tag'; name: string, attributes: table<string, unknown>, children: Tree }
--- @alias Node nil | boolean | string | Tag
--- @alias Tree Node | Node[]
local TagMetaTable = {}
--- @param name string
--- @param attributes? table<string, any>
--- @param children? Node | Node[]
--- @return Tag
function M.h(name, attributes, children)
return setmetatable({
kind = 'tag',
name = name,
attributes = attributes or {},
children = children,
}, TagMetaTable)
end
--------------------------------------------------------------------------------
-- Renderer class
--------------------------------------------------------------------------------
--- @alias RendererExtmark { id?: number; start: [number, number]; stop: [number, number]; opts: any; tag: any }
--- @class Renderer
--- @field bufnr number
--- @field ns number
--- @field changedtick number
--- @field old { lines: string[]; extmarks: RendererExtmark[] }
--- @field curr { lines: string[]; extmarks: RendererExtmark[] }
local Renderer = {}
Renderer.__index = Renderer
M.Renderer = Renderer
--- @param x any
--- @return boolean
function Renderer.is_tag(x) return type(x) == 'table' and getmetatable(x) == TagMetaTable end
--- @param x any
--- @return boolean
function Renderer.is_tag_arr(x)
if type(x) ~= 'table' then return false end
return #x == 0 or not Renderer.is_tag(x)
end
--- @param bufnr number|nil
function Renderer.new(bufnr)
if bufnr == nil then bufnr = vim.api.nvim_get_current_buf() end
if vim.b[bufnr]._renderer_ns == nil then
vim.b[bufnr]._renderer_ns = vim.api.nvim_create_namespace('my.renderer:' .. tostring(bufnr))
end
local self = setmetatable({
bufnr = bufnr,
ns = vim.b[bufnr]._renderer_ns,
changedtick = 0,
old = { lines = {}, extmarks = {} },
curr = { lines = {}, extmarks = {} },
}, Renderer)
return self
end
--- @param opts {
--- tree: Tree;
--- on_tag?: fun(tag: Tag, start0: [number, number], stop0: [number, number]): any;
--- }
function Renderer.markup_to_lines(opts)
--- @type string[]
local lines = {}
local curr_line1 = 1
local curr_col1 = 1 -- exclusive: sits one position **beyond** the last inserted text
--- @param s string
local function put(s)
lines[curr_line1] = (lines[curr_line1] or '') .. s
curr_col1 = #lines[curr_line1] + 1
end
local function put_line()
table.insert(lines, '')
curr_line1 = curr_line1 + 1
curr_col1 = 1
end
--- @param node Node
local function visit(node)
if node == nil or type(node) == 'boolean' then return end
if type(node) == 'string' then
local node_lines = vim.split(node, '\n')
for lnum, s in ipairs(node_lines) do
if lnum > 1 then put_line() end
put(s)
end
elseif Renderer.is_tag(node) then
local start0 = { curr_line1 - 1, curr_col1 - 1 }
-- visit the children:
if Renderer.is_tag_arr(node.children) then
for _, child in ipairs(node.children) do
-- newlines are not controlled by array entries, do NOT output a line here:
visit(child)
end
else
visit(node.children)
end
local stop0 = { curr_line1 - 1, curr_col1 - 1 }
if opts.on_tag then opts.on_tag(node, start0, stop0) end
elseif Renderer.is_tag_arr(node) then
for _, child in ipairs(node) do
-- newlines are not controlled by array entries, do NOT output a line here:
visit(child)
end
end
end
visit(opts.tree)
return lines
end
--- @param opts {
--- tree: string;
--- format_tag?: fun(tag: Tag): string;
--- }
function Renderer.markup_to_string(opts) return table.concat(Renderer.markup_to_lines(opts), '\n') end
--- @param tree Tree
function Renderer:render(tree)
local changedtick = vim.b[self.bufnr].changedtick
if changedtick ~= self.changedtick then
self.curr = { lines = vim.api.nvim_buf_get_lines(self.bufnr, 0, -1, false) }
self.changedtick = changedtick
end
--- @type RendererExtmark[]
local extmarks = {}
--- @type string[]
local lines = Renderer.markup_to_lines {
tree = tree,
on_tag = function(tag, start0, stop0)
if tag.name == 'text' then
local hl = tag.attributes.hl
if type(hl) == 'string' then
tag.attributes.extmark = tag.attributes.extmark or {}
tag.attributes.extmark.hl_group = tag.attributes.extmark.hl_group or hl
end
local extmark = tag.attributes.extmark
-- Force creating an extmark if there are key handlers. To accurately
-- sense the bounds of the text, we need an extmark:
if tag.attributes.on_key or tag.attributes.on_typed then extmark = extmark or {} end
if extmark then
table.insert(extmarks, {
start = start0,
stop = stop0,
opts = extmark,
tag = tag,
})
end
end
end,
}
self.old = self.curr
self.curr = { lines = lines, extmarks = extmarks }
self:_reconcile()
end
--- @private
--- @param info string
--- @param start integer
--- @param end_ integer
--- @param strict_indexing boolean
--- @param replacement string[]
function Renderer:_set_lines(info, start, end_, strict_indexing, replacement)
self:_log { 'set_lines', self.bufnr, start, end_, strict_indexing, replacement }
vim.api.nvim_buf_set_lines(self.bufnr, start, end_, strict_indexing, replacement)
self:_log { 'after(' .. info .. ')', vim.api.nvim_buf_get_lines(self.bufnr, 0, -1, false) }
end
--- @private
--- @param info string
--- @param start_row integer
--- @param start_col integer
--- @param end_row integer
--- @param end_col integer
--- @param replacement string[]
function Renderer:_set_text(info, start_row, start_col, end_row, end_col, replacement)
self:_log { 'set_text', self.bufnr, start_row, start_col, end_row, end_col, replacement }
vim.api.nvim_buf_set_text(self.bufnr, start_row, start_col, end_row, end_col, replacement)
self:_log { 'after(' .. info .. ')', vim.api.nvim_buf_get_lines(self.bufnr, 0, -1, false) }
end
--- @private
function Renderer:_log(...)
--
-- vim.print(...)
end
--- @private
function Renderer:_reconcile()
local line_changes = utils.levenshtein(self.old.lines, self.curr.lines)
self.old = self.curr
--
-- Step 1: morph the text to the desired state:
--
self:_log { line_changes = line_changes }
for _, line_change in ipairs(line_changes) do
local lnum0 = line_change.index - 1
if line_change.kind == 'add' then
self:_set_lines('add-line', lnum0, lnum0, true, { line_change.item })
elseif line_change.kind == 'change' then
-- Compute inter-line diff, and apply:
self:_log '--------------------------------------------------------------------------------'
local col_changes = utils.levenshtein(vim.split(line_change.from, ''), vim.split(line_change.to, ''))
for _, col_change in ipairs(col_changes) do
local cnum0 = col_change.index - 1
self:_log { line_change = col_change, cnum = cnum0, lnum = lnum0 }
if col_change.kind == 'add' then
self:_set_text('add-char', lnum0, cnum0, lnum0, cnum0, { col_change.item })
elseif col_change.kind == 'change' then
self:_set_text('change-char', lnum0, cnum0, lnum0, cnum0 + 1, { col_change.to })
elseif col_change.kind == 'delete' then
self:_set_text('del-char', lnum0, cnum0, lnum0, cnum0 + 1, {})
else
-- No change
end
end
elseif line_change.kind == 'delete' then
self:_set_lines('del-line', lnum0, lnum0 + 1, true, {})
else
-- No change
end
end
self.changedtick = vim.b[self.bufnr].changedtick
--
-- Step 2: reconcile extmarks:
--
-- Clear current extmarks:
vim.api.nvim_buf_clear_namespace(self.bufnr, self.ns, 0, -1)
-- Set current extmarks:
for _, extmark in ipairs(self.curr.extmarks) do
extmark.id = vim.api.nvim_buf_set_extmark(
self.bufnr,
self.ns,
extmark.start[1],
extmark.start[2],
vim.tbl_extend('force', {
id = extmark.id,
end_row = extmark.stop[1],
end_col = extmark.stop[2],
}, extmark.opts)
)
end
--
-- Step 3: setup an updated on_key handler:
--
vim.on_key(nil, self.ns)
vim.on_key(function(key, typed)
-- Discard if not in the current buffer:
if
-- do not capture keys in the wrong buffer:
vim.api.nvim_get_current_buf() ~= self.bufnr
-- do not capture keys in COMMAND mode:
or vim.startswith(vim.api.nvim_get_mode().mode, 'c')
then
return
end
-- find the tag with the smallest intersection that contains the cursor:
local pos0 = vim.api.nvim_win_get_cursor(0)
pos0[1] = pos0[1] - 1 -- make it actually 0-based
local pos_infos = self:get_pos_infos(pos0)
-- Check the attributes for each matching_tag and fire events if they are
-- listening:
for _, pos_info in ipairs(pos_infos) do
local tag = pos_info.tag
-- is the tag listening?
if tag.attributes.on_key and type(tag.attributes.on_key[key]) == 'function' then
-- key:
local result = tag.attributes.on_key[key]()
if result == '' then return '' end
elseif tag.attributes.on_typed and type(tag.attributes.on_typed[typed]) == 'function' then
-- typed:
local result = tag.attributes.on_typed[typed]()
if result == '' then return '' end
end
end
end, self.ns)
end
--- Returns pairs of extmarks and tags associate with said extmarks. The
--- returned tags/extmarks are sorted smallest (innermost) to largest
--- (outermost).
---
--- @private (private for now)
--- @param pos0 [number; number]
--- @return { extmark: RendererExtmark; tag: Tag; }[]
function Renderer:get_pos_infos(pos0)
local cursor_line0, cursor_col0 = pos0[1], pos0[2]
-- The cursor (block) occupies **two** extmark spaces: one for it's left
-- edge, and one for it's right. We need to do our own intersection test,
-- because the NeoVim API is over-inclusive in what it returns:
--- @type RendererExtmark[]
local intersecting_extmarks = vim
.iter(vim.api.nvim_buf_get_extmarks(self.bufnr, self.ns, pos0, pos0, { details = true, overlap = true }))
--- @return RendererExtmark
:map(function(ext)
--- @type number, number, number, { end_row?: number; end_col?: number }|nil
local id, line0, col0, details = unpack(ext)
local start = { line0, col0 }
local stop = { line0, col0 }
if details and details.end_row ~= nil and details.end_col ~= nil then
stop = { details.end_row, details.end_col }
end
return { id = id, start = start, stop = stop, opts = details }
end)
--- @param ext RendererExtmark
:filter(function(ext)
if ext.stop[1] ~= nil and ext.stop[2] ~= nil then
return cursor_line0 >= ext.start[1]
and cursor_col0 >= ext.start[2]
and cursor_line0 <= ext.stop[1]
and cursor_col0 < ext.stop[2]
else
return true
end
end)
:totable()
-- Sort the tags into smallest (inner) to largest (outer):
table.sort(
intersecting_extmarks,
--- @param x1 RendererExtmark
--- @param x2 RendererExtmark
function(x1, x2)
if
x1.start[1] == x2.start[1]
and x1.start[2] == x2.start[2]
and x1.stop[1] == x2.stop[1]
and x1.stop[2] == x2.stop[2]
then
return x1.id < x2.id
end
return x1.start[1] >= x2.start[1]
and x1.start[2] >= x2.start[2]
and x1.stop[1] <= x2.stop[1]
and x1.stop[2] <= x2.stop[2]
end
)
-- When we set the extmarks in the step above, we captured the IDs of the
-- created extmarks in self.curr.extmarks, which also has which tag each
-- extmark is associated with. Cross-reference with that list to get a list
-- of tags that we need to fire events for:
--- @type { extmark: RendererExtmark; tag: Tag }[]
local matching_tags = vim
.iter(intersecting_extmarks)
--- @param ext RendererExtmark
:map(function(ext)
for _, extmark_cache in ipairs(self.curr.extmarks) do
if extmark_cache.id == ext.id then return { extmark = ext, tag = extmark_cache.tag } end
end
end)
:totable()
return matching_tags
end
--------------------------------------------------------------------------------
-- TreeBuilder class
--------------------------------------------------------------------------------
--- @class TreeBuilder
--- @field private nodes Node[]
local TreeBuilder = {}
TreeBuilder.__index = TreeBuilder
M.TreeBuilder = TreeBuilder
function TreeBuilder.new()
local self = setmetatable({ nodes = {} }, TreeBuilder)
return self
end
--- @param nodes Tree
--- @return TreeBuilder
function TreeBuilder:put(nodes)
table.insert(self.nodes, nodes)
return self
end
--- @param name string
--- @param attributes? table<string, any>
--- @param children? Node | Node[]
--- @return TreeBuilder
function TreeBuilder:put_h(name, attributes, children)
local tag = M.h(name, attributes, children)
table.insert(self.nodes, tag)
return self
end
--- @param fn fun(TreeBuilder): any
--- @return TreeBuilder
function TreeBuilder:nest(fn)
local nested_writer = TreeBuilder.new()
fn(nested_writer)
table.insert(self.nodes, nested_writer.nodes)
return self
end
--- @return Tree
function TreeBuilder:tree() return self.nodes end
return M

294
lua/u/tracker.lua Normal file
View File

@ -0,0 +1,294 @@
local M = {}
M.debug = false
--------------------------------------------------------------------------------
-- class Signal
--------------------------------------------------------------------------------
--- @class Signal
--- @field name? string
--- @field private changing boolean
--- @field private value any
--- @field private subscribers table<function, boolean>
--- @field private on_dispose_callbacks function[]
local Signal = {}
M.Signal = Signal
Signal.__index = Signal
--- @param value any
--- @param name? string
--- @return Signal
function Signal:new(value, name)
local obj = setmetatable({
name = name,
changing = false,
value = value,
subscribers = {},
on_dispose_callbacks = {},
}, self)
return obj
end
--- @param value any
function Signal:set(value)
self.value = value
-- We don't handle cyclic updates:
if self.changing then
if M.debug then
vim.notify('circular dependency detected' .. (self.name and (' in ' .. self.name) or ''), vim.log.levels.WARN)
end
return
end
local prev_changing = self.changing
self.changing = true
local ok = true
local err = nil
for _, cb in ipairs(self.subscribers) do
local ok2, err2 = pcall(cb, value)
if not ok2 then
ok = false
err = err or err2
end
end
self.changing = prev_changing
if not ok then
vim.notify(
'error notifying' .. (self.name and (' in ' .. self.name) or '') .. ': ' .. tostring(err),
vim.log.levels.WARN
)
error(err)
end
end
--- @return any
function Signal:get()
local ctx = M.ExecutionContext.current()
if ctx then ctx:track(self) end
return self.value
end
--- @param fn function
function Signal:update(fn) self:set(fn(self.value)) end
--- @generic U
--- @param fn fun(value: T): U
--- @return Signal --<U>
function Signal:map(fn)
local mapped_signal = M.create_memo(function()
local value = self:get()
return fn(value)
end, self.name and self.name .. ':mapped' or nil)
return mapped_signal
end
--- @return Signal
function Signal:clone()
return self:map(function(x) return x end)
end
--- @param fn fun(value: T): boolean
--- @return Signal -- <T>
function Signal:filter(fn)
local filtered_signal = M.create_signal(nil, self.name and self.name .. ':filtered' or nil)
local unsubscribe_from_self = self:subscribe(function(value)
if fn(value) then filtered_signal:set(value) end
end)
filtered_signal:on_dispose(unsubscribe_from_self)
return filtered_signal
end
--- @param ms number
--- @return Signal -- <T>
function Signal:debounce(ms)
local function set_timeout(timeout, callback)
local timer = (vim.uv or vim.loop).new_timer()
timer:start(timeout, 0, function()
timer:stop()
timer:close()
callback()
end)
return timer
end
local filtered = M.create_signal(self.value, self.name and self.name .. ':debounced' or nil)
--- @type {
-- queued: { value: T, ts: number }[]
-- timer?: uv_timer_t
-- }
local state = { queued = {}, timer = nil }
local function clear_timeout()
if state.timer == nil then return end
pcall(function()
state.timer:stop()
state.timer:close()
end)
state.timer = nil
end
local unsubscribe_from_self = self:subscribe(function(value)
-- Stop any previously running timer:
if state.timer then clear_timeout() end
local now_ms = (vim.uv or vim.loop).hrtime() / 1e6
-- If there is anything older than `ms` in our queue, emit it:
local older_than_ms = vim.iter(state.queued):filter(function(item) return now_ms - item.ts > ms end):totable()
local last_older_than_ms = older_than_ms[#older_than_ms]
if last_older_than_ms then
filtered:set(last_older_than_ms.value)
state.queued = {}
end
-- overwrite anything young enough
table.insert(state.queued, { value = value, ts = now_ms })
state.timer = set_timeout(ms, function()
vim.schedule(function() filtered:set(value) end)
-- If a timer was allowed to run to completion, that means that no other
-- item has been queued, since the timer is reset every time a new item
-- comes in. This means we can reset the queue
clear_timeout()
state.queued = {}
end)
end)
filtered:on_dispose(unsubscribe_from_self)
return filtered
end
--- @param callback function
function Signal:subscribe(callback)
table.insert(self.subscribers, callback)
return function() self:unsubscribe(callback) end
end
--- @param callback function
function Signal:on_dispose(callback) table.insert(self.on_dispose_callbacks, callback) end
--- @param callback function
function Signal:unsubscribe(callback)
for i, cb in ipairs(self.subscribers) do
if cb == callback then
table.remove(self.subscribers, i)
break
end
end
end
function Signal:dispose()
self.subscribers = {}
for _, callback in ipairs(self.on_dispose_callbacks) do
callback()
end
end
--------------------------------------------------------------------------------
-- class ExecutionContext
--------------------------------------------------------------------------------
CURRENT_CONTEXT = nil
--- @class ExecutionContext
--- @field signals table<Signal, boolean>
local ExecutionContext = {}
M.ExecutionContext = ExecutionContext
ExecutionContext.__index = ExecutionContext
--- @return ExecutionContext
function ExecutionContext:new()
return setmetatable({
signals = {},
subscribers = {},
}, ExecutionContext)
end
function ExecutionContext.current() return CURRENT_CONTEXT end
--- @param fn function
--- @param ctx ExecutionContext
function ExecutionContext:run(fn, ctx)
local oldCtx = CURRENT_CONTEXT
CURRENT_CONTEXT = ctx
local result
local success, err = pcall(function() result = fn() end)
CURRENT_CONTEXT = oldCtx
if not success then error(err) end
return result
end
function ExecutionContext:track(signal) self.signals[signal] = true end
--- @param callback function
function ExecutionContext:subscribe(callback)
local wrapped_callback = function() callback() end
for signal in pairs(self.signals) do
signal:subscribe(wrapped_callback)
end
return function()
for signal in pairs(self.signals) do
signal:unsubscribe(wrapped_callback)
end
end
end
function ExecutionContext:dispose()
for signal, _ in pairs(self.signals) do
signal:dispose()
end
self.signals = {}
end
--------------------------------------------------------------------------------
-- Helpers
--------------------------------------------------------------------------------
--- @param value any
--- @param name? string
--- @return Signal
function M.create_signal(value, name) return Signal:new(value, name) end
--- @param fn function
--- @param name? string
--- @return Signal
function M.create_memo(fn, name)
--- @type Signal
local result
local unsubscribe = M.create_effect(function()
local value = fn()
if name and M.debug then vim.notify(name) end
if result then
result:set(value)
else
result = M.create_signal(value, name and ('m.s:' .. name) or nil)
end
end, name)
result:on_dispose(unsubscribe)
return result
end
--- @param fn function
--- @param name? string
function M.create_effect(fn, name)
local ctx = M.ExecutionContext:new()
M.ExecutionContext:run(fn, ctx)
return ctx:subscribe(function()
if name and M.debug then
local deps = vim
.iter(vim.tbl_keys(ctx.signals))
:map(function(s) return s.name end)
:filter(function(nm) return nm ~= nil end)
:join ','
vim.notify(name .. '(deps=' .. deps .. ')')
end
fn()
end)
end
return M

View File

@ -8,6 +8,18 @@ local M = {}
---@alias KeyMaps table<string, fun(): any | string> } ---@alias KeyMaps table<string, fun(): any | string> }
---@alias CmdArgs { args: string; bang: boolean; count: number; fargs: string[]; line1: number; line2: number; mods: string; name: string; range: 0|1|2; reg: string; smods: any; info: Range|nil } ---@alias CmdArgs { args: string; bang: boolean; count: number; fargs: string[]; line1: number; line2: number; mods: string; name: string; range: 0|1|2; reg: string; smods: any; info: Range|nil }
--- @generic T
--- @param x `T`
--- @param message? string
--- @return T
function M.dbg(x, message)
local t = {}
if message ~= nil then table.insert(t, message) end
table.insert(t, x)
vim.print(t)
return x
end
--- A utility for creating user commands that also pre-computes useful information --- A utility for creating user commands that also pre-computes useful information
--- and attaches it to the arguments. --- and attaches it to the arguments.
--- ---
@ -107,28 +119,97 @@ function M.repeatablemap(mode, lhs, rhs, opts)
end, vim.tbl_extend('force', opts or {}, { expr = true })) end, vim.tbl_extend('force', opts or {}, { expr = true }))
end end
function M.get_editor_dimensions() function M.get_editor_dimensions() return { width = vim.go.columns, height = vim.go.lines } end
local w = 0
local h = 0 --- @alias LevenshteinChange<T> ({ kind: 'add'; item: T; index: number; } | { kind: 'delete'; item: T; index: number; } | { kind: 'change'; from: T; to: T; index: number; })
local tabnr = vim.api.nvim_get_current_tabpage() --- @private
for _, winid in ipairs(vim.api.nvim_list_wins()) do --- @generic T
local tabpage = vim.api.nvim_win_get_tabpage(winid) --- @param x `T`[]
if tabpage == tabnr then --- @param y T[]
local pos = vim.api.nvim_win_get_position(winid) --- @param cost? { of_delete?: fun(x: T): number; of_add?: fun(x: T): number; of_change?: fun(x: T, y: T): number; }
local r, c = pos[1], pos[2] --- @return LevenshteinChange<T>[]
local win_w = vim.api.nvim_win_get_width(winid) function M.levenshtein(x, y, cost)
local win_h = vim.api.nvim_win_get_height(winid) cost = cost or {}
local right = c + win_w local cost_of_delete_f = cost.of_delete or function() return 1 end
local bottom = r + win_h local cost_of_add_f = cost.of_add or function() return 1 end
if right > w then w = right end local cost_of_change_f = cost.of_change or function() return 1 end
if bottom > h then h = bottom end
local m, n = #x, #y
-- Initialize the distance matrix
local dp = {}
for i = 0, m do
dp[i] = {}
for j = 0, n do
dp[i][j] = 0
end end
end end
if w == 0 or h == 0 then
w = vim.api.nvim_win_get_width(0) -- Fill the base cases
h = vim.api.nvim_win_get_height(0) for i = 0, m do
dp[i][0] = i
end end
return { width = w, height = h } for j = 0, n do
dp[0][j] = j
end
-- Compute the Levenshtein distance dynamically
for i = 1, m do
for j = 1, n do
if x[i] == y[j] then
dp[i][j] = dp[i - 1][j - 1] -- no cost if items are the same
else
local costDelete = dp[i - 1][j] + cost_of_delete_f(x[i])
local costAdd = dp[i][j - 1] + cost_of_add_f(y[j])
local costChange = dp[i - 1][j - 1] + cost_of_change_f(x[i], y[j])
dp[i][j] = math.min(costDelete, costAdd, costChange)
end
end
end
-- Backtrack to find the changes
local i = m
local j = n
--- @type LevenshteinChange[]
local changes = {}
while i > 0 or j > 0 do
local default_cost = dp[i][j]
local cost_of_change = (i > 0 and j > 0) and dp[i - 1][j - 1] or default_cost
local cost_of_add = j > 0 and dp[i][j - 1] or default_cost
local cost_of_delete = i > 0 and dp[i - 1][j] or default_cost
--- @param u number
--- @param v number
--- @param w number
local function is_first_min(u, v, w) return u <= v and u <= w end
if is_first_min(cost_of_change, cost_of_add, cost_of_delete) then
-- potential change
if x[i] ~= y[j] then
--- @type LevenshteinChange
local change = { kind = 'change', from = x[i], index = i, to = y[j] }
table.insert(changes, change)
end
i = i - 1
j = j - 1
elseif is_first_min(cost_of_add, cost_of_change, cost_of_delete) then
-- addition
--- @type LevenshteinChange
local change = { kind = 'add', item = y[j], index = i + 1 }
table.insert(changes, change)
j = j - 1
elseif is_first_min(cost_of_delete, cost_of_change, cost_of_add) then
-- deletion
--- @type LevenshteinChange
local change = { kind = 'delete', item = x[i], index = i }
table.insert(changes, change)
i = i - 1
else
error 'unreachable'
end
end
return changes
end end
return M return M

206
spec/tracker_spec.lua Normal file
View File

@ -0,0 +1,206 @@
local tracker = require 'u.tracker'
local Signal = tracker.Signal
local ExecutionContext = tracker.ExecutionContext
describe('Signal', function()
local signal
before_each(function() signal = Signal:new(0, 'testSignal') end)
it('should initialize with correct parameters', function()
assert.is.equal(signal.value, 0)
assert.is.equal(signal.name, 'testSignal')
assert.is.not_nil(signal.subscribers)
assert.is.equal(#signal.subscribers, 0)
assert.is.equal(signal.changing, false)
end)
it('should set new value and notify subscribers', function()
local called = false
signal:subscribe(function(value)
called = true
assert.is.equal(value, 42)
end)
signal:set(42)
assert.is.equal(called, true)
end)
it('should not notify subscribers during circular dependency', function()
signal.changing = true
local notified = false
signal:subscribe(function() notified = true end)
signal:set(42)
assert.is.equal(notified, false) -- No notification should occur
end)
it('should get current value', function()
signal:set(100)
assert.is.equal(signal:get(), 100)
end)
it('should update value with function', function()
signal:set(10)
signal:update(function(value) return value * 2 end)
assert.is.equal(signal:get(), 20)
end)
it('should dispose subscribers', function()
local called = false
local unsubscribe = signal:subscribe(function() called = true end)
unsubscribe()
signal:set(10)
assert.is.equal(called, false) -- Should not be notified
end)
describe('Signal:map', function()
it('should transform the signal value', function()
local signal = Signal:new(5)
local mapped_signal = signal:map(function(value) return value * 2 end)
assert.is.equal(mapped_signal:get(), 10) -- Initial transformation
signal:set(10)
assert.is.equal(mapped_signal:get(), 20) -- Updated transformation
end)
it('should handle empty transformations', function()
local signal = Signal:new(nil)
local mapped_signal = signal:map(function(value) return value or 'default' end)
assert.is.equal(mapped_signal:get(), 'default') -- Return default
signal:set 'new value'
assert.is.equal(mapped_signal:get(), 'new value') -- Return new value
end)
end)
describe('Signal:filter', function()
it('should only emit values that pass the filter', function()
local signal = Signal:new(5)
local filtered_signal = signal:filter(function(value) return value > 10 end)
assert.is.equal(filtered_signal:get(), nil) -- Initial value should not pass
signal:set(15)
assert.is.equal(filtered_signal:get(), 15) -- Now filtered
signal:set(8)
assert.is.equal(filtered_signal:get(), 15) -- Does not pass the filter
end)
it('should handle empty initial values', function()
local signal = Signal:new(nil)
local filtered_signal = signal:filter(function(value) return value ~= nil end)
assert.is.equal(filtered_signal:get(), nil) -- Should be nil
signal:set(10)
assert.is.equal(filtered_signal:get(), 10) -- Should pass now
end)
end)
describe('create_memo', function()
it('should compute a derived value and update when dependencies change', function()
local signal = Signal:new(2)
local memoized_signal = tracker.create_memo(function() return signal:get() * 2 end)
assert.is.equal(memoized_signal:get(), 4) -- Initially compute 2 * 2
signal:set(3)
assert.is.equal(memoized_signal:get(), 6) -- Update to 3 * 2 = 6
signal:set(5)
assert.is.equal(memoized_signal:get(), 10) -- Update to 5 * 2 = 10
end)
it('should not recompute if the dependencies do not change', function()
local call_count = 0
local signal = Signal:new(10)
local memoized_signal = tracker.create_memo(function()
call_count = call_count + 1
return signal:get() + 1
end)
assert.is.equal(memoized_signal:get(), 11) -- Compute first value
assert.is.equal(call_count, 1) -- Should compute once
memoized_signal:get() -- Call again, should use memoized value
assert.is.equal(call_count, 1) -- Still should only be one call
signal:set(10) -- Set the same value
assert.is.equal(memoized_signal:get(), 11)
assert.is.equal(call_count, 2)
signal:set(20)
assert.is.equal(memoized_signal:get(), 21)
assert.is.equal(call_count, 3)
end)
end)
describe('create_effect', function()
it('should track changes and execute callback', function()
local signal = Signal:new(5)
local call_count = 0
tracker.create_effect(function()
signal:get() -- track as a dependency
call_count = call_count + 1
end)
assert.is.equal(call_count, 1)
signal:set(10)
assert.is.equal(call_count, 2)
end)
it('should clean up signals and not call after dispose', function()
local signal = Signal:new(5)
local call_count = 0
local unsubscribe = tracker.create_effect(function()
call_count = call_count + 1
return signal:get() * 2
end)
assert.is.equal(call_count, 1) -- Initially calls
unsubscribe() -- Unsubscribe the effect
signal:set(10) -- Update signal value
assert.is.equal(call_count, 1) -- Callback should not be called again
end)
end)
end)
describe('ExecutionContext', function()
local context
before_each(function() context = ExecutionContext:new() end)
it('should initialize a new context', function()
assert.is.table(context.signals)
assert.is.table(context.subscribers)
end)
it('should track signals', function()
local signal = Signal:new(0)
context:track(signal)
assert.is.equal(next(context.signals), signal) -- Check if signal is tracked
end)
it('should subscribe to signals', function()
local signal = Signal:new(0)
local callback_called = false
context:track(signal)
context:subscribe(function() callback_called = true end)
signal:set(100)
assert.is.equal(callback_called, true) -- Callback should be called
end)
it('should dispose tracked signals', function()
local signal = Signal:new(0)
context:track(signal)
context:dispose()
assert.is.falsy(next(context.signals)) -- Should not have any tracked signals
end)
end)

70
spec/utils_spec.lua Normal file
View File

@ -0,0 +1,70 @@
local utils = require 'u.utils'
--- @param s string
local function split(s) return vim.split(s, '') end
--- @param original string
--- @param changes LevenshteinChange[]
local function morph(original, changes)
local t = split(original)
for _, change in ipairs(changes) do
if change.kind == 'add' then
table.insert(t, change.index, change.item)
elseif change.kind == 'delete' then
table.remove(t, change.index)
elseif change.kind == 'change' then
t[change.index] = change.to
end
end
return vim.iter(t):join ''
end
describe('utils', function()
it('levenshtein', function()
local original = 'abc'
local result = 'absece'
local changes = utils.levenshtein(split(original), split(result))
assert.are.same(changes, {
{
item = 'e',
kind = 'add',
index = 4,
},
{
item = 'e',
kind = 'add',
index = 3,
},
{
item = 's',
kind = 'add',
index = 3,
},
})
assert.are.same(morph(original, changes), result)
original = 'jonathan'
result = 'ajoanthan'
changes = utils.levenshtein(split(original), split(result))
assert.are.same(changes, {
{
from = 'a',
index = 4,
kind = 'change',
to = 'n',
},
{
from = 'n',
index = 3,
kind = 'change',
to = 'a',
},
{
index = 1,
item = 'a',
kind = 'add',
},
})
assert.are.same(morph(original, changes), result)
end)
end)