4

Is it possible to read from stdin in plain TeX? I have seen that it is possible in LaTeX with \typein (See here), however, this is unavailable in TeX. Are there any alternatives?

An MWE in LaTeX:

\documentclass{article}
\begin{document}
    \typein[\name]{What is your name?}%
    Hello, ``\name''
\end{document}"

This is pdfTeX, Version 3.14159265-2.6-1.40.18 (TeX Live 2017/Debian) (preloaded format=pdfl

  • Check latexdef @xtypein (the definition of typein)… – TeXnician Jan 22 at 15:56
  • @TeXnician \@xtypein doesn't seem to be defined, I'm running my program using tex – The Sign Painter Jan 22 at 16:20
  • Yes, of course you are using tex, but if you wanted to see what LaTeX does (in terms of TeX macros) it would be easiest to have a look at the LaTeX definition in latex.ltx or via latexdef… – TeXnician Jan 22 at 17:00
4

When you say \read<number> to \foo when the number doesn't correspond to an open input stream and the number is nonnegative, TeX will prompt you with

\foo=

The stream cannot be open if the number is greater than 15, so any integer from 16 up is good. If you use a negative number, the prompt is not shown, but TeX will wait for input nonetheless.

There's the problem of the trailing space, which comes from the end-of-line you insert by hitting Return. This can be solved by setting the end-of-line character to have category code 9.

\def\prompt#1{%
  \begingroup
  \catcode`\^^M=9 % ignore the end-of-line
  \read 20 to #1%
  \expandafter\endgroup
  \expandafter\def\expandafter#1\expandafter{#1}%
}

\prompt\foo

\show\foo

The console output is

\foo=xyz
> \foo=macro:
->xyz.
l.11 \show\foo

?

In the first line TeX prompts for \foo; I typed in xyz and Return. The output of \show tells us that there is no space. The grouping confines the change of category code. With the chain of \expandafter we are able to define \foo also outside the current group before closing it.

2

Similarly to \write 18 for output, the following solved my issue.

\read 18 to \name

Content from stdin appears in \name, however a space appears on the end.

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.