Take the 2-minute tour ×
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.

I am trying to do something like:

\newcommand{\sometext}{\input{somefile.txt}}

This works, but requires inputting the file every time the macro is used in the document.

I would like to know a way of forcing the file to be read when the macro is defined, so that when the macro is called in the document, it only represents the text, and not the command to read the text in.

share|improve this question
add comment

1 Answer 1

up vote 12 down vote accepted

You can read the content of a file into a macro with Heiko Oberdiek's catchfile package:

\CatchFileDef{\sometext}{somefile.txt}{<setup>}

This will read the file like a normal TeX file, i.e. it can include macros etc. The <setup> argument can be empty for files read normally but can include special code to e.g. read the file content verbatim or with special handling of line endings etc. A good candidate here is \makeatletter if the file contains macros with @ in their names.


Verbatim mode can be set using \let\do\@makeother\dospecials. You might want also to add \@noligs to disable ligatures. The text should then be typeset using \verbatim@font (which is identical to \normalfont\ttfamily). Otherwise some symbols (like _) will not be displayed correctly. The above commands need \makeatletter to be used before the \Catchfile and \makeatother afterwards.

If you want to preserve line endings use \obeylines. You should also add \obeyspaces if you want the spaces being print normally not with a special symbol. Also \frenchspacing can be added to avoid the larger space after dots.

\makeatletter
\CatchFileDef{\sometext}{somefile.txt}{\let\do\@makeother\dospecials\@noligs\obeyspaces\frenchspacing\relax}
\makeatother

% Verbatim text requires a suitable font:
\texttt{\sometext}

Make sure that the last command in <setup> isn't an assignment like ...\endlinechar=-1}. You need to add an \relax then, otherwise TeX will expand the internal commands of \CatchFileDef to look for the rest of the number. I mentioned that to the author already and an internal \relax will be added in the next version.

share|improve this answer
    
Thanks- that works well. But could you provide some more details on reading the content verbatim? What would one use as the setup argument in that case? –  Mark Mar 24 '11 at 19:24
    
@Mark: I updated my answer to include information about verbatim mode. –  Martin Scharrer Mar 24 '11 at 21:30
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.