15

I am trying to create a LaTeX command that will allow me to insert pre-defined tables with a minimum of fuss. This will also allow me to change the overall format of tables (e.g. caption above or below) globally, without having to modify each instance.

Ideally, I am thinking something along the lines of \includetable{label}{caption}, where label corresponds to the float's label (for linking purposes), and caption corresponds to the caption displayed above (or below) the table. I would like to use label for the filename also, e.g. the table contents would be defined in label.tex.

The problem I have is that I use colons in my labels to distinguish tables, figures, and sections in a consistent manner. For example, a table relating to a structure's mass budget would have a label like t:structure:mass; in Windows, I cannot have colons in filenames, so I would like the function \includetable to replace colons with hyphens when calling \input.

The closest thing I've found on Stack Overflow is https://stackoverflow.com/questions/95824/replace-a-character-with-a-string-in-latex, but I can't get this to work with colons instead of commas. Suggestions?

3
19
\usepackage{xstring}
\newcommand{\includetable}[2]{%
  \begin{table}
  \centering
  \caption{#2}\label{#1}
  \StrSubstitute{#1}{:}{-}[\temp]%
  \input{\temp}
  \end{table}}

Some variations are possible. One can think, for example, to a key-value syntax for deciding the position of the caption and for providing a short caption.

1
  • The package is named xstring without the s. – Ludovic Kuty Jun 27 '12 at 13:00
4

To be compiled with luaTeX.

\documentclass{article}

\begin{filecontents*}{t-mysection-mytable.tab}
\begin{tabular}{c|c}
  10 & 20 \\
  20 & 40
\end{tabular}
\end{filecontents*}

\def\includetable#1#2{%
  \begin{table}
    \centering
    \input{%
      \directlua{%
        local s, _ = string.gsub("#1",":","-")
        tex.sprint(s)}.tab}%
    \caption{#2}\label{#1}
  \end{table}}

\begin{document}

\includetable{t:mysection:mytable}{My table}

\end{document}

Your Answer

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