Is there any way of measuring the width of a VerbatimInput block?

In other words, I would like something along the following lines, except that the verbatim data should be taken from an external file as with \VerbatimInput:



% Get the verbatim data from an external file instead.
\SaveVerb{data}+verbatim text }&^+


Width is: \the\mylength.


(Saving the verbatim block is not crucial to me so if there is some completely different way of measuring its width that would also be fine. I also don't insist on using the \fancyvrb package if there is another verbatim package that does this.)


Your code actually works and will also work with listings. Better include a frame to see what is happening.

This is some verbatim .
Width is: \the\mylength.\par

As you change the contents of the file (which I saved with filecontents) you will see the length changing.

  • Thanks, that works great! Just one follow-up question: if I understand you correctly you are saying that this would also work with fancyvrb (which I would slightly prefer over listings in this case), but if in your code snippet above I replace \lstinputlisting with \VerbatimInput I get a "Something's wrong--perhaps a missing \item." error in the \settowidth command. – Per Austrin Mar 18 '12 at 14:07
  • @PerAustrin It is due to \fbox. Please replace with \fbox{\hbox to \mylength{\vbox{\VerbatimInput{verbatim.tex}}}} and everything will work out. – Yiannis Lazarides Mar 18 '12 at 14:29

You can use \savebox{\mybox}{<content>} (need \newsavebox\mybox first) to store anything in an horizontal box and then access its width using \wd\mybox. Actually \settowidth does something like that.

The problem with \VerbatimInput from fancyvrb is that it inserts the verbatim text as paragraph which will cause trouble in the restricted horizontal mode forced by a savebox and will force the width of the content to \linewidth anyway! Therefore you need to find some other command to input the verbatim text without forming a full paragraph. I'm not sure with verbatim package allow you to insert single-line verbatim content from an external file without forming a paragraph. However you could use the following command I just wrote which uses the usual verbatim related settings to do the job.



% Saves single line verbatim content into savebox from a file



Width is: \the\wd\mybox.

Text is: \usebox{\mybox}

  • Thanks! Unfortunately my files have more than one line so this does not quite solve my problem. – Per Austrin Mar 18 '12 at 14:08
  • @PerAustrin: Ok, then I misunderstood your question slightly. Your example made it look like you are working with small inline verbatim texts. – Martin Scharrer Mar 18 '12 at 15:51

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.