You could instead wrap your definition for \chapter
inside an \@ifundefined
(note to enclose this with \makeatletter ... \makeatother
).
\makeatletter
\@ifundefined{chapter}{}{
\titleformat{\chapter}[hang]
{\centering\bfseries\huge}
{}
{0pt}
{\titlerule[0.8pt]}[]
\titlespacing{\chapter}
{0pt}
{0pt}
{0pt}[0pt]
}
\makeatother
This way, you can keep the \chapter
style independently of the documentclass.
Clarification: This solution was never meant to provide the \chapter
command for article
class, but to keep the \chapter
style redefinitions regardless of the document class used.
As @UlrikeFischer mentioned, article
does not provide \chapter
, and this is for a reason, which also justifies the existence of book
and report
.
I personally find it very wrong to provide chapters in articles.
However, as OP asked, one can use titlesec
and titletoc
to define a \chapter
command. This could be done as follows (I tried to be close to the original, might not be perfect):
\documentclass{article}
\usepackage{titlesec}
\usepackage{titletoc}
\newcommand{\chaptername}{Chapter}
\makeatletter
\newcommand{\@chapapp}{\chaptername}
\makeatother
\titleclass{\chapter}{top}[\part]
\newcounter{chapter}
\titleformat{\chapter}[display]
{\bfseries\huge}
{\chaptertitlename\space\thechapter}
{20pt}
{\Huge\bfseries}
\titlespacing*{\chapter}
{0pt}
{50pt}
{40pt}
\titlecontents{chapter}
[1.5em]
{\vspace*{10pt}\bfseries}
{\contentslabel{1.3em}}
{\hspace*{-1.3em}}
{\hfill\contentspage}
\AddToHook{cmd/appendix/before}{
\setcounter{chapter}{0}
\gdef{\thechapter}{\Alph{chapter}}
}
\begin{document}
\chapter{A}
\end{document}
Note however that this is wrong on many levels.
For example, the book
and report
classes use \chapter*
to automatically issue the headings of \tableofcontents
, \begin{thebibliography}{...}
, \printindex
, etc., while the article
class uses \section*
for this.
Moreover, I have not accounted for markings which are used in the header of each page (similar to other information like page number).
The book
and report
classes define \chaptermark
for this, but obviously article
does not have that.
\documentclass{report}
or\documentclass{book}
does fix the issue! I did not know that thearticle
class has no support for chapters. Thank you! Would you mind writing an answer so that I can mark this question as answered?