2

I am trying to understand a behavior where section headers assume the color of the first word in the section.

Here is my MWE:

\documentclass{minimal}    
\usepackage{xcolor}    
\makeatletter
\newcommand\section{\@startsection{section}{1}{.25in}%
                                    {1.3ex \@plus .5ex \@minus .2ex}%
                                    {-.5em \@plus -.1em}%
                  {\reset@font\normalsize\bfseries}}
\makeatother    
\begin{document}
\section{First}
{\color{red} Hello there} More text
\end{document}

The desired outcome is for "Hello there" to be red but the rest of the text (including "First") to be black. However, "First" is red. If a word is inserted before "{\color" then the desired behavior occurs. What is going on here? The answer must be some basic fact about latex that I don't know.

Many thanks in advance.

  • 1
    Simply use \textcolor{red}{Hello there} – Bernard Mar 4 '19 at 16:40
  • Thanks--it works. Why does it behave this way? – Zach Boyd Mar 4 '19 at 16:41
  • No idea. Anyway, personally, I use the titlesec package for this sort of modifications to the defaults, and I don't think you'd have this sort of problem. – Bernard Mar 4 '19 at 16:44
  • 2
    Without the negative vertical space the problem doesn't occur. (Just a debuging result to help you figuring out the problem... But I can't explain it... possibly this negative space says to latex to start coloring from the beginning of the line... If you knew a way to add the #1 argument of the section inside the command you could possibly solve the problem -that is the "why?"-) – koleygr Mar 4 '19 at 16:54
  • That is very interesting--definitely a useful lead. – Zach Boyd Mar 4 '19 at 16:55
2

First, let say that the issue have nothing to do with the definition of \section. So the problem is not here, but in using \color{red}... instead of \textcolor{red}{...}.

Here is a MWE that replicate the issue

\documentclass{article}    
\usepackage{color}    

\begin{document}
\paragraph{Foo}
{\color{red}Bar} bla bla
\end{document}

Why?

When the fifth argument of \@startsection is negatif the heading is prepended to the paragraph of following text with the \everypar command. The command \everypar is executed in horizontal mode i.e. when TeX see the character H in Hello, but at this moment is too late and the color change is already done. Here is another exemple

\documentclass{article}    
\usepackage{color}    

\begin{document}
\everypar{Foo \everypar{}}
{\color{red}\ifvmode\hrule\vskip1cm\fi Bar} bla bla
\end{document}

The solution is to use \textcolor{red}{...} or \leavevmode{\color{red}...}.

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.