110 lines
2.6 KiB
Lua
110 lines
2.6 KiB
Lua
local M = {}
|
|
|
|
local has_treesitter, ts = pcall(require, "vim.treesitter")
|
|
local _, query = pcall(require, "vim.treesitter.query")
|
|
|
|
local M = {}
|
|
|
|
local function get_node_at_cursor()
|
|
local cursor = vim.api.nvim_win_get_cursor(0)
|
|
local cursor_range = { cursor[1] - 1, cursor[2] }
|
|
local buf = vim.api.nvim_get_current_buf()
|
|
local ok, parser = pcall(ts.get_parser, buf, "latex")
|
|
if not ok or not parser then
|
|
return
|
|
end
|
|
local root_tree = parser:parse()[1]
|
|
local root = root_tree and root_tree:root()
|
|
|
|
if not root then
|
|
return
|
|
end
|
|
|
|
return root:named_descendant_for_range(
|
|
cursor_range[1],
|
|
cursor_range[2],
|
|
cursor_range[1],
|
|
cursor_range[2]
|
|
)
|
|
end
|
|
|
|
local MATH_ENVIRONMENTS = {
|
|
displaymath = true,
|
|
equation = true,
|
|
eqnarray = true,
|
|
align = true,
|
|
math = true,
|
|
array = true,
|
|
}
|
|
|
|
local MATH_NODES = {
|
|
displayed_equation = true,
|
|
inline_formula = true,
|
|
math_environment = true,
|
|
}
|
|
|
|
M.in_env_md = function(env)
|
|
local row, col = unpack(vim.api.nvim_win_get_cursor(0))
|
|
local node = vim.treesitter.get_node({ bufnr = 0, pos = { row - 1, col } })
|
|
local bufnr = vim.api.nvim_get_current_buf()
|
|
while node do
|
|
if node:type() == "generic_environment" then
|
|
local begin = node:child(0)
|
|
local name = begin:field("name")
|
|
if name[1] and vim.treesitter.get_node_text(name[1], bufnr, nil) == "{" .. env .. "}" then
|
|
return true
|
|
end
|
|
end
|
|
node = node:parent()
|
|
end
|
|
return false
|
|
end
|
|
|
|
M.in_env = function(env)
|
|
local pos = vim.fn["vimtex#env#is_inside"](env)
|
|
return pos[1] ~= 0 or pos[2] ~= 0
|
|
end
|
|
|
|
-- For typst
|
|
M.in_mathzone= function()
|
|
if has_treesitter then
|
|
local buf = vim.api.nvim_get_current_buf()
|
|
local node = get_node_at_cursor()
|
|
while node do
|
|
if MATH_NODES[node:type()] then
|
|
return true
|
|
elseif node:type() == "math_environment" or node:type() == "generic_environment" then
|
|
local begin = node:child(0)
|
|
local names = begin and begin:field("name")
|
|
if names and names[1] and MATH_ENVIRONMENTS[query.get_node_text(names[1], buf):match("[A-Za-z]+")] then
|
|
return true
|
|
end
|
|
end
|
|
node = node:parent()
|
|
end
|
|
return false
|
|
end
|
|
end
|
|
|
|
M.in_text = function()
|
|
return not M.in_mathzone()
|
|
end
|
|
M.in_text_md = function()
|
|
return not M.in_mathzone()
|
|
end
|
|
|
|
M.in_item = function()
|
|
return M.in_env("itemize") or M.in_env("enumerate")
|
|
end
|
|
M.in_item_typst = function()
|
|
return M.in_env("itemize") or M.in_env("enum")
|
|
end
|
|
M.in_bib = function()
|
|
return M.in_env("thebibliography")
|
|
end
|
|
M.in_tikz = function()
|
|
return M.in_env("tikzpicture")
|
|
end
|
|
|
|
return M
|