Detect beginning of a sentence in a macro for capitalization
You could set the \sfcode of the "end of sentence" chars to something different and test for it:
\documentclass[10pt]{report}
\sfcode`\.=1001
\sfcode`\?=1001
\sfcode`\!=1001
\sfcode`\:=1001
\newcommand\secname{\ifnum\spacefactor=1001 Secname\else secname\fi}
\begin{document}
abc. \secname\ is \secname.
e.g.\@ \secname
\end{document}
\nonfrenchspacing is also setting the \sfcodes. In this case you could use something like this:
\documentclass[10pt]{report}
\nonfrenchspacing
\newcommand\secname{\ifnum\spacefactor>1900 Secname\else secname\fi}
\begin{document}
abc. \secname\ is \secname.
abc: \secname, \secname.
e.g.\@ \secname
\end{document}
Easiest way is to define two macros:
\def\secname{section}
\def\Secname{Section}
It is a very difficult task to determine sentence boundaries and one of the hottest topics in Computational Linguistics. To do so properly you need to determine that in Dr. Who, for example, the period after the "Dr." does not end a sentence, so you need to parse for all abbreviations and when you think you test for the next letter to start with a capital letter, think of e.g. and all the Latin abbreviations we use.
Before Ulrike posted her nice answer that uses \spacefactor
, I had thought this would be impossible in TeX without redefining .
. Just for completeness: Here's my answer that does redefine .
(after making it active, which probably is not such a good idea). Note that you do not have to use \@
as in Ulrike's solution.
\documentclass{article}
\let\period.
\catcode`.=\active
\let\qwe\relax
\futurelet\myspace{ }
\newcommand.{\period\futurelet\nextchar\testspace}
\newcommand\testspace{\ifx\nextchar\myspace\expandafter\eatspace\expandafter.\fi}
\def\eatspace. { \futurelet\nextchar\testsec}
\newcommand\testsec{\ifx\nextchar\secname\def\qwe{ }\fi}
\newcommand\secname{\ifx\qwe\relax section\else Section\let\qwe\relax\fi}
\begin{document}
abc. \secname\ is \secname.
abc: \secname, e.g.\ \secname.
\end{document}
Yes, This looks as if I had I tried to make it as obscure as possible. Two interesting points: 1. Note the definition of \myspace
(\space
does not work!). 2. I didn't manage to use LaTeX's \ifnextchar
to test if the next character is a space, so I used \futurelet
.