[Tex/LaTex] How to ‘\input’ a file without getting the implicit newline

external filesinput

Intro

I'm working on a lightweight package that allows you to put any content (typically LaTeX code) in an environment, then use that content multiple times, each time scanned separately, so you can use it both as verbatim output and interpreted as LaTeX.

Its main purpose is to typeset LaTeX code and its 'result' side-by-side; useful for documenting TeX packages without having to copy/paste code. But it has other purposes as well.

After experimenting with \scantokens until I gave up in tears, I arrived at the filecontents environment, which almost solved my problem singlehandedly!

The Problem

The problem is, when reintroducing filecontented code through \input, LaTeX adds an implicit newline at the end, which translates to whitespace that I can't seem to get rid of.

I've seen many semi-related questions floating around, with answers employing techniques like:

  • reading a file line-by-line,
  • using \everyeof in some clever way,
  • playing with \endlinechar or
  • using packages such as catchfile

but none of them provides a clear answer to the following question:

The Question

How can I \input a file without getting the implicit newline?

Minimal Working Example

\documentclass[margin=1mm]{standalone}

\usepackage{filecontents}

\begin{filecontents*}{tmp.tex}
    \LaTeX{}\end{filecontents*}

\begin{document}
    \fbox{\input{tmp.tex}}
\end{document}

enter image description here

Note the extra whitespace to the right of the box.

Note also that I'm definitely not adding any explicit whitespace. Even a manually produced file (so, not using filecontents) with no newlines at all exhibits the same problem.

Best Answer

The following requires a different command, say \minput:

\documentclass[margin=1mm,varwidth]{standalone}

\usepackage{filecontents}

\newcommand\minput[1]{%
  \input{#1}%
  \ifhmode\ifnum\lastnodetype=11 \unskip\fi\fi}

\begin{filecontents*}{tmp.tex}
\LaTeX{}
\end{filecontents*}
\begin{filecontents*}{tmp2.tex}
\LaTeX
\end{filecontents*}
\begin{filecontents*}{tmp3.tex}
\LaTeX\hspace{2em}
\end{filecontents*}

\begin{document}
\fbox{\input{tmp.tex}} \fbox{\minput{tmp.tex}}

\minput{tmp}Nospace \minput{tmp} Space

\minput{tmp2} Space

\minput{tmp3}Nospace

\LaTeX\hspace{2em}Nospace
\end{document}

This will fail if the input file ends with something like \hskip 2pt, but I believe one can ignore such cases.

enter image description here

Related Question