From this answer, I tweaked it a little bit to redefine \section as follows:
\let\oldsection\section
\renewcommand{\section}[1]%
{
\begin{tcolorbox}
[
colback=gray!50!white,% background
colframe=gray!50!white,% frame colour
coltext=black, % text color
width=\linewidth,%
height=0.7cm,
halign=left,
valign=center,
fontupper=\large\bfseries,
arc=0mm, auto outer arc,
]
{\stepcounter{section}\arabic{section}$\,|\quad$ #1}
\end{tcolorbox}
}
However, the moment I use \tableofcontents, it does not work as expected (I am using an article class, by the way.)
Then, by scanning article.cls, the definition of \tableofcontents is as follows:
\newcommand\tableofcontents{%
\section*{\contentsname
\@mkboth{%
\MakeUppercase\contentsname}{\MakeUppercase\contentsname}}%
\@starttoc{toc}%
}
I tried replacing \section with \oldsection, but it does not work. Can someone help, please?
Edit: MWE
\NeedsTeXFormat{LaTeX2e}
\ProvidesPackage{sample}
\RequirePackage{letltxmacro, tcolorbox}
\LetLtxMacro{\oldsection}{\section}
\renewcommand{\section}[1]%
{
\begin{tcolorbox}
[
colback=gray!50!white,% background
colframe=gray!50!white,% frame colour
coltext=black, % text color
width=\linewidth,%
height=0.7cm,
halign=left,
valign=center,
fontupper=\large\bfseries,
arc=0mm, auto outer arc,
]
{\stepcounter{section}\arabic{section}$,|\quad$ #1}
\end{tcolorbox}
}
\renewcommand\tableofcontents{%
\oldsection*{\contentsname
@mkboth{%
\MakeUppercase\contentsname}{\MakeUppercase\contentsname}}%
@starttoc{toc}%
}
\endinput
\documentclass[letterpaper, 10pt]{article}
\usepackage{sample}
\begin{document}
\tableofcontents
\section{I}
\subsection{1}
\subsection{2}
\section{II}
\subsection{1}
\subsection{2}
\end{document}
Edit: Used \LetLtxMacro instead of \let
\sectioncommand takes an optional argument, which determines what's written to the aux file (and eventually to the toc file, which is where the contents of the Table of Contents are assembled). If left blank, the optional argument of\sectiondefaults to the command's mandatory argument. Your redefinition of\section, however, guarantees that nothing is written to the aux file. Was that deliberate? – Mico Mar 29 '21 at 07:10\newcommand\section{\@startsection {section}{1}{\z@}{-3.5ex \@plus -1ex\@minus -.2ex}{2.3ex \@plus.2ex}{\normalfont\Large\bfseries}}– soupless Mar 29 '21 at 07:12\@startsection(contained in the filelatex.ltx, the LaTeX "kernel"), you'll find (for unstarred section-like commands), the instruction\@dblarg{\@sect{#1}{#2}{#3}{#4}{#5}{#6}}, where\@sect, finally, contains the instruction\addcontentsline{toc}{#1}{...}. Unfortunately, this setup was not designed to be easy to adjust. I recommend you look into the capabilities of thetitlesecandsectstyfor solutions that are feasible in finite time. – Mico Mar 29 '21 at 07:21