# Insert box only if enough space at line's end

I have a general question about the paragraph-forming mechanism, but provide an example of the application (skip down to the general question if you prefer):

I am looking at Skeat's edition of Piers the Plowman (published 1869) and want to automate the book's typesetter's approach to appending line number aids at the end of each line: print every fifth line number at the end of the line (flush right against the right margin), except that when the text comes right up to the right margin (or is even allowed to overflow it slightly), defer inserting the line number until the next available opportunity (as done below). It's not hard to simply correct the labeling by hand, but let's suppose there is no possibility of editing the .tex file by hand between successive compilations.

The general question is whether there is a way of testing whether a line break has been previously inserted (i.e., an \hbox has already been added to the current vertical list) in the current paragraph? And of testing whether a break is optimal at a particular word boundary within a paragraph? Could this be done in one compilation pass, or would it take two?

(I see what might be a similar situation at another question, but wonder whether this particular problem is tractable to a more elegant solution).

• it's impossible to answer really wothout some sample input, in normal running text linebreaking is optimised over the whole paragraph so no boxes have been added to the vertical list until all macros in the paragraph have been evaluated. On the other hand in manual line breaking such as the verse environment \\  each line is really a separate paragraph and added individually so can of course be measured and a number added or not easily. The same could also be done (perhaps) in automatic line breaking but there are choices, do you want the number to affect the linebreaking – David Carlisle Aug 4 '16 at 8:39
• @DavidCarlisle thanks for the comments. Since you say the one-line-per-paragraph case is easy, I'm going to try to solve it on my own. If I can't figure it out, I'll update the question with an MWE. – jlovegren Aug 4 '16 at 17:09