lunes, 24 de agosto de 2009

Contador dinámico en LaTeX // LaTeX dynamic counter

(spanish version below)

I recently found myself in need of enumerating several tasks inside a tabular environment. The number of tasks was high and subjected to changes both in number and order so I thought that I needed a way to avoid having to manually change the number corresponding to each task.

I didn't find any tutorial that satisfied my requirements, so I had to find my own way of doing things. This tutorial tries to explain the solution I adopted, though any change or improvement is welcome.

1- Create the counter and set its initial value

\newcounter{counter}
\setcounter{counter}{1}

2- I want to use it inside a tabular environment and I want to make sure that each new line increments the value of the counter. To achieve this, I created a new command that adds a new line to a table and increments the value of the counter.

\newcommand{\newtbln}{\stepcounter{counter} \\ \hline}

I'd advise you to place new commands at the top of your LaTeX sheet so that these new commands become part of your template.

3- Create the table and use the counter with the \the command, which accesses the value of the variable

%5 centered columns. The one containing the description of the task has its width limited to 5.5 cm
\begin{tabular}{|c|p{5.5cm}|c|c|c|}
\hline
%I don't want this line to increment the counter thus I create the new line the traditional way
\emph{Id} & \emph{Description} & \emph{Duration} & \emph{Starting date} & \emph{Ending date} \\ \hline
\thecounter & This is the first task & - & - & - \newtbln
\thecounter & This is the second task & - & -& - \newtbln
\thecounter & This is the third task & - & -& - \newtbln
\end{tabular}


A screenshot of the resulting table


(it has an error, but I don't feel like taking a new screenshot)

* SPANISH VERSION *


Recientemente me vi en la necesidad de enumerar una serie de tareas dentro de una tabla. Eran bastantes y ni el número ni el orden estaba claro, de hecho era bastante probable que lo cambiara a mitad, así que decidí buscar la manera de evitar tener que reescribir a mano los números que correspondían a cada tarea, cosa que ya me ha tocado hacer en el pasado.

No encontré ningún tutorial ni página que lo explicara claramente y al final tuve que mezclar información de diversas fuentes, así que he decidido hacer este mini tutorial para explicar mi solución. Si alguno tenéis algo mejor, estaré encantado de actualizar esta entrada.

1- Crear el contador y fijar su valor inicial, en mi caso 1

\newcounter{counter}
\setcounter{counter}{1}

2- Como lo quiero usar dentro de una tabla, quiero asegurarme de que cada nueva línea incremente el contador en 1. Para esto creo un nuevo comando que crea una nueva línea en la tabla e incrementa el contador.

\newcommand{\newtbln}{\stepcounter{counter} \\ \hline}

Os recomiendo que los comandos nuevos que creéis los pongáis en la parte de arriba del documento LaTeX de manera que si reutilizáis la plantilla no tengáis que ir buscándolos por el texto.

3- Por último, creo la tabla y accedo al valor de la variable con el comando \the

%5 columnas centradas y la que contiene más texto limito su ancho a 5.5 cm
\begin{tabular}{|c|p{5.5cm}|c|c|c|}
\hline
%Esta línea no quiero que incremente el contador, así que no uso el comando creado antes
\emph{Id} & \emph{Description} & \emph{Duration} & \emph{Starting date} & \emph{Ending date} \\ \hline
\thecounter & This is the first task & - & - & - \newtbln
\thecounter & This is the second task & - & -& - \newtbln
\thecounter & This is the third task & - & -& - \newtbln
\end{tabular}


Y por último, el resultado final


(tiene un error, pero no me apetece tomar un nuevo screenshot)

4 comentarios:

Poplop dijo...

¿Es que nadie se atreve con esto?

Ignacio dijo...

Very good English, cousin. I´m impressed. Is "Tabular environment" the way you computer people call it?

Miguel dijo...

I'm glad your judgment is positive, I know you are a demanding reader.

In the LaTeX world, an environment is a concept to define a block inside the whole. In this case, the environment is called tabular (\begin{tabular}), but there are dozens of environments, each of them with their own rules and style.

Anónimo dijo...

@Tigre. Nice post, tought that you've forgotten your blog after all this time without writting.

@Ignacio and @Tigre. I think that you could also explain as what it's inside the enviroment have different scope. Dunno...