[Tex/LaTex] Lyx cross refernce to figures not working when there is a new line between caption and label

cross-referencingfloatslyx

When I put a new line between the caption and label of a figure float, the cross referencing is shown as "Figure ??" in the resulting PDF file. The hyperlink in the PDF however, works just fine. After removal of the newline between the caption and label, the cross referencing is shown properly, i.e. "Figure 1.1". Does that newline somehow disassociates the label from the caption ? My understanding is that, as long as they are all withing the same float, it should work.

The screen shots are bellow:

without new line, this works

with a new line, this doesn't work

before edit on Jan 10:

I'm writing a thesis containing several chapters. The master document's documentclass is book(KOMA-script). The chapters are inserted as branches of the master document. Cross referencing to figures are working fine for all chapters except one. In this faulty chapter, the cross references appear as "Figure ??". However, the hyper link within the resulting PDF document works.

I've already checked this, this is not exactly the problem I'm facing.

Best Answer

When you mention "hyperlink to the figure", I assume you're referring to the hyperlink from the LoF. Yes, that's all based on the \caption, which is set correctly. However, as is clear from your example code, inserting a newline in LyX actually creates a separate group around the caption:

\begin{figure}[h]
\noindent \begin{centering}
\includegraphics[<opts>]{<filename>}\caption{<caption>}

\par\end{centering}

\noindent \centering{}\label{<label>}
\end{figure}

From the above we can see that \caption is placed inside a centering group. Now, according to Understanding how references and labels work you'll see that \label uses \@currentlabel - a macro that is updated when you step a counter. In this case the counter is stepped as part of the call to \caption. However, this update is reverted when the group is closed, because the update is only local to the group that its used in.

So it seems you should NOT put an empty line between the \caption and \label in LyX. It's just the way LyX interprets new lines within structures that seems strange. Of course, as a GUI-like editor for LaTeX, it attempts to remove some of the code-like insertions from the user. However, with this intuitiveness comes some assumptions... something that is clearly incorrectly interpreted in this case.

Related Question