update lua API to 1-based indices; add renderer
All checks were successful
NeoVim tests / plenary-tests (push) Successful in 10s

This commit is contained in:
2025-05-04 15:22:19 -06:00
parent 7fb60add94
commit 4dfadf97e5
32 changed files with 4309 additions and 1067 deletions

5
lua/u/.luarc.json Normal file
View File

@@ -0,0 +1,5 @@
{
"$schema": "https://raw.githubusercontent.com/LuaLS/vscode-lua/master/setting/schema.json",
"diagnostics.globals": ["assert", "vim"],
"runtime.version": "LuaJIT"
}

View File

@@ -1,72 +1,128 @@
local Range = require 'u.range'
local Renderer = require('u.renderer').Renderer
---@class Buffer
---@field buf number
--- @class u.Buffer
--- @field bufnr number
--- @field b vim.var_accessor
--- @field bo vim.bo
--- @field private renderer u.Renderer
local Buffer = {}
Buffer.__index = Buffer
---@param buf? number
---@return Buffer
function Buffer.from_nr(buf)
if buf == nil or buf == 0 then buf = vim.api.nvim_get_current_buf() end
local b = { buf = buf }
setmetatable(b, { __index = Buffer })
return b
--- @param bufnr? number
--- @return u.Buffer
function Buffer.from_nr(bufnr)
if bufnr == nil or bufnr == 0 then bufnr = vim.api.nvim_get_current_buf() end
local renderer = Renderer.new(bufnr)
return setmetatable({
bufnr = bufnr,
b = vim.b[bufnr],
bo = vim.bo[bufnr],
renderer = renderer,
}, Buffer)
end
---@return Buffer
--- @return u.Buffer
function Buffer.current() return Buffer.from_nr(0) end
---@param listed boolean
---@param scratch boolean
---@return Buffer
function Buffer.create(listed, scratch) return Buffer.from_nr(vim.api.nvim_create_buf(listed, scratch)) end
function Buffer:set_tmp_options()
self:set_option('bufhidden', 'delete')
self:set_option('buflisted', false)
self:set_option('buftype', 'nowrite')
--- @param listed boolean
--- @param scratch boolean
--- @return u.Buffer
function Buffer.create(listed, scratch)
return Buffer.from_nr(vim.api.nvim_create_buf(listed, scratch))
end
---@param nm string
function Buffer:get_option(nm) return vim.api.nvim_get_option_value(nm, { buf = self.buf }) end
function Buffer:set_tmp_options()
self.bo.bufhidden = 'delete'
self.bo.buflisted = false
self.bo.buftype = 'nowrite'
end
---@param nm string
function Buffer:set_option(nm, val) return vim.api.nvim_set_option_value(nm, val, { buf = self.buf }) end
function Buffer:line_count() return vim.api.nvim_buf_line_count(self.bufnr) end
---@param nm string
function Buffer:get_var(nm) return vim.api.nvim_buf_get_var(self.buf, nm) end
function Buffer:all() return Range.from_buf_text(self.bufnr) end
---@param nm string
function Buffer:set_var(nm, val) return vim.api.nvim_buf_set_var(self.buf, nm, val) end
function Buffer:is_empty() return self:line_count() == 1 and self:line(1):text() == '' end
function Buffer:line_count() return vim.api.nvim_buf_line_count(self.buf) end
function Buffer:all() return Range.from_buf_text(self.buf) end
function Buffer:is_empty() return self:line_count() == 1 and self:line0(0):text() == '' end
---@param line string
--- @param line string
function Buffer:append_line(line)
local start = -1
if self:is_empty() then start = -2 end
vim.api.nvim_buf_set_lines(self.buf, start, -1, false, { line })
vim.api.nvim_buf_set_lines(self.bufnr, start, -1, false, { line })
end
---@param num number 0-based line index
function Buffer:line0(num)
if num < 0 then return self:line0(self:line_count() + num) end
return Range.from_line(self.buf, num)
--- @param num number 1-based line index
function Buffer:line(num)
if num < 0 then num = self:line_count() + num + 1 end
return Range.from_line(self.bufnr, num)
end
---@param start number 0-based line index
---@param stop number 0-based line index
function Buffer:lines(start, stop) return Range.from_lines(self.buf, start, stop) end
--- @param start number 1-based line index
--- @param stop number 1-based line index
function Buffer:lines(start, stop) return Range.from_lines(self.bufnr, start, stop) end
---@param txt_obj string
---@param opts? { contains_cursor?: boolean; pos?: Pos }
function Buffer:text_object(txt_obj, opts)
opts = vim.tbl_extend('force', opts or {}, { buf = self.buf })
return Range.from_text_object(txt_obj, opts)
--- @param motion string
--- @param opts? { contains_cursor?: boolean; pos?: u.Pos }
function Buffer:motion(motion, opts)
opts = vim.tbl_extend('force', opts or {}, { bufnr = self.bufnr })
return Range.from_motion(motion, opts)
end
--- @param event string|string[]
--- @diagnostic disable-next-line: undefined-doc-name
--- @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.bufnr }))
end
--- @param tree u.renderer.Tree
function Buffer:render(tree) return self.renderer:render(tree) end
--- Filter buffer content through an external command (like Vim's :%!)
--- @param cmd string[] Command to run (with arguments)
--- @param opts? {cwd?: string, preserve_cursor?: boolean}
--- @return nil
--- @throws string Error message if command fails
--- @note Special placeholders in cmd:
--- - $FILE: replaced with the buffer's filename (if any)
--- - $DIR: replaced with the buffer's directory (if any)
function Buffer:filter_cmd(cmd, opts)
opts = opts or {}
local cwd = opts.cwd or vim.uv.cwd()
local old_lines = self:all():lines()
-- Save cursor position if needed, defaulting to true
local save_pos = opts.preserve_cursor ~= false and vim.fn.winsaveview()
-- Run the command
local result = vim
.system(
-- Replace special placeholders in `cmd` with their values:
vim
.iter(cmd)
:map(function(x)
if x == '$FILE' then return vim.api.nvim_buf_get_name(self.bufnr) end
if x == '$DIR' then return vim.fs.dirname(vim.api.nvim_buf_get_name(self.bufnr)) end
return x
end)
:totable(),
{
cwd = cwd,
stdin = old_lines,
text = true,
}
)
:wait()
-- Check for command failure
if result.code ~= 0 then error('Command failed: ' .. (result.stderr or '')) end
-- Process and apply the result
local new_lines = vim.split(result.stdout, '\n')
if new_lines[#new_lines] == '' then table.remove(new_lines) end
Renderer.patch_lines(self.bufnr, old_lines, new_lines)
-- Restore cursor position if saved
if save_pos then vim.fn.winrestview(save_pos) end
end
return Buffer

View File

@@ -1,14 +1,15 @@
local Buffer = require 'u.buffer'
---@class CodeWriter
---@field lines string[]
---@field indent_level number
---@field indent_str string
--- @class u.CodeWriter
--- @field lines string[]
--- @field indent_level number
--- @field indent_str string
local CodeWriter = {}
CodeWriter.__index = CodeWriter
---@param indent_level? number
---@param indent_str? string
---@return CodeWriter
--- @param indent_level? number
--- @param indent_str? string
--- @return u.CodeWriter
function CodeWriter.new(indent_level, indent_str)
if indent_level == nil then indent_level = 0 end
if indent_str == nil then indent_str = ' ' end
@@ -18,26 +19,27 @@ function CodeWriter.new(indent_level, indent_str)
indent_level = indent_level,
indent_str = indent_str,
}
setmetatable(cw, { __index = CodeWriter })
setmetatable(cw, CodeWriter)
return cw
end
---@param p Pos
--- @param p u.Pos
function CodeWriter.from_pos(p)
local line = Buffer.from_nr(p.buf):line0(p.lnum):text()
return CodeWriter.from_line(line, p.buf)
local line = Buffer.from_nr(p.bufnr):line(p.lnum):text()
return CodeWriter.from_line(line, p.bufnr)
end
---@param line string
---@param buf? number
function CodeWriter.from_line(line, buf)
if buf == nil then buf = vim.api.nvim_get_current_buf() end
--- @param line string
--- @param bufnr? number
function CodeWriter.from_line(line, bufnr)
if bufnr == nil then bufnr = vim.api.nvim_get_current_buf() end
local ws = line:match '^%s*'
local expandtab = vim.api.nvim_get_option_value('expandtab', { buf = buf })
local shiftwidth = vim.api.nvim_get_option_value('shiftwidth', { buf = buf })
local expandtab = vim.api.nvim_get_option_value('expandtab', { buf = bufnr })
local shiftwidth = vim.api.nvim_get_option_value('shiftwidth', { buf = bufnr })
local indent_level = 0
--- @type number
local indent_level
local indent_str = ''
if expandtab then
while #indent_str < shiftwidth do
@@ -52,16 +54,16 @@ function CodeWriter.from_line(line, buf)
return CodeWriter.new(indent_level, indent_str)
end
---@param line string
--- @param line string
function CodeWriter:write_raw(line)
if line:find '\n' then error 'line contains newline character' end
table.insert(self.lines, line)
end
---@param line string
--- @param line string
function CodeWriter:write(line) self:write_raw(self.indent_str:rep(self.indent_level) .. line) end
---@param f? fun(cw: CodeWriter):any
--- @param f? fun(cw: u.CodeWriter):any
function CodeWriter:indent(f)
local cw = {
lines = self.lines,

69
lua/u/logger.lua Normal file
View File

@@ -0,0 +1,69 @@
local M = {}
--- @params name string
function M.file_for_name(name)
return vim.fs.joinpath(vim.fn.stdpath 'cache', 'u.log', name .. '.log.jsonl')
end
--------------------------------------------------------------------------------
-- Logger class
--------------------------------------------------------------------------------
--- @class u.Logger
--- @field name string
--- @field private fd number
local Logger = {}
Logger.__index = Logger
M.Logger = Logger
--- @param name string
function Logger.new(name)
local file_path = M.file_for_name(name)
vim.fn.mkdir(vim.fs.dirname(file_path), 'p')
local self = setmetatable({
name = name,
fd = (vim.uv or vim.loop).fs_open(file_path, 'a', tonumber('644', 8)),
}, Logger)
return self
end
--- @private
--- @param level string
function Logger:write(level, ...)
local data = { ... }
if #data == 1 then data = data[1] end
(vim.uv or vim.loop).fs_write(
self.fd,
vim.json.encode { ts = os.date(), level = level, data = data } .. '\n'
)
end
function Logger:trace(...) self:write('INFO', ...) end
function Logger:debug(...) self:write('DEBUG', ...) end
function Logger:info(...) self:write('INFO', ...) end
function Logger:warn(...) self:write('WARN', ...) end
function Logger:error(...) self:write('ERROR', ...) end
function M.setup()
vim.api.nvim_create_user_command('Logfollow', function(args)
if #args.fargs == 0 then
vim.print 'expected log name'
return
end
local log_file_path = M.file_for_name(args.fargs[1])
vim.fn.mkdir(vim.fs.dirname(log_file_path), 'p')
vim.system({ 'touch', log_file_path }):wait()
vim.cmd.new()
local winnr = vim.api.nvim_get_current_win()
vim.wo[winnr][0].number = false
vim.wo[winnr][0].relativenumber = false
vim.cmd.terminal('tail -f "' .. log_file_path .. '"')
vim.cmd.startinsert()
end, { nargs = '*' })
end
return M

View File

@@ -1,24 +1,17 @@
local Range = require 'u.range'
local vim_repeat = require 'u.repeat'
---@type fun(range: Range): nil|(fun():any)
--- @type fun(range: u.Range): nil|(fun():any)
local __U__OpKeymapOpFunc_rhs = nil
--- This is the global utility function used for operatorfunc
--- in opkeymap
---@type nil|fun(range: Range): fun():any|nil
---@param ty 'line'|'char'|'block'
--- @type nil|fun(range: u.Range): fun():any|nil
--- @param ty 'line'|'char'|'block'
-- selene: allow(unused_variable)
function __U__OpKeymapOpFunc(ty)
function _G.__U__OpKeymapOpFunc(ty)
if __U__OpKeymapOpFunc_rhs ~= nil then
local range = Range.from_op_func(ty)
local repeat_inject = __U__OpKeymapOpFunc_rhs(range)
vim_repeat.set(function()
vim.o.operatorfunc = 'v:lua.__U__OpKeymapOpFunc'
if repeat_inject ~= nil and type(repeat_inject) == 'function' then repeat_inject() end
vim_repeat.native_repeat()
end)
__U__OpKeymapOpFunc_rhs(range)
end
end
@@ -28,12 +21,17 @@ end
--- g@: tells vim to way for a motion, and then call operatorfunc.
--- 2. The operatorfunc is set to a lua function that computes the range being operated over, that
--- then calls the original passed callback with said range.
---@param mode string|string[]
---@param lhs string
---@param rhs fun(range: Range): nil|(fun():any) This function may return another function, which is called whenever the operator is repeated
---@param opts? vim.keymap.set.Opts
--- @param mode string|string[]
--- @param lhs string
--- @param rhs fun(range: u.Range): nil
--- @diagnostic disable-next-line: undefined-doc-name
--- @param opts? vim.keymap.set.Opts
local function opkeymap(mode, lhs, rhs, opts)
vim.keymap.set(mode, lhs, function()
-- We don't need to wrap the operation in a repeat, because expr mappings are
-- repeated seamlessly by Vim anyway. In addition, the u.repeat:`.` mapping will
-- set IS_REPEATING to true, so that callbacks can check if they should used cached
-- values.
__U__OpKeymapOpFunc_rhs = rhs
vim.o.operatorfunc = 'v:lua.__U__OpKeymapOpFunc'
return 'g@'

View File

@@ -1,162 +1,170 @@
local MAX_COL = vim.v.maxcol
---@param buf number
---@param lnum number
local function line_text(buf, lnum) return vim.api.nvim_buf_get_lines(buf, lnum, lnum + 1, false)[1] end
--- @param bufnr number
--- @param lnum number 1-based
local function line_text(bufnr, lnum)
return vim.api.nvim_buf_get_lines(bufnr, lnum - 1, lnum, false)[1]
end
---@class Pos
---@field buf number buffer number
---@field lnum number 1-based line index
---@field col number 1-based column index
---@field off number
--- @class u.Pos
--- @field bufnr number buffer number
--- @field lnum number 1-based line index
--- @field col number 1-based column index
--- @field off number
local Pos = {}
Pos.__index = Pos
Pos.MAX_COL = MAX_COL
---@param buf? number
---@param lnum number
---@param col number
---@param off? number
---@return Pos
function Pos.new(buf, lnum, col, off)
if buf == nil or buf == 0 then buf = vim.api.nvim_get_current_buf() end
function Pos.__tostring(self)
if self.off ~= 0 then
return string.format('Pos(%d:%d){bufnr=%d, off=%d}', self.lnum, self.col, self.bufnr, self.off)
else
return string.format('Pos(%d:%d){bufnr=%d}', self.lnum, self.col, self.bufnr)
end
end
--- @param bufnr? number
--- @param lnum number 1-based
--- @param col number 1-based
--- @param off? number
--- @return u.Pos
function Pos.new(bufnr, lnum, col, off)
if bufnr == nil or bufnr == 0 then bufnr = vim.api.nvim_get_current_buf() end
if off == nil then off = 0 end
local pos = {
buf = buf,
bufnr = bufnr,
lnum = lnum,
col = col,
off = off,
}
local function str()
if pos.off ~= 0 then
return string.format('Pos(%d:%d){buf=%d, off=%d}', pos.lnum, pos.col, pos.buf, pos.off)
else
return string.format('Pos(%d:%d){buf=%d}', pos.lnum, pos.col, pos.buf)
end
end
setmetatable(pos, {
__index = Pos,
__tostring = str,
__lt = Pos.__lt,
__le = Pos.__le,
__eq = Pos.__eq,
})
setmetatable(pos, Pos)
return pos
end
function Pos.is(x)
local mt = getmetatable(x)
return mt and mt.__index == Pos
end
function Pos.invalid() return Pos.new(0, 0, 0, 0) end
function Pos.__lt(a, b) return a.lnum < b.lnum or (a.lnum == b.lnum and a.col < b.col) end
function Pos.__le(a, b) return a < b or a == b end
function Pos.__eq(a, b) return a.lnum == b.lnum and a.col == b.col end
---@param name string
---@return Pos
function Pos.from_pos(name)
local p = vim.fn.getpos(name)
local col = p[3]
if col ~= MAX_COL then col = col - 1 end
return Pos.new(p[1], p[2] - 1, col, p[4])
function Pos.__eq(a, b)
return getmetatable(a) == Pos
and getmetatable(b) == Pos
and a.bufnr == b.bufnr
and a.lnum == b.lnum
and a.col == b.col
end
function Pos.__add(x, y)
if type(x) == 'number' then
x, y = y, x
end
if getmetatable(x) ~= Pos or type(y) ~= 'number' then return nil end
return x:next(y)
end
function Pos.__sub(x, y)
if type(x) == 'number' then
x, y = y, x
end
if getmetatable(x) ~= Pos or type(y) ~= 'number' then return nil end
return x:next(-y)
end
function Pos:clone() return Pos.new(self.buf, self.lnum, self.col, self.off) end
--- @param name string
--- @return u.Pos
function Pos.from_pos(name)
local p = vim.fn.getpos(name)
return Pos.new(p[1], p[2], p[3], p[4])
end
---@return boolean
function Pos:is_invalid() return self.lnum == 0 and self.col == 0 and self.off == 0 end
function Pos:clone() return Pos.new(self.bufnr, self.lnum, self.col, self.off) end
--- @return boolean
function Pos:is_col_max() return self.col == MAX_COL end
---@return number[]
function Pos:as_vim() return { self.buf, self.lnum, self.col, self.off } end
--- Normalize the position to a real position (take into account vim.v.maxcol).
function Pos:as_real()
local maxlen = #line_text(self.bufnr, self.lnum)
local col = self.col
if self:is_col_max() then
if col > maxlen then
-- We could use utilities in this file to get the given line, but
-- since this is a low-level function, we are going to optimize and
-- use the API directly:
col = #line_text(self.buf, self.lnum) - 1
col = maxlen
end
return Pos.new(self.buf, self.lnum, col, self.off)
return Pos.new(self.bufnr, self.lnum, col, self.off)
end
---@param pos string
function Pos:save_to_pos(pos)
if pos == '.' then
vim.api.nvim_win_set_cursor(0, { self.lnum + 1, self.col })
return
end
function Pos:as_vim() return { self.bufnr, self.lnum, self.col, self.off } end
local p = self:as_real()
vim.fn.setpos(pos, { p.buf, p.lnum + 1, p.col + 1, p.off })
end
--- @param pos string
function Pos:save_to_pos(pos) vim.fn.setpos(pos, { self.bufnr, self.lnum, self.col, self.off }) end
---@param mark string
--- @param mark string
function Pos:save_to_mark(mark)
local p = self:as_real()
vim.api.nvim_buf_set_mark(p.buf, mark, p.lnum + 1, p.col, {})
vim.api.nvim_buf_set_mark(p.bufnr, mark, p.lnum, p.col - 1, {})
end
---@return string
--- @return string
function Pos:char()
local line = line_text(self.buf, self.lnum)
local line = line_text(self.bufnr, self.lnum)
if line == nil then return '' end
return line:sub(self.col + 1, self.col + 1)
return line:sub(self.col, self.col)
end
---@param dir? -1|1
---@param must? boolean
---@return Pos|nil
function Pos:line() return line_text(self.bufnr, self.lnum) end
--- @param dir? -1|1
--- @param must? boolean
--- @return u.Pos|nil
function Pos:next(dir, must)
if must == nil then must = false end
if dir == nil or dir == 1 then
-- Next:
local num_lines = vim.api.nvim_buf_line_count(self.buf)
local last_line = line_text(self.buf, num_lines - 1) -- buf:line0(-1)
if self.lnum == num_lines - 1 and self.col == (#last_line - 1) then
local num_lines = vim.api.nvim_buf_line_count(self.bufnr)
local last_line = line_text(self.bufnr, num_lines)
if self.lnum == num_lines and self.col == #last_line then
if must then error 'error in Pos:next(): Pos:next() returned nil' end
return nil
end
local col = self.col + 1
local line = self.lnum
local line_max_col = #line_text(self.buf, self.lnum) - 1
local line_max_col = #line_text(self.bufnr, self.lnum)
if col > line_max_col then
col = 0
col = 1
line = line + 1
end
return Pos.new(self.buf, line, col, self.off)
return Pos.new(self.bufnr, line, col, self.off)
else
-- Previous:
if self.col == 0 and self.lnum == 0 then
if self.col == 1 and self.lnum == 1 then
if must then error 'error in Pos:next(): Pos:next() returned nil' end
return nil
end
local col = self.col - 1
local line = self.lnum
local prev_line_max_col = #(line_text(self.buf, self.lnum - 1) or '') - 1
if col < 0 then
col = math.max(prev_line_max_col, 0)
local prev_line_max_col = #(line_text(self.bufnr, self.lnum - 1) or '')
if col < 1 then
col = math.max(prev_line_max_col, 1)
line = line - 1
end
return Pos.new(self.buf, line, col, self.off)
return Pos.new(self.bufnr, line, col, self.off)
end
end
---@param dir? -1|1
--- @param dir? -1|1
function Pos:must_next(dir)
local next = self:next(dir, true)
if next == nil then error 'unreachable' end
return next
end
---@param dir -1|1
---@param predicate fun(p: Pos): boolean
---@param test_current? boolean
--- @param dir -1|1
--- @param predicate fun(p: u.Pos): boolean
--- @param test_current? boolean
function Pos:next_while(dir, predicate, test_current)
if test_current and not predicate(self) then return end
local curr = self
@@ -168,15 +176,15 @@ function Pos:next_while(dir, predicate, test_current)
return curr
end
---@param dir -1|1
---@param predicate string|fun(p: Pos): boolean
--- @param dir -1|1
--- @param predicate string|fun(p: u.Pos): boolean
function Pos:find_next(dir, predicate)
if type(predicate) == 'string' then
local s = predicate
predicate = function(p) return s == p:char() end
end
---@type Pos|nil
--- @type u.Pos|nil
local curr = self
while curr ~= nil do
if predicate(curr) then return curr end
@@ -186,12 +194,14 @@ function Pos:find_next(dir, predicate)
end
--- Finds the matching bracket/paren for the current position.
---@param max_chars? number|nil
---@param invocations? Pos[]
---@return Pos|nil
--- @param max_chars? number|nil
--- @param invocations? u.Pos[]
--- @return u.Pos|nil
function Pos:find_match(max_chars, invocations)
if invocations == nil then invocations = {} end
if vim.tbl_contains(invocations, function(p) return self == p end, { predicate = true }) then return nil end
if vim.tbl_contains(invocations, function(p) return self == p end, { predicate = true }) then
return nil
end
table.insert(invocations, self)
local openers = { '{', '[', '(', '<' }
@@ -201,12 +211,20 @@ function Pos:find_match(max_chars, invocations)
local is_closer = vim.tbl_contains(closers, c)
if not is_opener and not is_closer then return nil end
local i, _ = vim.iter(is_opener and openers or closers):enumerate():find(function(_, c2) return c == c2 end)
local i, _ = vim
.iter(is_opener and openers or closers)
:enumerate()
:find(function(_, c2) return c == c2 end)
-- Store the character we will be looking for:
local c_match = (is_opener and closers or openers)[i]
---@type Pos|nil
--- @type u.Pos|nil
local cur = self
---@return Pos|nil
--- `adv` is a helper that moves the current position backward or forward,
--- depending on whether we are looking for an opener or a closer. It returns
--- nil if 1) the watch-dog `max_chars` falls bellow 0, or 2) if we have gone
--- beyond the beginning/end of the file.
--- @return u.Pos|nil
local function adv()
if cur == nil then return nil end
@@ -218,7 +236,7 @@ function Pos:find_match(max_chars, invocations)
return cur:next(is_opener and 1 or -1)
end
-- scan until we find a match:
-- scan until we find `c_match`:
cur = adv()
while cur ~= nil and cur:char() ~= c_match do
cur = adv()
@@ -236,4 +254,17 @@ function Pos:find_match(max_chars, invocations)
return cur
end
--- @param lines string|string[]
function Pos:insert_before(lines)
if type(lines) == 'string' then lines = vim.split(lines, '\n') end
vim.api.nvim_buf_set_text(
self.bufnr,
self.lnum - 1,
self.col - 1,
self.lnum - 1,
self.col - 1,
lines
)
end
return Pos

View File

@@ -1,62 +1,86 @@
local Pos = require 'u.pos'
local State = require 'u.state'
local orig_on_yank = vim.highlight.on_yank
local on_yank_enabled = true;
(vim.highlight --[[@as any]]).on_yank = function(opts)
-- Certain functions in the Range class yank text. In order to prevent unwanted
-- highlighting, we intercept and discard some calls to the `on_yank` callback.
local orig_on_yank = vim.hl.on_yank
local on_yank_enabled = true
--- @diagnostic disable-next-line: duplicate-set-field
function vim.hl.on_yank(opts)
if not on_yank_enabled then return end
return orig_on_yank(opts)
end
---@class Range
---@field start Pos
---@field stop Pos|nil
---@field mode 'v'|'V'
--- @class u.Range
--- @field start u.Pos
--- @field stop u.Pos|nil
--- @field mode 'v'|'V'
local Range = {}
Range.__index = Range
function Range.__tostring(self)
--- @param p u.Pos
local function posstr(p)
if p == nil then
return 'nil'
elseif p.off ~= 0 then
return string.format('Pos(%d:%d){off=%d}', p.lnum, p.col, p.off)
else
return string.format('Pos(%d:%d)', p.lnum, p.col)
end
end
---@param start Pos
---@param stop Pos|nil
---@param mode? 'v'|'V'
---@return Range
local _1 = posstr(self.start)
local _2 = posstr(self.stop)
return string.format(
'Range{bufnr=%d, mode=%s, start=%s, stop=%s}',
self.start.bufnr,
self.mode,
_1,
_2
)
end
--------------------------------------------------------------------------------
-- Range constructors:
--------------------------------------------------------------------------------
--- @param start u.Pos
--- @param stop u.Pos|nil
--- @param mode? 'v'|'V'
--- @return u.Range
function Range.new(start, stop, mode)
if stop ~= nil and stop < start then
start, stop = stop, start
end
local r = { start = start, stop = stop, mode = mode or 'v' }
local function str()
---@param p Pos
local function posstr(p)
if p == nil then
return 'nil'
elseif p.off ~= 0 then
return string.format('Pos(%d:%d){off=%d}', p.lnum, p.col, p.off)
else
return string.format('Pos(%d:%d)', p.lnum, p.col)
end
end
local _1 = posstr(r.start)
local _2 = posstr(r.stop)
return string.format('Range{buf=%d, mode=%s, start=%s, stop=%s}', r.start.buf, r.mode, _1, _2)
end
setmetatable(r, { __index = Range, __tostring = str })
setmetatable(r, Range)
return r
end
function Range.is(x)
local mt = getmetatable(x)
return mt and mt.__index == Range
--- @param ranges (u.Range|nil)[]
function Range.smallest(ranges)
--- @type u.Range[]
ranges = vim.iter(ranges):filter(function(r) return r ~= nil and not r:is_empty() end):totable()
if #ranges == 0 then return nil end
-- find smallest match
local smallest = ranges[1]
for _, r in ipairs(ranges) do
local start, stop = r.start, r.stop
if start > smallest.start and stop < smallest.stop then smallest = r end
end
return smallest
end
---@param lpos string
---@param rpos string
---@return Range
--- @param lpos string
--- @param rpos string
--- @return u.Range
function Range.from_marks(lpos, rpos)
local start = Pos.from_pos(lpos)
local stop = Pos.from_pos(rpos)
---@type 'v'|'V'
--- @type 'v'|'V'
local mode
if stop:is_col_max() then
mode = 'V'
@@ -67,98 +91,109 @@ function Range.from_marks(lpos, rpos)
return Range.new(start, stop, mode)
end
---@param buf? number
function Range.from_buf_text(buf)
if buf == nil or buf == 0 then buf = vim.api.nvim_get_current_buf() end
local num_lines = vim.api.nvim_buf_line_count(buf)
--- @param bufnr? number
function Range.from_buf_text(bufnr)
if bufnr == nil or bufnr == 0 then bufnr = vim.api.nvim_get_current_buf() end
local num_lines = vim.api.nvim_buf_line_count(bufnr)
local start = Pos.new(buf, 0, 0)
local stop = Pos.new(buf, num_lines - 1, Pos.MAX_COL)
local start = Pos.new(bufnr, 1, 1)
local stop = Pos.new(bufnr, num_lines, Pos.MAX_COL)
return Range.new(start, stop, 'V')
end
---@param buf? number
---@param line number 0-based line index
function Range.from_line(buf, line) return Range.from_lines(buf, line, line) end
--- @param bufnr? number
--- @param line number 1-based line index
function Range.from_line(bufnr, line) return Range.from_lines(bufnr, line, line) end
---@param buf? number
---@param start_line number 0-based line index
---@param stop_line number 0-based line index
function Range.from_lines(buf, start_line, stop_line)
if buf == nil or buf == 0 then buf = vim.api.nvim_get_current_buf() end
--- @param bufnr? number
--- @param start_line number based line index
--- @param stop_line number based line index
function Range.from_lines(bufnr, start_line, stop_line)
if bufnr == nil or bufnr == 0 then bufnr = vim.api.nvim_get_current_buf() end
if stop_line < 0 then
local num_lines = vim.api.nvim_buf_line_count(buf)
stop_line = num_lines + stop_line
local num_lines = vim.api.nvim_buf_line_count(bufnr)
stop_line = num_lines + stop_line + 1
end
return Range.new(Pos.new(buf, start_line, 0), Pos.new(buf, stop_line, Pos.MAX_COL), 'V')
return Range.new(Pos.new(bufnr, start_line, 1), Pos.new(bufnr, stop_line, Pos.MAX_COL), 'V')
end
---@param text_obj string
---@param opts? { buf?: number; contains_cursor?: boolean; pos?: Pos, user_defined?: boolean }
---@return Range|nil
function Range.from_text_object(text_obj, opts)
--- @param motion string
--- @param opts? { bufnr?: number; contains_cursor?: boolean; pos?: u.Pos, user_defined?: boolean }
--- @return u.Range|nil
function Range.from_motion(motion, opts)
-- Options handling:
opts = opts or {}
if opts.buf == nil then opts.buf = vim.api.nvim_get_current_buf() end
if opts.bufnr == nil then opts.bufnr = vim.api.nvim_get_current_buf() end
if opts.contains_cursor == nil then opts.contains_cursor = false end
if opts.user_defined == nil then opts.user_defined = false end
---@type "a" | "i"
local selection_type = text_obj:sub(1, 1)
local obj_type = text_obj:sub(#text_obj, #text_obj)
local is_quote = vim.tbl_contains({ "'", '"', '`' }, obj_type)
local cursor = Pos.from_pos '.'
-- Extract some information from the motion:
--- @type 'a'|'i', string
local scope, motion_rest = motion:sub(1, 1), motion:sub(2)
local is_txtobj = scope == 'a' or scope == 'i'
local is_quote_txtobj = is_txtobj and vim.tbl_contains({ "'", '"', '`' }, motion_rest)
-- Yank, then read '[ and '] to know the bounds:
---@type { start: Pos; stop: Pos }
local positions
vim.api.nvim_buf_call(opts.buf, function()
positions = State.run(0, function(s)
s:track_winview()
s:track_register '"'
s:track_pos '.'
s:track_pos "'["
s:track_pos "']"
--- @type u.Pos
local start
--- @type u.Pos
local stop
-- Capture the original state of the buffer for restoration later.
local original_state = {
winview = vim.fn.winsaveview(),
regquote = vim.fn.getreg '"',
cursor = vim.fn.getpos '.',
pos_lbrack = vim.fn.getpos "'[",
pos_rbrack = vim.fn.getpos "']",
}
vim.api.nvim_buf_call(opts.bufnr, function()
if opts.pos ~= nil then opts.pos:save_to_pos '.' end
if opts.pos ~= nil then opts.pos:save_to_pos '.' end
Pos.invalid():save_to_pos "'["
Pos.invalid():save_to_pos "']"
local null_pos = Pos.new(0, 0, 0, 0)
null_pos:save_to_pos "'["
null_pos:save_to_pos "']"
local prev_on_yank_enabled = on_yank_enabled
on_yank_enabled = false
vim.cmd {
cmd = 'normal',
bang = not opts.user_defined,
args = { '""y' .. motion },
mods = { silent = true },
}
on_yank_enabled = prev_on_yank_enabled
local prev_on_yank_enabled = on_yank_enabled
on_yank_enabled = false
vim.cmd {
cmd = 'normal',
bang = not opts.user_defined,
args = { '""y' .. text_obj },
mods = { silent = true },
}
on_yank_enabled = prev_on_yank_enabled
local start = Pos.from_pos "'["
local stop = Pos.from_pos "']"
if
-- I have no idea why, but when yanking `i"`, the stop-mark is
-- placed on the ending quote. For other text-objects, the stop-
-- mark is placed before the closing character.
(is_quote and selection_type == 'i' and stop:char() == obj_type)
-- *Sigh*, this also sometimes happens for `it` as well.
or (text_obj == 'it' and stop:char() == '<')
then
stop = stop:next(-1) or stop
end
return { start = start, stop = stop }
end)
start = Pos.from_pos "'["
stop = Pos.from_pos "']"
end)
local start = positions.start
local stop = positions.stop
if start == stop and start.lnum == 0 and start.col == 0 and start.off == 0 then return nil end
if opts.contains_cursor and not Range.new(start, stop):contains(cursor) then return nil end
-- Restore original state:
vim.fn.winrestview(original_state.winview)
vim.fn.setreg('"', original_state.regquote)
vim.fn.setpos('.', original_state.cursor)
vim.fn.setpos("'[", original_state.pos_lbrack)
vim.fn.setpos("']", original_state.pos_rbrack)
if is_quote and selection_type == 'a' then
start = start:find_next(1, obj_type) or start
stop = stop:find_next(-1, obj_type) or stop
if start == stop and start:is_invalid() then return nil end
-- Fixup the bounds:
if
-- I have no idea why, but when yanking `i"`, the stop-mark is
-- placed on the ending quote. For other text-objects, the stop-
-- mark is placed before the closing character.
(is_quote_txtobj and scope == 'i' and stop:char() == motion_rest)
-- *Sigh*, this also sometimes happens for `it` as well.
or (motion == 'it' and stop:char() == '<')
then
stop = stop:next(-1) or stop
end
if is_quote_txtobj and scope == 'a' then
start = start:find_next(1, motion_rest) or start
stop = stop:find_next(-1, motion_rest) or stop
end
if
opts.contains_cursor
and not Range.new(start, stop):contains(Pos.new(unpack(original_state.cursor)))
then
return nil
end
return Range.new(start, stop)
@@ -178,7 +213,7 @@ end
--- Get range information from the current text range being operated on
--- as defined by an operator-pending function. Infers line-wise vs. char-wise
--- based on the type, as given by the operator-pending function.
---@param type 'line'|'char'|'block'
--- @param type 'line'|'char'|'block'
function Range.from_op_func(type)
if type == 'block' then error 'block motions not supported' end
@@ -188,12 +223,12 @@ function Range.from_op_func(type)
end
--- Get range information from command arguments.
---@param args unknown
---@return Range|nil
--- @param args unknown
--- @return u.Range|nil
function Range.from_cmd_args(args)
---@type 'v'|'V'
--- @type 'v'|'V'
local mode
---@type nil|Pos
--- @type nil|u.Pos
local start
local stop
if args.range == 0 then
@@ -201,78 +236,153 @@ function Range.from_cmd_args(args)
else
start = Pos.from_pos "'<"
stop = Pos.from_pos "'>"
if stop:is_col_max() then
mode = 'V'
else
mode = 'v'
end
mode = stop:is_col_max() and 'V' or 'v'
end
return Range.new(start, stop, mode)
end
---
function Range.find_nearest_brackets()
local a = Range.from_text_object('a<', { contains_cursor = true })
local b = Range.from_text_object('a[', { contains_cursor = true })
local c = Range.from_text_object('a(', { contains_cursor = true })
local d = Range.from_text_object('a{', { contains_cursor = true })
return Range.smallest { a, b, c, d }
return Range.smallest {
Range.from_motion('a<', { contains_cursor = true }),
Range.from_motion('a[', { contains_cursor = true }),
Range.from_motion('a(', { contains_cursor = true }),
Range.from_motion('a{', { contains_cursor = true }),
}
end
function Range.find_nearest_quotes()
local a = Range.from_text_object([[a']], { contains_cursor = true })
if a ~= nil and a:is_empty() then a = nil end
local b = Range.from_text_object([[a"]], { contains_cursor = true })
if b ~= nil and b:is_empty() then b = nil end
local c = Range.from_text_object([[a`]], { contains_cursor = true })
if c ~= nil and c:is_empty() then c = nil end
return Range.smallest { a, b, c }
return Range.smallest {
Range.from_motion([[a']], { contains_cursor = true }),
Range.from_motion([[a"]], { contains_cursor = true }),
Range.from_motion([[a`]], { contains_cursor = true }),
}
end
---@param ranges (Range|nil)[]
function Range.smallest(ranges)
---@type Range[]
local new_ranges = {}
for _, r in pairs(ranges) do
if r ~= nil then table.insert(new_ranges, r) end
end
ranges = new_ranges
if #ranges == 0 then return nil end
--------------------------------------------------------------------------------
-- Structural utilities:
--------------------------------------------------------------------------------
-- find smallest match
local max_start = ranges[1].start
local min_stop = ranges[1].stop
local result = ranges[1]
for _, r in ipairs(ranges) do
local start, stop = r.start, r.stop
if start > max_start and stop < min_stop then
max_start = start
min_stop = stop
result = r
end
end
return result
function Range:clone()
return Range.new(self.start:clone(), self.stop ~= nil and self.stop:clone() or nil, self.mode)
end
function Range:clone() return Range.new(self.start:clone(), self.stop ~= nil and self.stop:clone() or nil, self.mode) end
function Range:line_count()
if self:is_empty() then return 0 end
return self.stop.lnum - self.start.lnum + 1
end
function Range:is_empty() return self.stop == nil end
function Range:to_linewise()
local r = self:clone()
r.mode = 'V'
r.start.col = 0
r.start.col = 1
if r.stop ~= nil then r.stop.col = Pos.MAX_COL end
return r
end
function Range:is_empty() return self.stop == nil end
--- @param x u.Pos | u.Range
function Range:contains(x)
if getmetatable(x) == Pos then
return not self:is_empty() and x >= self.start and x <= self.stop
elseif getmetatable(x) == Range then
return self:contains(x.start) and self:contains(x.stop)
end
return false
end
--- @param other u.Range
--- @return u.Range|nil, u.Range|nil
function Range:difference(other)
local outer, inner = self, other
if not outer:contains(inner) then
outer, inner = inner, outer
end
if not outer:contains(inner) then return nil, nil end
local left
if outer.start ~= inner.start then
local stop = inner.start:clone() - 1
left = Range.new(outer.start, stop)
else
left = Range.new(outer.start) -- empty range
end
local right
if inner.stop ~= outer.stop then
local start = inner.stop:clone() + 1
right = Range.new(start, outer.stop)
else
right = Range.new(inner.stop) -- empty range
end
return left, right
end
--- @param left string
--- @param right string
function Range:save_to_pos(left, right)
if self:is_empty() then
self.start:save_to_pos(left)
self.start:save_to_pos(right)
else
self.start:save_to_pos(left)
self.stop:save_to_pos(right)
end
end
--- @param left string
--- @param right string
function Range:save_to_marks(left, right)
if self:is_empty() then
self.start:save_to_mark(left)
self.start:save_to_mark(right)
else
self.start:save_to_mark(left)
self.stop:save_to_mark(right)
end
end
function Range:set_visual_selection()
if self:is_empty() then return end
if vim.api.nvim_get_current_buf() ~= self.start.bufnr then
error 'Range:set_visual_selection() called on a buffer other than the current buffer'
end
local curr_mode = vim.fn.mode()
if curr_mode ~= self.mode then vim.cmd.normal { args = { self.mode }, bang = true } end
self.start:save_to_pos '.'
vim.cmd.normal { args = { 'o' }, bang = true }
self.stop:save_to_pos '.'
end
--------------------------------------------------------------------------------
-- Range.from_* functions:
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- Text access/manipulation utilities:
--------------------------------------------------------------------------------
function Range:length()
if self:is_empty() then return 0 end
local line_positions =
vim.fn.getregionpos(self.start:as_real():as_vim(), self.stop:as_real():as_vim(), { type = 'v' })
local len = 0
for linenr, line in ipairs(line_positions) do
if linenr > 1 then len = len + 1 end -- each newline is counted as a char
local line_start_col = line[1][3]
local line_stop_col = line[2][3]
local line_len = line_stop_col - line_start_col + 1
len = len + line_len
end
return len
end
function Range:line_count()
if self:is_empty() then return 0 end
return self.stop.lnum - self.start.lnum + 1
end
function Range:trim_start()
if self:is_empty() then return end
@@ -298,116 +408,135 @@ function Range:trim_stop()
return r
end
---@param p Pos
function Range:contains(p) return not self:is_empty() and p >= self.start and p <= self.stop end
--- @param i number 1-based
--- @param j? number 1-based
function Range:sub(i, j)
local line_positions =
vim.fn.getregionpos(self.start:as_real():as_vim(), self.stop:as_real():as_vim(), { type = 'v' })
---@return string[]
--- @param idx number 1-based
--- @return u.Pos|nil
local function get_pos(idx)
if idx < 0 then return get_pos(self:length() + idx + 1) end
-- find the position of the first line that contains the i-th character:
local curr_len = 0
for linenr, line in ipairs(line_positions) do
if linenr > 1 then curr_len = curr_len + 1 end -- each newline is counted as a char
local line_start_col = line[1][3]
local line_stop_col = line[2][3]
local line_len = line_stop_col - line_start_col + 1
if curr_len + line_len >= idx then
return Pos.new(self.start.bufnr, line[1][2], line_start_col + (idx - curr_len) - 1)
end
curr_len = curr_len + line_len
end
end
local start = get_pos(i)
if not start then
-- start is inalid, so return an empty range:
return Range.new(self.start, nil, self.mode)
end
local stop
if j then stop = get_pos(j) end
if not stop then
-- stop is inalid, so return an empty range:
return Range.new(start, nil, self.mode)
end
return Range.new(start, stop, 'v')
end
--- @return string[]
function Range:lines()
if self:is_empty() then return {} end
local lines = {}
for i = 0, self.stop.lnum - self.start.lnum do
local line = self:line0(i)
if line ~= nil then table.insert(lines, line.text()) end
end
return lines
return vim.fn.getregion(self.start:as_vim(), self.stop:as_vim(), { type = self.mode })
end
---@return string
--- @return string
function Range:text() return vim.fn.join(self:lines(), '\n') end
---@param i number 1-based
---@param j? number 1-based
function Range:sub(i, j) return self:text():sub(i, j) end
---@param l number
---@return { line: string; idx0: { start: number; stop: number; }; lnum: number; range: fun():Range; text: fun():string }|nil
function Range:line0(l)
if l < 0 then return self:line0(self:line_count() + l) end
--- @param l number
-- luacheck: ignore
--- @return { line: string; idx0: { start: number; stop: number; }; lnum: number; range: fun():u.Range; text: fun():string }|nil
function Range:line(l)
if l < 0 then l = self:line_count() + l + 1 end
if l > self:line_count() then return end
local line = vim.api.nvim_buf_get_lines(self.start.buf, self.start.lnum + l, self.start.lnum + l + 1, false)[1]
if line == nil then return end
local line_indices =
vim.fn.getregionpos(self.start:as_vim(), self.stop:as_vim(), { type = self.mode })
local line_bounds = line_indices[l]
local start = 0
local stop = #line - 1
if l == 0 then start = self.start.col end
if l == self.stop.lnum - self.start.lnum then stop = self.stop.col end
if stop == Pos.MAX_COL then stop = #line - 1 end
local lnum = self.start.lnum + l
return {
line = line,
idx0 = { start = start, stop = stop },
lnum = lnum,
range = function()
return Range.new(
Pos.new(self.start.buf, lnum, start, self.start.off),
Pos.new(self.start.buf, lnum, stop, self.stop.off),
'v'
)
end,
text = function() return line:sub(start + 1, stop + 1) end,
}
local start = Pos.new(unpack(line_bounds[1]))
local stop = Pos.new(unpack(line_bounds[2]))
return Range.new(start, stop)
end
---@param replacement nil|string|string[]
--- @param replacement nil|string|string[]
function Range:replace(replacement)
if replacement == nil then replacement = {} end
if type(replacement) == 'string' then replacement = vim.fn.split(replacement, '\n') end
local buf = self.start.buf
-- convert to start-inclusive, stop-exclusive coordinates:
local start_lnum, stop_lnum = self.start.lnum, (self.stop and self.stop.lnum or self.start.lnum) + 1
local start_col, stop_col = self.start.col, (self.stop and self.stop.col or self.start.col) + 1
local bufnr = self.start.bufnr
local replace_type = (self:is_empty() and 'insert') or (self.mode == 'v' and 'region') or 'lines'
---@param alnum number
---@param acol number
---@param blnum number
---@param bcol number
local function set_text(alnum, acol, blnum, bcol, repl)
-- row indices are end-inclusive, and column indices are end-exclusive.
vim.api.nvim_buf_set_text(buf, alnum, acol, blnum, bcol, repl)
local function update_stop_non_linewise()
local new_last_line_num = self.start.lnum + #replacement - 1
local new_last_col = #(replacement[#replacement] or '')
if new_last_line_num == start_lnum then new_last_col = new_last_col + start_col - 1 end
self.stop = Pos.new(buf, new_last_line_num, new_last_col)
if new_last_line_num == self.start.lnum then
new_last_col = new_last_col + self.start.col - 1
end
self.stop = Pos.new(bufnr, new_last_line_num, new_last_col)
end
---@param alnum number
---@param blnum number
local function set_lines(alnum, blnum, repl)
-- indexing is zero-based, end-exclusive
vim.api.nvim_buf_set_lines(buf, alnum, blnum, false, repl)
if #repl == 0 then
local function update_stop_linewise()
if #replacement == 0 then
self.stop = nil
else
local new_last_line_num = start_lnum + #replacement - 1
self.stop = Pos.new(self.start.buf, new_last_line_num, Pos.MAX_COL, self.stop.off)
local new_last_line_num = self.start.lnum - 1 + #replacement - 1
self.stop = Pos.new(bufnr, new_last_line_num + 1, Pos.MAX_COL, self.stop.off)
end
self.mode = 'v'
end
if replace_type == 'insert' then
set_text(start_lnum, start_col, start_lnum, start_col, replacement)
-- To insert text at a given `(row, column)` location, use `start_row =
-- end_row = row` and `start_col = end_col = col`.
vim.api.nvim_buf_set_text(
bufnr,
self.start.lnum - 1,
self.start.col - 1,
self.start.lnum - 1,
self.start.col - 1,
replacement
)
update_stop_non_linewise()
elseif replace_type == 'region' then
-- Fixup the bounds:
local last_line = vim.api.nvim_buf_get_lines(buf, stop_lnum - 1, stop_lnum, false)[1] or ''
local max_col = #last_line
set_text(start_lnum, start_col, stop_lnum - 1, math.min(stop_col, max_col), replacement)
local max_col = #self.stop:line()
-- Indexing is zero-based. Row indices are end-inclusive, and column indices
-- are end-exclusive.
vim.api.nvim_buf_set_text(
bufnr,
self.start.lnum - 1,
self.start.col - 1,
self.stop.lnum - 1,
math.min(self.stop.col, max_col),
replacement
)
update_stop_non_linewise()
elseif replace_type == 'lines' then
set_lines(start_lnum, stop_lnum, replacement)
-- Indexing is zero-based, end-exclusive.
vim.api.nvim_buf_set_lines(bufnr, self.start.lnum - 1, self.stop.lnum, true, replacement)
update_stop_linewise()
else
error 'unreachable'
end
end
---@param amount number
--- @param amount number
function Range:shrink(amount)
local start = self.start
local stop = self.stop
@@ -425,61 +554,17 @@ function Range:shrink(amount)
return Range.new(start, stop, self.mode)
end
---@param amount number
--- @param amount number
function Range:must_shrink(amount)
local shrunk = self:shrink(amount)
if shrunk == nil or shrunk:is_empty() then error 'error in Range:must_shrink: Range:shrink() returned nil' end
if shrunk == nil or shrunk:is_empty() then
error 'error in Range:must_shrink: Range:shrink() returned nil'
end
return shrunk
end
---@param left string
---@param right string
function Range:save_to_pos(left, right)
if self:is_empty() then
self.start:save_to_pos(left)
self.start:save_to_pos(right)
else
self.start:save_to_pos(left)
self.stop:save_to_pos(right)
end
end
---@param left string
---@param right string
function Range:save_to_marks(left, right)
if self:is_empty() then
self.start:save_to_mark(left)
self.start:save_to_mark(right)
else
self.start:save_to_mark(left)
self.stop:save_to_mark(right)
end
end
function Range:set_visual_selection()
if self:is_empty() then return end
if vim.api.nvim_get_current_buf() ~= self.start.buf then vim.api.nvim_set_current_buf(self.start.buf) end
State.run(self.start.buf, function(s)
s:track_mark 'a'
s:track_mark 'b'
self.start:save_to_mark 'a'
self.stop:save_to_mark 'b'
local mode = self.mode
local normal_cmd_args = ''
if vim.api.nvim_get_mode().mode == 'n' then normal_cmd_args = normal_cmd_args .. mode end
normal_cmd_args = normal_cmd_args .. '`ao`b'
vim.cmd { cmd = 'normal', args = { normal_cmd_args }, bang = true }
return nil
end)
end
---@param group string
---@param opts? { timeout?: number, priority?: number, on_macro?: boolean }
--- @param group string
--- @param opts? { timeout?: number, priority?: number, on_macro?: boolean }
function Range:highlight(group, opts)
if self:is_empty() then return end
@@ -490,33 +575,31 @@ function Range:highlight(group, opts)
if not opts.on_macro and in_macro then return { clear = function() end } end
local ns = vim.api.nvim_create_namespace ''
State.run(self.start.buf, function(s)
if not in_macro then s:track_winview() end
vim.highlight.range(
self.start.buf,
ns,
group,
{ self.start.lnum, self.start.col },
{ self.stop.lnum, self.stop.col },
{
inclusive = true,
priority = opts.priority,
regtype = self.mode,
}
)
return nil
end)
local winview = vim.fn.winsaveview()
vim.hl.range(
self.start.bufnr,
ns,
group,
{ self.start.lnum - 1, self.start.col - 1 },
{ self.stop.lnum - 1, self.stop.col - 1 },
{
inclusive = true,
priority = opts.priority,
timeout = opts.timeout,
regtype = self.mode,
}
)
if not in_macro then vim.fn.winrestview(winview) end
vim.cmd.redraw()
local function clear()
vim.api.nvim_buf_clear_namespace(self.start.buf, ns, self.start.lnum, self.stop.lnum + 1)
vim.cmd.redraw()
end
if opts.timeout ~= nil then vim.defer_fn(clear, opts.timeout) end
return { ns = ns, clear = clear }
return {
ns = ns,
clear = function()
vim.api.nvim_buf_clear_namespace(self.start.bufnr, ns, self.start.lnum - 1, self.stop.lnum)
vim.cmd.redraw()
end,
}
end
return Range

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

@@ -0,0 +1,570 @@
local M = {}
local H = {}
--- @alias u.renderer.Tag { kind: 'tag'; name: string, attributes: table<string, unknown>, children: u.renderer.Tree }
--- @alias u.renderer.Node nil | boolean | string | u.renderer.Tag
--- @alias u.renderer.Tree u.renderer.Node | u.renderer.Node[]
-- luacheck: ignore
--- @type table<string, fun(attributes: table<string, any>, children: u.renderer.Tree): u.renderer.Tag> & fun(name: string, attributes: table<string, any>, children: u.renderer.Tree): u.renderer.Tag>
M.h = setmetatable({}, {
__call = function(_, name, attributes, children)
return {
kind = 'tag',
name = name,
attributes = attributes or {},
children = children,
}
end,
__index = function(_, name)
-- vim.print('dynamic hl ' .. name)
return function(attributes, children)
return M.h('text', vim.tbl_deep_extend('force', { hl = name }, attributes), children)
end
end,
})
-- Renderer {{{
--- @alias RendererExtmark { id?: number; start: [number, number]; stop: [number, number]; opts: any; tag: any }
--- @class u.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
--- @private
--- @param x any
--- @return boolean
function Renderer.is_tag(x) return type(x) == 'table' and x.kind == 'tag' end
--- @private
--- @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: u.renderer.Tree;
--- on_tag?: fun(tag: u.renderer.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 u.renderer.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 --[[@as u.renderer.Node[] ]])
do
-- newlines are not controlled by array entries, do NOT output a line here:
visit(child)
end
else -- luacheck: ignore
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: u.renderer.Tag): string;
--- }
function Renderer.markup_to_string(opts) return table.concat(Renderer.markup_to_lines(opts), '\n') end
--- @param bufnr number
--- @param old_lines string[] | nil
--- @param new_lines string[]
function Renderer.patch_lines(bufnr, old_lines, new_lines)
--
-- Helpers:
--
--- @param start integer
--- @param end_ integer
--- @param strict_indexing boolean
--- @param replacement string[]
local function _set_lines(start, end_, strict_indexing, replacement)
vim.api.nvim_buf_set_lines(bufnr, start, end_, strict_indexing, replacement)
end
--- @param start_row integer
--- @param start_col integer
--- @param end_row integer
--- @param end_col integer
--- @param replacement string[]
local function _set_text(start_row, start_col, end_row, end_col, replacement)
vim.api.nvim_buf_set_text(bufnr, start_row, start_col, end_row, end_col, replacement)
end
-- Morph the text to the desired state:
local line_changes =
H.levenshtein(old_lines or vim.api.nvim_buf_get_lines(bufnr, 0, -1, false), new_lines)
for _, line_change in ipairs(line_changes) do
local lnum0 = line_change.index - 1
if line_change.kind == 'add' then
_set_lines(lnum0, lnum0, true, { line_change.item })
elseif line_change.kind == 'change' then
-- Compute inter-line diff, and apply:
local col_changes =
H.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
if col_change.kind == 'add' then
_set_text(lnum0, cnum0, lnum0, cnum0, { col_change.item })
elseif col_change.kind == 'change' then
_set_text(lnum0, cnum0, lnum0, cnum0 + 1, { col_change.to })
elseif col_change.kind == 'delete' then
_set_text(lnum0, cnum0, lnum0, cnum0 + 1, {})
else -- luacheck: ignore
-- No change
end
end
elseif line_change.kind == 'delete' then
_set_lines(lnum0, lnum0 + 1, true, {})
else -- luacheck: ignore
-- No change
end
end
end
--- @param tree u.renderer.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
-- Set any necessary keymaps:
for _, mode in ipairs { 'i', 'n', 'v', 'x', 'o' } do
for lhs, _ in pairs(tag.attributes[mode .. 'map'] or {}) do
-- Force creating an extmark if there are key handlers. To accurately
-- sense the bounds of the text, we need an extmark:
extmark = extmark or {}
vim.keymap.set(
'n',
lhs,
function() return self:_expr_map_callback('n', lhs) end,
{ buffer = self.bufnr, expr = true, replace_keycodes = true }
)
end
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 start integer
--- @param end_ integer
--- @param strict_indexing boolean
--- @param replacement string[]
function Renderer:_set_lines(start, end_, strict_indexing, replacement)
vim.api.nvim_buf_set_lines(self.bufnr, start, end_, strict_indexing, replacement)
end
--- @private
--- @param start_row integer
--- @param start_col integer
--- @param end_row integer
--- @param end_col integer
--- @param replacement string[]
function Renderer:_set_text(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)
end
--- @private
function Renderer:_reconcile() -- {{{
--
-- Step 1: morph the text to the desired state:
--
Renderer.patch_lines(self.bufnr, self.old.lines, self.curr.lines)
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
self.old = self.curr
end -- }}}
--- @private
--- @param mode string
--- @param lhs string
function Renderer:_expr_map_callback(mode, lhs) -- {{{
-- 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)
if #pos_infos == 0 then return lhs end
-- Find the first tag that is listening for this event:
local cancel = false
for _, pos_info in ipairs(pos_infos) do
local tag = pos_info.tag
-- is the tag listening?
local f = vim.tbl_get(tag.attributes, mode .. 'map', lhs)
if type(f) == 'function' then
local result = f()
if result == '' then
-- bubble-up to the next tag, but set cancel to true, in case there are
-- no more tags to bubble up to:
cancel = true
else
return result
end
end
end
-- Resort to default behavior:
return cancel and '' or lhs
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: u.renderer.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: u.renderer.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 u.TreeBuilder
--- @field private nodes u.renderer.Node[]
local TreeBuilder = {}
TreeBuilder.__index = TreeBuilder
M.TreeBuilder = TreeBuilder
function TreeBuilder.new()
local self = setmetatable({ nodes = {} }, TreeBuilder)
return self
end
--- @param nodes u.renderer.Tree
--- @return u.TreeBuilder
function TreeBuilder:put(nodes)
table.insert(self.nodes, nodes)
return self
end
--- @param name string
--- @param attributes? table<string, any>
--- @param children? u.renderer.Node | u.renderer.Node[]
--- @return u.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 u.TreeBuilder
function TreeBuilder:nest(fn)
local nested_writer = TreeBuilder.new()
fn(nested_writer)
table.insert(self.nodes, nested_writer.nodes)
return self
end
--- @return u.renderer.Tree
function TreeBuilder:tree() return self.nodes end
-- }}}
-- Levenshtein utility {{{
-- luacheck: ignore
--- @alias LevenshteinChange<T> ({ kind: 'add'; item: T; index: number; } | { kind: 'delete'; item: T; index: number; } | { kind: 'change'; from: T; to: T; index: number; })
--- @private
--- @generic T
--- @param x `T`[]
--- @param y T[]
--- @param cost? { of_delete?: fun(x: T): number; of_add?: fun(x: T): number; of_change?: fun(x: T, y: T): number; }
--- @return LevenshteinChange<T>[] The changes, from last (greatest index) to first (smallest index).
function H.levenshtein(x, y, cost)
-- At the moment, this whole `cost` plumbing is not used. Deletes have the
-- same cost as Adds or Changes. I can imagine a future, however, where
-- fudging with the costs of operations produces a more optimized change-set
-- that is tailored to working better with how NeoVim manipulates text. I've
-- done no further investigation in this area, however, so it's impossible to
-- tell if such tuning would produce real benefit. For now, I'm leaving this
-- in here even though it's not actively used. Hopefully having this
-- callback-based plumbing does not cause too much of a performance hit to
-- the renderer.
cost = cost or {}
local cost_of_delete_f = cost.of_delete or function() return 1 end
local cost_of_add_f = cost.of_add or function() return 1 end
local cost_of_change_f = cost.of_change or function() return 1 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
-- Fill the base cases
for i = 0, m do
dp[i][0] = i
end
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 cost_delete = dp[i - 1][j] + cost_of_delete_f(x[i])
local cost_add = dp[i][j - 1] + cost_of_add_f(y[j])
local cost_change = dp[i - 1][j - 1] + cost_of_change_f(x[i], y[j])
dp[i][j] = math.min(cost_delete, cost_add, cost_change)
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
-- }}}
return M

View File

@@ -1,61 +1,39 @@
local M = {}
local function _normal(cmd) vim.cmd { cmd = 'normal', args = { cmd }, bang = true } end
local IS_REPEATING = false
--- @type function
local REPEAT_ACTION = nil
M.native_repeat = function() _normal '.' end
M.native_undo = function() _normal 'u' end
local function is_repeatable_last_mutator() return vim.b.changedtick <= (vim.b.my_changedtick or 0) end
local function update_ts() vim.b.tt_changedtick = vim.b.changedtick end
---@param cmd? string|fun():unknown
function M.set(cmd)
update_ts()
if cmd ~= nil then vim.b.tt_repeatcmd = cmd end
--- @param f fun()
function M.run_repeatable(f)
REPEAT_ACTION = f
REPEAT_ACTION()
vim.b.my_changedtick = vim.b.changedtick
end
local function tt_was_last_repeatable()
local ts, tt_ts = vim.b.changedtick, vim.b.tt_changedtick
return tt_ts ~= nil and ts <= tt_ts
end
---@generic T
---@param cmd string|fun():T
---@return T
function M.run(cmd)
M.set(cmd)
local result = cmd()
update_ts()
return result
end
function M.do_repeat()
local tt_cmd = vim.b.tt_repeatcmd
if not tt_was_last_repeatable() or (type(tt_cmd) ~= 'function' and type(tt_cmd) ~= 'string') then
return M.native_repeat()
end
-- execute the cached command:
local count = vim.api.nvim_get_vvar 'count1'
if type(tt_cmd) == 'string' then
_normal(count .. tt_cmd --[[@as string]])
else
local last_return
for _ = 1, count do
last_return = M.run(tt_cmd --[[@as fun():any]])
end
return last_return
end
end
function M.undo()
local tt_was_last_repeatable_before_undo = tt_was_last_repeatable()
M.native_undo()
if tt_was_last_repeatable_before_undo then update_ts() end
end
function M.is_repeating() return IS_REPEATING end
function M.setup()
vim.keymap.set('n', '.', M.do_repeat)
vim.keymap.set('n', 'u', M.undo)
vim.keymap.set('n', '.', function()
IS_REPEATING = true
for _ = 1, vim.v.count1 do
if is_repeatable_last_mutator() and type(REPEAT_ACTION) == 'function' then
M.run_repeatable(REPEAT_ACTION)
else
vim.cmd { cmd = 'normal', args = { '.' }, bang = true }
end
end
IS_REPEATING = false
end)
vim.keymap.set('n', 'u', function()
local was_repeatable_last_mutator = is_repeatable_last_mutator()
for _ = 1, vim.v.count1 do
vim.cmd { cmd = 'normal', args = { 'u' }, bang = true }
end
if was_repeatable_last_mutator then vim.b.my_changedtick = vim.b.changedtick end
end)
end
return M

View File

@@ -1,90 +0,0 @@
---@class State
---@field buf number
---@field registers table
---@field marks table
---@field positions table
---@field keymaps { mode: string; lhs: any, rhs: any, buffer?: number }[]
---@field global_options table<string, any>
---@field win_view vim.fn.winsaveview.ret|nil
local State = {}
---@param buf number
---@return State
function State.new(buf)
if buf == 0 then buf = vim.api.nvim_get_current_buf() end
local s = { buf = buf, registers = {}, marks = {}, positions = {}, keymaps = {}, global_options = {} }
setmetatable(s, { __index = State })
return s
end
---@generic T
---@param buf number
---@param f fun(s: State):T
---@return T
function State.run(buf, f)
local s = State.new(buf)
local ok, result = pcall(f, s)
s:restore()
if not ok then error(result) end
return result
end
---@param buf number
---@param f fun(s: State, callback: fun(): any):any
---@param callback fun():any
function State.run_async(buf, f, callback)
local s = State.new(buf)
f(s, function()
s:restore()
callback()
end)
end
function State:track_keymap(mode, lhs)
local old =
-- Look up the mapping in buffer-local maps:
vim.iter(vim.api.nvim_buf_get_keymap(self.buf, mode)):find(function(map) return map.lhs == lhs end)
-- Look up the mapping in global maps:
or vim.iter(vim.api.nvim_get_keymap(mode)):find(function(map) return map.lhs == lhs end)
-- Did we find a mapping?
if old == nil then return end
-- Track it:
table.insert(self.keymaps, { mode = mode, lhs = lhs, rhs = old.rhs or old.callback, buffer = old.buffer })
end
---@param reg string
function State:track_register(reg) self.registers[reg] = vim.fn.getreg(reg) end
---@param mark string
function State:track_mark(mark) self.marks[mark] = vim.api.nvim_buf_get_mark(self.buf, mark) end
---@param pos string
function State:track_pos(pos) self.positions[pos] = vim.fn.getpos(pos) end
---@param nm string
function State:track_global_option(nm) self.global_options[nm] = vim.go[nm] end
function State:track_winview() self.win_view = vim.fn.winsaveview() end
function State:restore()
for reg, val in pairs(self.registers) do
vim.fn.setreg(reg, val)
end
for mark, val in pairs(self.marks) do
vim.api.nvim_buf_set_mark(self.buf, mark, val[1], val[2], {})
end
for pos, val in pairs(self.positions) do
vim.fn.setpos(pos, val)
end
for _, map in ipairs(self.keymaps) do
vim.keymap.set(map.mode, map.lhs, map.rhs, { buffer = map.buffer })
end
for nm, val in pairs(self.global_options) do
vim.go[nm] = val
end
if self.win_view ~= nil then vim.fn.winrestview(self.win_view) end
end
return State

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

@@ -0,0 +1,307 @@
local M = {}
M.debug = false
--------------------------------------------------------------------------------
-- class Signal
--------------------------------------------------------------------------------
--- @class u.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 u.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
function Signal:schedule_set(value)
vim.schedule(function() self:set(value) 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
--- @param fn function
function Signal:schedule_update(fn) self:schedule_set(fn(self.value)) end
--- @generic U
--- @param fn fun(value: T): U
--- @return u.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 u.Signal
function Signal:clone()
return self:map(function(x) return x end)
end
--- @param fn fun(value: T): boolean
--- @return u.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 u.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)
--- @diagnostic disable-next-line: undefined-doc-name
--- @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()
--- @diagnostic disable-next-line: undefined-field
state.timer:stop()
--- @diagnostic disable-next-line: undefined-field
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
--------------------------------------------------------------------------------
local CURRENT_CONTEXT = nil
--- @class u.ExecutionContext
--- @field signals table<u.Signal, boolean>
local ExecutionContext = {}
M.ExecutionContext = ExecutionContext
ExecutionContext.__index = ExecutionContext
--- @return u.ExecutionContext
function ExecutionContext.new()
return setmetatable({
signals = {},
subscribers = {},
}, ExecutionContext)
end
function ExecutionContext.current() return CURRENT_CONTEXT end
--- @param fn function
--- @param ctx u.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 u.Signal
function M.create_signal(value, name) return Signal:new(value, name) end
--- @param fn function
--- @param name? string
--- @return u.Signal
function M.create_memo(fn, name)
--- @type u.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

45
lua/u/txtobj.lua Normal file
View File

@@ -0,0 +1,45 @@
local Range = require 'u.range'
local M = {}
local ESC = vim.api.nvim_replace_termcodes('<Esc>', true, false, true)
--- @param key_seq string
--- @param fn fun(key_seq: string):u.Range|nil
--- @param opts? { buffer: number|nil }
function M.define(key_seq, fn, opts)
if opts ~= nil and opts.buffer == 0 then opts.buffer = vim.api.nvim_get_current_buf() end
local function handle_visual()
local range = fn(key_seq)
if range == nil or range:is_empty() then
vim.cmd.normal(ESC)
return
end
range:set_visual_selection()
end
vim.keymap.set({ 'x' }, key_seq, handle_visual, opts and { buffer = opts.buffer } or nil)
local function handle_normal()
local range = fn(key_seq)
if range == nil then return end
if not range:is_empty() then
range:set_visual_selection()
else
local original_eventignore = vim.go.eventignore
vim.go.eventignore = 'all'
-- insert a single space, so we can select it:
local p = range.start
p:insert_before ' '
vim.go.eventignore = original_eventignore
-- select the space:
Range.new(p, p, 'v'):set_visual_selection()
end
end
vim.keymap.set({ 'o' }, key_seq, handle_normal, opts and { buffer = opts.buffer } or nil)
end
return M

View File

@@ -4,9 +4,22 @@ local M = {}
-- Types
--
---@alias QfItem { col: number, filename: string, kind: string, lnum: number, text: 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 QfItem { col: number, filename: string, kind: string, lnum: number, text: string }
--- @alias KeyMaps table<string, fun(): any | string> }
-- luacheck: ignore
--- @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: u.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
--- and attaches it to the arguments.
@@ -20,9 +33,10 @@ local M = {}
--- vim.print(args.info:lines())
--- end, { nargs = '*', range = true })
--- ```
---@param name string
---@param cmd string | fun(args: CmdArgs): any
---@param opts? { nargs?: 0|1|'*'|'?'|'+'; range?: boolean|'%'|number; count?: boolean|number, addr?: string; completion?: string }
--- @param name string
--- @param cmd string | fun(args: CmdArgs): any
-- luacheck: ignore
--- @param opts? { nargs?: 0|1|'*'|'?'|'+'; range?: boolean|'%'|number; count?: boolean|number, addr?: string; completion?: string }
function M.ucmd(name, cmd, opts)
local Range = require 'u.range'
@@ -37,98 +51,6 @@ function M.ucmd(name, cmd, opts)
vim.api.nvim_create_user_command(name, cmd2, opts or {})
end
---@param key_seq string
---@param fn fun(key_seq: string):Range|Pos|nil
---@param opts? { buffer: number|nil }
function M.define_text_object(key_seq, fn, opts)
local Range = require 'u.range'
local Pos = require 'u.pos'
if opts ~= nil and opts.buffer == 0 then opts.buffer = vim.api.nvim_get_current_buf() end
local function handle_visual()
local range_or_pos = fn(key_seq)
if range_or_pos == nil then return end
if Range.is(range_or_pos) and range_or_pos:is_empty() then range_or_pos = range_or_pos.start end
if Range.is(range_or_pos) then
local range = range_or_pos --[[@as Range]]
range:set_visual_selection()
else
vim.cmd { cmd = 'normal', args = { '<Esc>' }, bang = true }
end
end
vim.keymap.set({ 'x' }, key_seq, handle_visual, opts and { buffer = opts.buffer } or nil)
local function handle_normal()
local State = require 'u.state'
-- enter visual mode:
vim.cmd { cmd = 'normal', args = { 'v' }, bang = true }
local range_or_pos = fn(key_seq)
if range_or_pos == nil then return end
if Range.is(range_or_pos) and range_or_pos:is_empty() then range_or_pos = range_or_pos.start end
if Range.is(range_or_pos) then
range_or_pos:set_visual_selection()
elseif Pos.is(range_or_pos) then
local p = range_or_pos --[[@as Pos]]
State.run(0, function(s)
s:track_global_option 'eventignore'
vim.go.eventignore = 'all'
-- insert a single space, so we can select it:
vim.api.nvim_buf_set_text(0, p.lnum, p.col, p.lnum, p.col, { ' ' })
-- select the space:
Range.new(p, p, 'v'):set_visual_selection()
end)
end
end
vim.keymap.set({ 'o' }, key_seq, handle_normal, opts and { buffer = opts.buffer } or nil)
end
---@type fun(): nil|(fun():any)
local __U__RepeatableOpFunc_rhs = nil
--- This is the global utility function used for operatorfunc
--- in repeatablemap
---@type nil|fun(range: Range): fun():any|nil
-- selene: allow(unused_variable)
function __U__RepeatableOpFunc()
if __U__RepeatableOpFunc_rhs ~= nil then __U__RepeatableOpFunc_rhs() end
end
function M.repeatablemap(mode, lhs, rhs, opts)
vim.keymap.set(mode, lhs, function()
__U__RepeatableOpFunc_rhs = rhs
vim.o.operatorfunc = 'v:lua.__U__RepeatableOpFunc'
return 'g@ '
end, vim.tbl_extend('force', opts or {}, { expr = true }))
end
function M.get_editor_dimensions()
local w = 0
local h = 0
local tabnr = vim.api.nvim_get_current_tabpage()
for _, winid in ipairs(vim.api.nvim_list_wins()) do
local tabpage = vim.api.nvim_win_get_tabpage(winid)
if tabpage == tabnr then
local pos = vim.api.nvim_win_get_position(winid)
local r, c = pos[1], pos[2]
local win_w = vim.api.nvim_win_get_width(winid)
local win_h = vim.api.nvim_win_get_height(winid)
local right = c + win_w
local bottom = r + win_h
if right > w then w = right end
if bottom > h then h = bottom end
end
end
if w == 0 or h == 0 then
w = vim.api.nvim_win_get_width(0)
h = vim.api.nvim_win_get_height(0)
end
return { width = w, height = h }
end
function M.get_editor_dimensions() return { width = vim.go.columns, height = vim.go.lines } end
return M