8000 mini.nvim/lua/mini/starter.lua at main · mosegontar/mini.nvim · GitHub
[go: up one dir, main page]

Skip to content

Latest commit

 

History

History
1439 lines (1270 loc) · 48.8 KB

starter.lua

File metadata and controls

1439 lines (1270 loc) · 48.8 KB
-- Add top padding
local top_lines = {}
for _ = 1, top do
table.insert(top_lines, { H.content_unit('', 'empty', nil) })
end
content = vim.list_extend(top_lines, content)
return content
end
end
--- Hook generator for adding bullet to items
---
--- Output is a content hook which adds supplied string to be displayed to the
--- left of item.
---
---@param bullet string String to be placed to the left of item name.
--- Default: "░ ".
---@param place_cursor boolean Whether to place cursor on the first character
--- of bullet when corresponding item becomes current. Default: true.
---
---@return function Content hook.
function MiniStarter.gen_hook.adding_bullet(bullet, place_cursor)
bullet = bullet or '░ '
place_cursor = place_cursor == nil and true or place_cursor
return function(content)
local coords = MiniStarter.content_coords(content, 'item')
-- Go backwards to avoid conflict when inserting units
for i = #coords, 1, -1 do
local l_num, u_num = coords[i].line, coords[i].unit
local bullet_unit = {
string = bullet,
type = 'item_bullet',
hl = 'MiniStarterItemBullet',
-- Use `_item` instead of `item` because it is better to be 'private'
_item = content[l_num][u_num].item,
_place_cursor = place_cursor,
}
table.insert(content[l_num], u_num, bullet_unit)
end
return content
end
end
--- Hook generator for indexing items
---
--- Output is a content hook which adds unique index to the start of item's
--- name. It results into shortening queries required to choose an item (at
--- expense of clarity).
---
---@param grouping string One of "all" (number indexing across all sections) or
--- "section" (letter-number indexing within each section). Default: "all".
---@param exclude_sections table Array of section names (values of `section`
--- element of item) for which index won't be added. Default: `{}`.
---
---@return function Content hook.
function MiniStarter.gen_hook.indexing(grouping, exclude_sections)
grouping = grouping or 'all'
exclude_sections = exclude_sections or {}
local per_section = grouping == 'section'
return function(content)
local cur_section, n_section, n_item = nil, 0, 0
local coords = MiniStarter.content_coords(content, 'item')
for _, c in ipairs(coords) do
local unit = content[c.line][c.unit]
local item = unit.item
if not vim.tbl_contains(exclude_sections, item.section) then
n_item = n_item + 1
if cur_section ~= item.section then
cur_section = item.section
-- Cycle through lower case letters
n_section = math.fmod(n_section, 26) + 1
n_item = per_section and 1 or n_item
end
local section_index = per_section and string.char(96 + n_section) or ''
unit.string = ('%s%s. %s'):format(section_index, n_item, unit.string)
end
end
return content
end
end
--- Hook generator for aligning content
---
--- Output is a content hook which independently aligns content horizontally
--- and vertically. Basically, this computes left and top pads for
--- |MiniStarter.gen_hook.padding| such that output lines would appear aligned
--- in certain way.
---
---@param horizontal string One of "left", "center", "right". Default: "left".
---@param vertical string One of "top", "center", "bottom". Default: "top".
---
---@return function Content hook.
function MiniStarter.gen_hook.aligning(horizontal, vertical)
horizontal = horizontal == nil and 'left' or horizontal
vertical = vertical == nil and 'top' or vertical
local horiz_coef = ({ left = 0, center = 0.5, right = 1.0 })[horizontal]
local vert_coef = ({ top = 0, center = 0.5, bottom = 1.0 })[vertical]
return function(content)
local line_strings = MiniStarter.content_to_lines(content)
-- Align horizontally
-- Don't use `string.len()` to account for multibyte characters
local lines_width = vim.tbl_map(function(l)
return vim.fn.strdisplaywidth(l)
end, line_strings)
local min_right_space = vim.api.nvim_win_get_width(0) - math.max(unpack(lines_width))
local left_pad = math.max(math.floor(horiz_coef * min_right_space), 0)
-- Align vertically
local bottom_space = vim.api.nvim_win_get_height(0) - #line_strings
local top_pad = math.max(math.floor(vert_coef * bottom_space), 0)
return MiniStarter.gen_hook.padding(left_pad, top_pad)(content)
end
end
-- Work with content ----------------------------------------------------------
--- Helper to iterate through content
---
--- Basically, this traverses content "2d array" (in depth-first fashion; top
--- to bottom, left to right) and returns "coordinates" of units for which
--- `predicate` is true-ish.
---
---@param content table Content "2d array".
---@param predicate function|string|nil Predictate to filter units. If it is:
--- - Function, then it is evaluated with unit as input.
--- - String, then it checks unit to have this type (allows easy getting of
--- units with some type).
--- - `nil`, all units are kept.
---
---@return table Array of resulting units' coordinates. Each coordinate is a
--- table with <line> and <unit> keys. To retrieve actual unit from coordinate
--- `c`, use `content[c.line][c.unit]`.
function MiniStarter.content_coords(content, predicate)
content = content or MiniStarter.content
if predicate == nil then
predicate = function(unit)
return true
end
end
if type(predicate) == 'string' then
local pred_type = predicate
predicate = function(unit)
return unit.type == pred_type
end
end
local res = {}
for l_num, line in ipairs(content) do
for u_num, unit in ipairs(line) do
if predicate(unit) then
table.insert(res, { line = l_num, unit = u_num })
end
end
end
return res
end
-- stylua: ignore start
--- Convert content to buffer lines
---
--- One buffer line is made by concatenating `string` element of units within
--- same content line.
---
---@param content table Content "2d array".
---
---@return table Array of strings for each buffer line.
function MiniStarter.content_to_lines(content)
return vim.tbl_map(
function(content_line)
return table.concat(
-- Ensure that each content line is indeed a single buffer line
vim.tbl_map(function(x) return x.string:gsub('\n', ' ') end, content_line), ''
)
end,
content or MiniStarter.content
)
end
-- stylua: ignore end
--- Convert content to items
---
--- Parse content (in depth-first fashion) and retrieve each item from `item`
--- element of content units with type "item". This also:
--- - Computes some helper information about how item will be actually
--- displayed (after |MiniStarter.content_to_lines|) and minimum number of
--- prefix characters needed for a particular item to be queried single.
--- - Modifies item's `name` element taking it from corresponing `string`
--- element of content unit. This allows modifying item's `name` at the stage
--- of content hooks (like, for example, in |MiniStarter.gen_hook.indexing|).
---
---@param content table Content "2d array".
---
---@return table Array of items.
function MiniStarter.content_to_items(content)
content = content or MiniStarter.content
-- NOTE: this havily utilizes 'modify by reference' nature of Lua tables
local items = {}
for l_num, line in ipairs(content) do
-- Track 0-based starting column of current unit (using byte length)
local start_col = 0
for _, unit in ipairs(line) do
-- Cursor position is (1, 0)-based
local cursorpos = { l_num, start_col }
if unit.type == 'item' then
local item = unit.item
-- Take item's name from content string
item.name = unit.string:gsub('\n', ' ')
item._line = l_num - 1
item._start_col = start_col
item._end_col = start_col + unit.string:len()
-- Don't overwrite possible cursor position from item's bullet
item._cursorpos = item._cursorpos or cursorpos
table.insert(items, item)
end
-- Prefer placing cursor at start of item's bullet
if unit.type == 'item_bullet' and unit._place_cursor then
-- Item bullet uses 'private' `_item` element instead of `item`
unit._item._cursorpos = cursorpos
end
start_col = start_col + unit.string:len()
end
end
-- Compute length of unique prefix for every item's name (ignoring case)
local strings = vim.tbl_map(function(x)
return x.name:lower()
end, items)
local nprefix = H.unique_nprefix(strings)
for i, n in ipairs(nprefix) do
items[i]._nprefix = n
end
return items
end
-- Other exported functions ---------------------------------------------------
--- Evaluate current item
function MiniStarter.eval_current_item()
H.eval_fun_or_string(H.items[H.current_item_id].action, true)
end
--- Update current item
---
--- This makes next (with respect to `direction`) active item to be current.
---
---@param direction string One of "next" or "previous".
function MiniStarter.update_current_item(direction)
-- Advance current item B40F
local prev_current = H.current_item_id
H.current_item_id = H.next_active_item_id(H.current_item_id, direction)
if H.current_item_id == prev_current then
return
end
-- Update cursor position
H.position_cursor_on_current_item()
-- Highlight current item
vim.api.nvim_buf_clear_namespace(H.buf_id, H.ns.current_item, 0, -1)
H.add_hl_current_item()
end
--- Add character to current query
---
--- - Update current query by appending `char` to its end (only if it results
--- into at least one active item) or delete latest character if `char` is `nil`.
--- - Recompute status of items: "active" if its name starts with new query,
--- "inactive" otherwise.
--- - Update highlighting: whole strings for "inactive" items, current query
--- for "active" items.
---
---@param char string Single character to be added to query. If `nil`, deletes
--- latest character from query.
function MiniStarter.add_to_query(char)
local new_query
if char == nil then
new_query = H.query:sub(0, H.query:len() - 1)
else
new_query = ('%s%s'):format(H.query, char)
end
H.make_query(new_query)
end
--- Set current query
---
---@param query string|nil Query to be set (only if it results into at least one
--- active item). Default: `nil` for setting query to empty string, which
--- essentially resets query.
function MiniStarter.set_query(query)
query = query or ''
if type(query) ~= 'string' then
error('`query` should be either `nil` or string.')
end
H.make_query(query)
end
--- Act on |CursorMoved| by repositioning cursor in fixed place.
function MiniStarter.on_cursormoved()
H.position_cursor_on_current_item()
end
-- Helper data ================================================================
-- Module default config
H.default_config = MiniStarter.config
-- Default config values
H.default_items = {
function()
if _G.MiniSessions == nil then
return {}
end
return MiniStarter.sections.sessions(5, true)()
end,
MiniStarter.sections.recent_files(5, false, false),
MiniStarter.sections.builtin_actions(),
}
H.default_header = function()
local hour = tonumber(vim.fn.strftime('%H'))
-- [04:00, 12:00) - morning, [12:00, 20:00) - day, [20:00, 04:00) - evening
local part_id = math.floor((hour + 4) / 8) + 1
local day_part = ({ 'evening', 'morning', 'afternoon', 'evening' })[part_id]
local username = vim.loop.os_get_passwd()['username'] or 'USERNAME'
return ('Good %s, %s'):format(day_part, username)
end
H.default_footer = [[
Type query to filter items
<BS> deletes latest character from query
<Esc> resets current query
<Down>/<Up> and <M-j>/<M-k> move current item
<CR> executes action of current item
<C-c> closes this buffer]]
H.default_content_hooks = { MiniStarter.gen_hook.adding_bullet(), MiniStarter.gen_hook.aligning('center', 'center') }
-- Normalized values from config
H.items = {} -- items gathered with `MiniStarter.content_to_items` from final content
H.header = {} -- table of strings
H.footer = {} -- table of strings
-- Identifier of current item
H.current_item_id = nil
-- Buffer identifier where everything is displayed
H.buf_id = nil
-- Namespaces for highlighting
H.ns = {
activity = vim.api.nvim_create_namespace(''),
current_item = vim.api.nvim_create_namespace(''),
general = vim.api.nvim_create_namespace(''),
}
-- Current search query
H.query = ''
-- Helper functionality =======================================================
-- Settings -------------------------------------------------------------------
function H.setup_config(config)
-- General idea: if some table elements are not present in user-supplied
-- `config`, take them from default config
vim.validate({ config = { config, 'table', true } })
config = vim.tbl_deep_extend('force', H.default_config, config or {})
vim.validate({
autoopen = { config.autoopen, 'boolean' },
evaluate_single = { config.evaluate_single, 'boolean' },
items = { config.items, 'table', true },
-- `header` and `footer` can have any type
content_hooks = { config.content_hooks, 'table', true },
query_updaters = { config.query_updaters, 'string' },
})
return config
end
function H.apply_config(config)
MiniStarter.config = config
0