# [Tugindia] Help me write a macro? (writing out strings to a file)

Tue Sep 13 13:37:27 CEST 2005

On Tue, September 13, 2005 2:37 pm, Ajay Narottam Shah said:
> Folks,
>
> I want to write a macro which works like this.
>
> The context is a book. At the start of processing chapter 4, an empty
> file 4.keywords should be created. When I say:
>
>      \keyword{string}
>
> this should be typeset in boldface in the running text, but
>
>      string\\
>
> should be written into 4.keywords as well. File buffering should not
> be done.
>
> At the end of the chapter, I should be able to say
>
> \tableofkeywords
>
> which should induce the code:
>
>   \section*{Keywords}
>
>   \textsl{
>     \input{4.keywords}
>   }
>
> By not having buffering, it would become a one-pass algorithm, because
> at the end of the chapter, the file 4.keywords would be ready to use.
>
> How would I go about writing this macro?

Here is one way of doing it:

\documentclass[a4paper]{book}
\usepackage{xspace}

\newwrite\keywrite

\def\keyword#1{\IfFileExists{\thechapter.keywords}%
{\immediate\write\keywrite{\string\key{#1}\string\\}}%
{\immediate\openout\keywrite=\thechapter.keywords
\immediate\write\keywrite{\string\key{#1}\string\\}}%
\textbf{#1}\xspace}

\def\key#1{\textsl{#1}}%

\def\tableofkeywords{%
\IfFileExists{\thechapter.keywords}%
{\immediate\closeout\keywrite
\section*{Keywords}%
\input{\thechapter.keywords}%
}%
{\typeout{Keywords File not available}}%
}

%---------------------------------------------------

\begin{document}

\chapter{One}

This is a keyword test.
\keyword{One}
\keyword{A}
\keyword{B}
\keyword{Keywords}

\tableofkeywords

\chapter{Two}

This is another chapter to test keywords.

\keyword{Two}
\keyword{Another}
\keyword{Ajay}

\tableofkeywords

\end{document}

--