3

I want to accomplish the following: write function \mydictionary{} which takes every two lines of the following

aa
bb
cc
dd
ee
ff
etc

and outputs with formatting

\textbf{aa}\textit{bb}
\textbf{cc}\textit{dd}
\textbf{ee}\textit{ff}
etc

How can I do this in LaTeX?

Thanks in advance.

4
  • 1
    This seems to be a job for sed or awk but not LaTeX.
    – Johannes_B
    Jan 7, 2017 at 16:51
  • 1
    @Johannes_B ... or latex :-) Jan 7, 2017 at 17:18
  • @DavidCarlisle ... or TeX (there is nothing LaTeX specific in our answer).
    – wipet
    Jan 8, 2017 at 15:34
  • @wipet apart from \textxx :-) Jan 8, 2017 at 16:43

2 Answers 2

10

enter image description here

\documentclass{article}

\def\foo#1 #2 {%
\ifx!#1\else
\textbf{#1}\textit{#2} %
\expandafter\foo\fi}


\begin{document}

\foo
aa
bb
cc
dd
ee
ff
! !

\end{document}
2

I'm new to writing macros, so here's a trivial variant that I find easier to reason about: using two sentinel values, one to terminate the macro and one to identify the end of arguments.

\documentclass{article}

\def\mydictionary#1 #2 #3!{%
\textbf{#1}\textit{#2}
\ifx Z#3\else\mydictionary#3!\fi}

\begin{document}

\mydictionary
aa
bb
cc
dd
ee
ff
Z!

\end{document}

Of course if your text has any ! internally, or if some odd-numbered line begins with Z, you'll need to choose different delimiters to get the desired results.

3
  • 1
    note that this uses far more of TeX's stack than the version I posted, you scan the entire list each time in #3 and as the recursive call is not at the end there is no tail recursion elimination and this will stack in tex's input buffers, similarly as you have not expanded the \fi before the recursive call this will be in an open ifx context nested for each pair Jan 8, 2017 at 16:56
  • @DavidCarlisle Thank you! I posted this answer partly hoping to learn something like this. That makes sense, and now I understand better the motivation for using the \expandafter\foo\fi form. Jan 8, 2017 at 17:51
  • @DavidCarlisle Aside: Actually I'm new to writing macros and my first real introduction recently came from trying to understand your own xii.tex :-) After unpacking everything (slowly), I understood everything except the reason for exactly this thing (the & macro, defined by something effectively like \def&#1\fi{\fi#1}), and now I understand that as well! Jan 8, 2017 at 17:52

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .