How can I make a conditional that checks if it is currently inside a \part, \chapter, or \section?
IF inside sectioning = TRUE
DO "This text is inside a section."
ELSE
DO "This text is not inside a section."
How can I make a conditional that checks if it is currently inside a \part, \chapter, or \section?
IF inside sectioning = TRUE
DO "This text is inside a section."
ELSE
DO "This text is not inside a section."
\documentclass{article}
\newcount\Level
\let\Part=\part\def\part{\global\Level=0\Part}
\let\Chapter=\chapter\def\chapter{\global\Level=1\Chapter}
\let\Section=\section\def\section{\global\Level=2\Section}
\let\Subsection=\subsection\def\subsection{\global\Level=3\Subsection}
\let\Subsubsection=\subsubsection\def\subsubsection{\global\Level=4\Subsubsection}
\def\levelText{i am inside a
\ifcase\the\Level part
\or chapter
\or section
\or subsection
\or subsubsection
\else default text \fi}
\begin{document}
\part{foo}
\levelText
\section{bar}
\levelText
\subsection{baz}
\levelText
\end{document}

\Part, \Chapter, etc instructions, I suggest you encase the five \let... instructions inside \makeatletter ... \makeatother and endow each of the uppercase-letter macros with an @ symbol.
– Mico
Nov 12 '11 at 12:50
ConTeXt provides system modes *section, *subsection, etc that are active inside section heads. For example
\def\CheckSection
{\doifmodeelse{*section}
{inside section}
{outside section}}
\def\CheckSubSection
{\doifmodeelse{*subsection}
{inside subsection}
{outside subsection}}
\setuppapersize[A7]
\starttext
\section{Test \CheckSection\ \CheckSubSection}
Test \CheckSection\ \CheckSubSection
\subsection{Test \CheckSection\ \CheckSubSection}
Test \CheckSection\ \CheckSubSection
\stoptext
gives

Note that these modes are inactive when displaying table of contents. If you want to check if you are inside a table of contents (or list, in ConTeXt terminology), check for *list mode. Similarly, you can check for *marking mode to see if you are inside a marking (header or footer), and check for *register to see if you are inside a register (index, etc.).
If your problem is related to this other question from you and consists in providing automatically the \protect before \fbox, you can simply say
\usepackage{etoolbox}
\robustify{\fbox}
so that any later usage of \fbox won't require the \protect even inside moving arguments such as a section title.
\section{blah blah \mymacro{<stuff>} blah blah}where<stuff>is evaluated in a certain way depending on whether you're in a\sectionor not. Better yet, provide a more detailed description of the setting using a code example that forms part of a standard document. – Werner Nov 12 '11 at 08:28.tocfile so that it appears in the ToC. It might also be used for PDF bookmarks in a similar way. I assume you want to have this conditional to test for potential problems with the expansion when written to the.auxfile, right? – Martin Scharrer Nov 12 '11 at 08:30