2

I'm trying to visualize newlines in an input file by making ^^M active and displaying it as \n. However, the \input command appears to append an extra empty line at the end of the file, which I don't want.

According to tex.pdf:

486. An empty line is appended at the end of a read_file.

Here's a minimal example demonstrating the issue:

\documentclass{article}

\begingroup
\catcode`\^^M=13%
\gdef\visiblenewline{%
\catcode`\^^M=13%
\def^^M{ \textbackslash n }%
}%
\endgroup

\begin{document}
\visiblenewline\input{file.txt}%
\end{document}

file.txt:

Line 1
Line 2
Line 3
Line 4
Line 5

(Note: file.txt has no trailing empty lines)

Expected Output

Line 1 \n Line 2 \n Line 3 \n Line 4 \n Line 5

Actual Output

Line 1 \n Line 2 \n Line 3 \n Line 4 \n Line 5 \n 

The extra \n at the end is the problem. How can I prevent this automatically appended empty line from appearing, or strip it during input? I'm looking for a TeX-level workaround for this behavior.

3
  • please do not link to particular mirrors. link to the round robin thingy instead. Commented 22 hours ago
  • note a line without a newline after 5 isn't portable, not all filesystems support that which was why tex always acts as if one is there. you don't need "trailing empty lines" just a end of line at the end of the last line Commented 19 hours ago
  • 1
    beware doing \catcode`\^^M=13% better use =\active or =13 % or the following commands will be expanded before the assignment Commented 19 hours ago

1 Answer 1

4

There should be an end of line after 5 many editors (diff programs etc) will complain with files with no end of line after the last line, but anyway whether or not there is an eol in the actual file you can remove a final \n

enter image description here

\documentclass{article}

\begingroup
\catcode`\^^M=13%
\gdef\visiblenewline{%
\catcode`\^^M=13%
\def^^M{\leavevmode\hbox{ \textbackslash n }}%
}%
\endgroup

\begin{document}
{
  \visiblenewline\input{file.txt}%
 \setbox0\lastbox}%
\end{document}
6
  • 1
    why do you need to set the cat code inside and outside the defn, please? Commented 17 hours ago
  • 1
    @cfr I just copied the code from the OP. But you need it on the outside so \def^^M is valid, and you need it on the inside so it is active when the file is read. Commented 17 hours ago
  • oh, I see. because the change inside the \gdef doesn't affect the meaning of its definition? Commented 15 hours ago
  • 1
    yes the replacemnt text is like any other argument it is tokenised with the catcodes in effect at the time of definition not the time of use. Commented 14 hours ago
  • thanks. it frustrates me that I know that, but I still cannot read it that way. Commented 13 hours ago

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.