how to custom textobject? #1738
-
Contributing guidelines
Module(s)mini.ai Questionhow to add custom textobject for the below text block? |
Beta Was this translation helpful? Give feedback.
Answered by
echasnovski
Apr 10, 2025
Replies: 1 comment
-
|
I think the most straightforward and robust way here would be to use function that returns array of regions. So something like this: local custom_block = function(ai_type, _, _)
local lines = vim.api.nvim_buf_get_lines(0, 0, -1, false)
local title_start_lines, res = {}, {}
local process_line = function(i, l)
-- If line is for "begin", document it and move on until its "end" part
local start_title = l:match('^=begin (.*)$')
if start_title ~= nil then
title_start_lines[start_title] = i
return
end
-- Use only "end" lines that have same title as some previous "begin"
local end_title = l:match('^=end (.*)$')
if end_title == nil or title_start_lines[end_title] == nil then return end
-- Ignore "begin" and "end" lines for `i` textobject
local from_line = title_start_lines[end_title] + (ai_type == 'i' and 1 or 0)
local to_line = i - (ai_type == 'i' and 1 or 0)
title_start_lines[end_title] = nil
if from_line >= to_line then return end
local to_col = ai_type == 'i' and vim.fn.getline(to_line):len() or l:len()
local from, to = { line = from_line, col = 1 }, { line = to_line, col = to_col }
table.insert(res, { from = from, to = to, vis_mode = 'V' })
end
for i, l in ipairs(lines) do
process_line(i, l)
end
return res
end
require('mini.ai').setup({ custom_textobjects = { x = custom_block } }) |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
echasnovski
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I think the most straightforward and robust way here would be to use function that returns array of regions. So something like this: