使用 LuaLaTeX 确定当前表格列号

使用 LuaLaTeX 确定当前表格列号

我想使用 Lua 和 LaTeX 来确定排版表格时的当前列号。我更喜欢基于 Lua 的解决方案,因为我不太擅长使用纯 TeX 或 expl3。

以下为示例:

The & col & is & \colNum

生产

The & col & is & 4

我预见到的一些问题:如果我想利用输入缓冲区来尝试这一点,我相信它会一次处理一行。例如,如果我想计算&没有前导的行数\,我需要在新行上使用列计数宏。是否有任何我可以利用的内部 tex 变量或计数器?

重写&以提高计数器并重写\\以重置它是否会有害?

答案1

可以使用LuaTeX的节点库来统计当前行对应的hlist中现有的列:

\documentclass{article}
\directlua{
  local funcs = lua.get_functions_table()
  local glue_t, unset_t, tabskip_st = node.id'glue', node.id'unset'
  for subid, name in ipairs(node.subtypes'glue') do
    if name == 'tabskip' then
      tabskip_st = subid
      break
    end
  end
  assert(tabskip_st)
  local colNumFunc = luatexbase.new_luafunction'colNum'
  token.set_lua('colNum', colNumFunc)
  funcs[colNumFunc] = function()
    local nest
    % Find the nesting level corresponding to the alignment row
    for i = tex.nest.ptr, 1, -1 do
      local tail = tex.nest[i].tail
      % We identify alignments by testing the last node:
      % In an alignment row it will always be a tabskip and tabskips can't appear
      % outside of alignments (except if people write crazy Lua code, but then all bets are off anyway)
      if tail.id == glue_t and tail.subtype == tabskip_st then
        nest = tex.nest[i]
        break
      end
    end
    if nest then
      % We found an alignment, now just count the existing boxes
      % Every column is a unset node, the subtype contains the number of additionally spanned columns
      local col = 1
      for _, sub in node.traverse_id(unset_t, nest.head) do
        col = col + sub + 1
      end
      tex.sprint(-2, tostring(col))
    else
      % There was no alignment. The user is trying to mess with us again
      tex.error'Attempt to get column number outside of alignment'
      tex.sprint(-2, '0')
    end
  end
}
% Based on a learnlatex.org example since the OP couldn't be bothered to include a MWE
\usepackage{array}

\begin{document}
\begin{tabular}{cp{9cm}}
  Column \colNum: Tier  & Beschreibung \\
  Hund                  & Column \colNum: Der Hund ist ein Mitglied der Gattung Canis, welche Teil der Familie
                          Canidae ist, und das weitverbreitetste Landraubtier. \\
  Column \colNum: Katze & Column \colNum: Katzen sind eine domestizierte Art kleiner fleischfressender
                          Säugetiere. Sie ist die einzige domestizierte Art der Familie Felidae
                          und wird häufig als Hauskatze bezeichnet, um sie von den wildlebenden
                          Mitglieder dieser Familie abzugrenzen. \\
\end{tabular}
\end{document}

在此处输入图片描述

相关内容