5

How can i let Tex only display the list of tables if there exists at least one table and not if there's none?

2
  • 1
    Welcome to tex.sx. To clarify, what you want is to be able to always specify \listoftables, but have a page with that heading produced only if a table exists. Is that so? Jun 25 at 21:17
  • Yes, that is so. Jul 24 at 22:23

1 Answer 1

8

You can save the meaning of \listoftables, make the macro a no-op, but then add at the beginning of the first table the instruction to write in the log file that \listoftables has to receive its original meaning.

With \AddToHookNext, this is executed just once.

\documentclass{article}

\makeatletter
\let\orig@listoftables\listoftables
\let\listoftables\relax
\AddToHookNext{env/table/begin}{%
  \write\@auxout{\global\let\string\listoftables\string\orig@listoftables}%
}
\makeatother

\begin{document}

\listoftables

\section{Test}

\begin{table}[htp]
There is a table
\caption{Test}
\end{table}

\begin{table}[htp]
There is a table
\caption{Test}
\end{table}

\end{document}

enter image description here

The .aux file contains

\relax 
\@writefile{toc}{\contentsline {section}{\numberline {1}Test}{1}{}\protected@file@percent }
\global \let \listoftables\orig@listoftables
\@writefile{lot}{\contentsline {table}{\numberline {1}{\ignorespaces Test}}{1}{}\protected@file@percent }
\@writefile{lot}{\contentsline {table}{\numberline {2}{\ignorespaces Test}}{1}{}\protected@file@percent }
\gdef \@abspage@last{1}

Note that \global is necessary, because the .aux file is read in a group.

If I comment out the two table environments, the output is

enter image description here

and no list of tables is produced.

11
  • Your example works out a strange way. If i test it in "TeXstudio", sometimes the list of tables is seen, sometimes is not whenever tables are present and if i delete the tables then after first run, the list is present, after second run, it's not. If i test your example with "bookdown" then the list of tables won't appear no matter the tables are present or not. Without your example, the empty list of tables is present if no tables are present. Jul 24 at 22:59
  • @user7351278 I don’t know what bookdown is, sorry. Are you sure you have an up-to-date TeX distribution?
    – egreg
    Jul 25 at 7:45
  • bookdown is a framework for creating different output out of R markdown files. The distribution is up-to-date. Jul 27 at 0:47
  • @user7351278 Still unclear, sorry. Possibly the conversion engine doesn’t handle the code right.
    – egreg
    Jul 27 at 8:42
  • How do you check whether your code works? Jul 28 at 6:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.