Files
nvim/lua/util/latex.lua

109 lines
2.5 KiB
Lua
Raw Permalink Normal View History

2025-05-13 19:37:28 +10:00
local M = {}
2025-10-14 20:51:06 +11:00
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,
}
2025-05-13 19:37:28 +10:00
local MATH_NODES = {
displayed_equation = true,
inline_formula = true,
math_environment = true,
}
M.in_env_md = function(env)
2025-09-21 20:43:38 +10:00
local row, col = unpack(vim.api.nvim_win_get_cursor(0))
local node = vim.treesitter.get_node({ bufnr = 0, pos = { row - 1, col } })
2025-05-13 19:37:28 +10:00
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
2025-10-14 20:51:06 +11:00
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()
2025-09-21 20:43:38 +10:00
end
2025-10-14 20:51:06 +11:00
return false
2025-05-13 19:37:28 +10:00
end
end
M.in_text = function()
return not M.in_mathzone()
end
2025-10-14 20:51:06 +11:00
M.in_text_md = function()
return not M.in_mathzone()
end
2025-05-13 19:37:28 +10:00
M.in_item = function()
return M.in_env("itemize") or M.in_env("enumerate")
end
2025-09-30 22:59:47 +10:00
M.in_item_typst = function()
return M.in_env("itemize") or M.in_env("enum")
end
2025-05-13 19:37:28 +10:00
M.in_bib = function()
return M.in_env("thebibliography")
end
M.in_tikz = function()
return M.in_env("tikzpicture")
end
return M