If I have understood it correctly, you would like the section number to be displayed along with the theorem number only when it is referenced from another section.
Your P.S. suggests that this includes the number that is displayed in the theorem itself. (See the final comment at the bottom of this answer if you do want the section number displayed in the theorem head.)
Here is one way this could be accomplished:
\documentclass{report}
\usepackage{amsthm}
\newtheorem{theorem}{Theorem}[section]
\DeclareRobustCommand\optionalsec[1]{%
\ifnum\pdfstrcmp{#1}{\thesection}=0\else#1.\fi
}
\renewcommand\thetheorem{%
\optionalsec{\thesection}\arabic{theorem}%
}
\begin{document}
\chapter{First chapter}
\section{First section}
\begin{theorem} \label{th:a}
Theorem text.
\end{theorem}
The theorem above is called Theorem~\ref{th:a}.
\section{Second section}
The theorem in the previous section is called Theorem~\ref{th:a}.
\chapter{Second chapter}
\section{Another first section}
That theorem in the previous chapter is called Theorem~\ref{th:a}.
\end{document}


I'm defining a macro \optionalsec
that takes one argument and prints it only if it is different from the current (formatted) section number.
It also adds a period if this is the case.
So, for instance, \optionalsec{1.1}
prints nothing when called from within section 1.1, and it prints 1.1.
otherwise.
I then set \thetheorem
to \optionalsec{\thesection}\arabic{theorem}
so that the section number is only prepended if it is referenced from another section.
For this to work, the macro \optionalsec
needs to be robust (see e.g. the answers to this question), which means that it will be written to the .aux file unexpanded.
This is why I'm using \DeclareRobustCommand
instead of \newcommand
.
Remarks:
If you're using xelatex
or lualatex
, or using latex
to create a .dvi file, then you should instead define \optionalsec
using
\usepackage{pdftexcmds} %% <- for \pdf@strcmp
\makeatletter %% <- make @ usable in command names
\DeclareRobustCommand\optionalsec[1]{%
\ifnum\pdf@strcmp{#1}{\thesection}=0\else#1.\fi
}
\makeatother %% <- revert @
because \pdfstrcmp
is only defined for pdfTeX.
If you do want the section number to appear in the theorem head, you could define a theorem style that explicitly includes it and use that.
The following theorem style matches the default, apart from the inclusion of \thesection.
:
\usepackage{amsthm}
\newtheoremstyle{mytheoremstyle} %% Name
{} %% Space above
{} %% Space below
{} %% Body font
{} %% Indent amount
{\bfseries} %% Theorem head font
{.} %% Punctuation after theorem head
{5pt plus 1pt minus 1pt} %% Space after theorem head
{\thmname{#1}\thmnumber{ \thesection.#2}\thmnote{ #3}} %% Theorem head spec
\theoremstyle{mytheoremstyle}
\newtheorem{theorem}{Theorem}[section]