動態表格:設定表格後的列號

動態表格:設定表格後的列號

我想建立一個動態表格,\N在頁面開頭有一個列,其中\N是整個文件的節數,因此\N設定的值桌子。當我設定\Ntable 之前的值時(在我的範例中,將 line 26 移到\N=\value{section}line 10 之後\section{section 1}),一切正常,但是當我設定 table 之後的值時\N(如我的範例所示),這會生成錯誤。

\N這是我的程式碼,表後面有 set 的值。我想這並不難,但我找不到解決方案。有人有想法嗎?

\documentclass[12pt,a4paper]{article}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage[french]{babel}
\usepackage{graphicx}
\newtoks\cols
\newcounter{i}
\newcount\N
\begin{document}
    \section{section 1}
\cols={}
\setcounter{i}{1}
\loop
\cols=\expandafter{\the\expandafter\cols\the\value{i}}
\ifnum\value{i}<\N
\cols=\expandafter{\the\cols &}
\stepcounter{i}
\repeat
\begin{tabular}{|*{\N}{c|}}
    \the\cols
\end{tabular}
\section{section 2}
\section{section 3}
\section{section 4}
\section{section 5}
\N=\value{section}
\end{document}

答案1

通常,可以透過將表儲存到外部文件在文件末尾。您所需要做的就是\input文件前面部分的外部文件。然而,這確實需要編譯文件兩次才能正確更新表。這是一個例子:

\documentclass[12pt,a4paper]{article}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage[french]{babel}
\usepackage{graphicx}
\usepackage{expl3}

\begin{document}
\section{section 1}
% load the table, if it exists
\InputIfFileExists{\jobname.table}{}{}
\section{section 2}
\section{section 3}
\section{section 4}
\section{section 5}

\ExplSyntaxOn
% open external file for writing
\iow_open:Nn \g_tmpa_iow {\jobname.table}
% get number of sections
\int_set:Nn \l_tmpa_int {\value{section}}
% write begin environment 
\iow_now:Nx \g_tmpa_iow {\c_backslash_str begin{tabular}
    {|*{\int_use:N \l_tmpa_int}{c|}}}
% write columns into a sequence
\seq_clear:N \l_tmpa_seq
% loop over integers and fill the sequence
\int_step_inline:nn {\l_tmpa_int} {
    \seq_put_right:Nn \l_tmpa_seq {#1}
}
% write table content
\iow_now:Nx \g_tmpa_iow {
    \seq_use:Nn \l_tmpa_seq {~&~} % join the sequence with " & "
}
% write end environment
\iow_now:Nx \g_tmpa_iow {\c_backslash_str end{tabular}}
\iow_close:N \g_tmpa_iow
\ExplSyntaxOff
\end{document}

我對LaTeX3比較熟悉。我相信您也可以使用 LaTeX2e 程式碼來實現相同的目標。

更新:將節數儲存在變數中

如果您只想將節數儲存在變數中,這裡有一個更簡單的範例。它將該行寫入文件\global\def\numsection{5}aux可以在下次運行時存取該文件。

\documentclass[12pt,a4paper]{article}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage[french]{babel}
\usepackage{graphicx}


\begin{document}
Number of sections: \numsection

\section{section 1}
\section{section 2}
\section{section 3}
\section{section 4}
\section{section 5}

\makeatletter
\immediate\write\@auxout{\string\global\string\def\string\numsection{\the\value{section}}}
\makeatother

\end{document}

相關內容