You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Neovim中自定义LuaSnip片段生成LaTeX各类表格?

自定义LuaSnip实现LaTeX表格类片段的方案

1. 基础静态表格片段

先从最简单的静态片段入手,直接定义固定结构的tabular、array等环境,适合快速插入常用格式:

local ls = require("luasnip")
local s = ls.snippet
local t = ls.text_node
local i = ls.insert_node

ls.add_snippets("tex", {
  -- 基础tabular片段(默认两列居中)
  s("tab", {
    t("\\begin{tabular}{"),
    i(1, "cc"), -- 可直接改成常用列格式,比如|c|c|
    t("}"),
    t({"", "\\hline"}),
    t({"", i(2, "内容 & 内容 \\\\"), ""}),
    t({"", "\\hline"}),
    t({"", "\\end{tabular}"}),
    i(0) -- 光标最终停留位置
  }),

  -- 数学环境array片段
  s("arr", {
    t("\\begin{array}{"),
    i(1, "cc"),
    t("}"),
    t({"", i(2, "a & b \\\\"), ""}),
    t({"", "c & d"}),
    t({"", "\\end{array}"}),
    i(0)
  }),
})

2. 动态生成行列的智能片段

如果需要根据输入的行列数自动生成对应结构,用dynamic_node实现,避免手动重复写&和\:

local ls = require("luasnip")
local s = ls.snippet
local t = ls.text_node
local i = ls.insert_node
local d = ls.dynamic_node
local fmt = require("luasnip.extras.fmt").fmt

ls.add_snippets("tex", {
  -- 动态列数的tabular片段
  s("dtab", fmt([[
    \begin{tabular}{>{}}<{}}
      \hline
      {}
      \hline
    \end{tabular}
    {}
  ]], {
    i(1, "c"), -- 单列格式,比如c、l、r
    i(2, "3"), -- 列数,输入数字后自动生成对应列的占位符
    d(3, function(args)
      local cols = tonumber(args[1][1]) or 1
      local line = {}
      -- 生成一行的列占位符
      for j = 1, cols do
        table.insert(line, i(j, "col" .. j))
        if j ~= cols then
          table.insert(line, t(" & "))
        end
      end
      table.insert(line, t(" \\\\"))
      return ls.sn(nil, line)
    end, {2}), -- 依赖第二个输入的列数
    i(0)
  })),
})

3. 数学专用矩阵片段

针对数学笔记常用的pmatrix、bmatrix等环境,写专属片段:

ls.add_snippets("tex", {
  -- 带括号的pmatrix矩阵片段
  s("pmatrix", {
    t("\\begin{pmatrix}"),
    t({"", i(1, "1 & 0 \\\\"), ""}),
    t({"", "0 & 1"}),
    t({"", "\\end{pmatrix}"}),
    i(0)
  }),

  -- 方括号bmatrix片段
  s("bmatrix", {
    t("\\begin{bmatrix}"),
    t({"", i(1, "a & b \\\\"), ""}),
    t({"", "c & d"}),
    t({"", "\\end{bmatrix}"}),
    i(0)
  }),
})

4. 带表头的复杂表格片段

如果需要带竖线、多行表头的复杂表格,直接定义结构化片段:

ls.add_snippets("tex", {
  s("tabhead", fmt([[
    \begin{tabular}{|{}|{}|}
      \hline
      {} & {} \\
      \hline
      {} & {} \\
      \hline
      {} & {} \\
      \hline
    \end{tabular}
    {}
  ]], {
    i(1, "c"), i(2, "c"),
    i(3, "表头1"), i(4, "表头2"),
    i(5, "内容1"), i(6, "内容2"),
    i(7, "内容3"), i(8, "内容4"),
    i(0)
  })),
})

使用提示

  • 把上述代码放到Neovim配置目录下的lua/snippets/tex.lua,然后在init.lua里添加加载语句:
    require("luasnip.loaders.from_lua").load({paths = "~/.config/nvim/lua/snippets/"})
    
  • 可按需调整默认列格式、占位符内容,比如把默认列数改成2,或者给表格加上默认竖线
  • 动态片段还可以扩展支持输入行数,生成多行内容,原理和动态列数一致

内容的提问来源于stack exchange,提问作者Oleg Khodasevich

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 03:43:39