\ProvidesPackage{kao}

%----------------------------------------------------------------------------------------
%	DECLARE KAO
%----------------------------------------------------------------------------------------

\DefineFamily{kao}% Define the family name
\DefineFamilyMember{kao}% Add a member to the family
\DefineFamilyKey{kao}{secnumdepth}[1]{\setcounter{secnumdepth}{#1}\FamilyKeyStateProcessed}% Define a key and a default value
\FamilyProcessOptions{kao}% Process the options

%----------------------------------------------------------------------------------------
%	USEFUL PACKAGES AND COMMANDS
%----------------------------------------------------------------------------------------

\RequirePackage{kvoptions} % Handle package options
\RequirePackage{etoolbox} % Easy programming to modify TeX stuff
\RequirePackage{calc} % Make calculations
\RequirePackage[usenames,dvipsnames,table]{xcolor} % Colours
\RequirePackage{iftex} % Check whether XeTeX is being used
\RequirePackage{xifthen} % Easy conditionals
\RequirePackage{options} % Manage class options
\RequirePackage{xparse} % Parse arguments for macros
\RequirePackage{xpatch} % Patch LaTeX code in external packages
\RequirePackage{xstring} % Parse strings
\RequirePackage{afterpage} % Run commands after specific pages
\RequirePackage{imakeidx} % For the index; must be loaded before the 'caption' and 'hyperref' packages
\RequirePackage{varioref} % For the cross-references; must be loaded before the 'hyperref' and 'cleveref' packages
\AtEndPreamble{\RequirePackage{scrhack}} % Make some packages compatible with KOMAScript

% Define \Ifthispageodd (with a capital 'i') to make kaobook compatible with older KOMAScript versions
\@ifpackagelater{scrbase}{2019/12/22}{%
}{%
	\let\Ifthispageodd\ifthispageodd%
}

%----------------------------------------------------------------------------------------
%	KAO-SPECIFIC OPTIONS
%----------------------------------------------------------------------------------------

% Set up the package options
\SetupKeyvalOptions{
	family = kao,
	prefix = kao@
}

% https://tex.stackexchange.com/questions/47576/combining-ifxetex-and-ifluatex-with-the-logical-or-operation
% Introduce a command to find out whether the compiler is XeTeX or LuaTeX
\newif\ifxetexorluatex
\ifxetex
	\xetexorluatextrue
\else
	\ifluatex
		\xetexorluatextrue
	\else
		\xetexorluatexfalse
	\fi
\fi

\ifxetexorluatex
	\newcommand{\kao@defaultfontmethod}{modern}
\else
	\newcommand{\kao@defaultfontmethod}{tex}
\fi

% Set default based on rendering engine
\DeclareStringOption[\kao@defaultfontmethod]{fontmethod}

\ProcessKeyvalOptions{kao}

%----------------------------------------------------------------------------------------
%	TITLE AND AUTHOR MACROS
%----------------------------------------------------------------------------------------

% Provide an optional argument to the \title command in which to store a plain text title, without any formatting
% Usage: \title[Plain Title]{Actual Title}
\newcommand{\@plaintitle}{}
\renewcommand{\title}[2][]{%
	\gdef\@title{#2} % Store the full title in @title
	\ifthenelse{\isempty{#1}}{ % If there is no plain title
		\renewcommand{\@plaintitle}{\@title} % Use full title
	}{ % If there is a plain title
		\renewcommand{\@plaintitle}{#1} % Use provided plain-text title
	}%
	\hypersetup{pdftitle={\@plaintitle}} % Set the PDF metadata title
}

% Provide an optional argument to the \author command in which to store a plain text author, without any formatting
% Usage: \author[Plain Author]{Actual Author}
\newcommand{\@plainauthor}{}
\renewcommand{\author}[2][]{%
	\gdef\@author{#2} % Store the full author in @author
	\ifthenelse{\isempty{#1}}{ % If there is no plain author
		\renewcommand{\@plainauthor}{\@author}% Use full author
	}{ % If there is a plain author
		\renewcommand{\@plainauthor}{#1}% Use provided plain-text author
	}%
	\hypersetup{pdfauthor={\@plainauthor}} % Set the PDF metadata author
}

% Make a bookmark to the title page
\pretocmd{\maketitle}{\pdfbookmark[1]{\@plaintitle}{title}}{}{}%

%----------------------------------------------------------------------------------------
%	PAGE LAYOUT
%----------------------------------------------------------------------------------------

% Define lengths to set the scale of the document. Changing these 
% lengths should affect all the other pagesize-dependent elements in the 
% layout, such as the geometry of the page, the spacing between 
% paragraphs, and so on. (As of now, not all the elements rely on hscale 
% and vscale; future work will address this shortcoming.)
\newlength{\hscale}
\newlength{\vscale}

% By default, the scales are set to work for a4paper
\setlength{\hscale}{1mm}
\setlength{\vscale}{1mm}

% Define hscale and vscale for all types of paper
\@ifclasswith{\@baseclass}{a0paper}{\setlength{\hscale}{4mm}\setlength{\vscale}{4mm}}{}
\@ifclasswith{\@baseclass}{a1paper}{\setlength{\hscale}{2.828mm}\setlength{\vscale}{2.828mm}}{}
\@ifclasswith{\@baseclass}{a2paper}{\setlength{\hscale}{2mm}\setlength{\vscale}{2mm}}{}
\@ifclasswith{\@baseclass}{a3paper}{\setlength{\hscale}{1.414mm}\setlength{\vscale}{1.414mm}}{}
\@ifclasswith{\@baseclass}{a4paper}{\setlength{\hscale}{1mm}\setlength{\vscale}{1mm}}{}
\@ifclasswith{\@baseclass}{a5paper}{\setlength{\hscale}{0.704mm}\setlength{\vscale}{0.704mm}}{}
\@ifclasswith{\@baseclass}{a6paper}{\setlength{\hscale}{0.5mm}\setlength{\vscale}{0.5mm}}{}
\@ifclasswith{\@baseclass}{b0paper}{\setlength{\hscale}{4.761mm}\setlength{\vscale}{4.761mm}}{}
\@ifclasswith{\@baseclass}{b1paper}{\setlength{\hscale}{3.367mm}\setlength{\vscale}{3.367mm}}{}
\@ifclasswith{\@baseclass}{b2paper}{\setlength{\hscale}{2.380mm}\setlength{\vscale}{2.380mm}}{}
\@ifclasswith{\@baseclass}{b3paper}{\setlength{\hscale}{1.681mm}\setlength{\vscale}{1.681mm}}{}
\@ifclasswith{\@baseclass}{b4paper}{\setlength{\hscale}{1.190mm}\setlength{\vscale}{1.190mm}}{}
\@ifclasswith{\@baseclass}{b5paper}{\setlength{\hscale}{0.837mm}\setlength{\vscale}{0.837mm}}{}
\@ifclasswith{\@baseclass}{b6paper}{\setlength{\hscale}{0.570mm}\setlength{\vscale}{0.570mm}}{}
\@ifclasswith{\@baseclass}{c0paper}{\setlength{\hscale}{4.367mm}\setlength{\vscale}{4.367mm}}{}
\@ifclasswith{\@baseclass}{c1paper}{\setlength{\hscale}{3.085mm}\setlength{\vscale}{3.085mm}}{}
\@ifclasswith{\@baseclass}{c2paper}{\setlength{\hscale}{2.180mm}\setlength{\vscale}{2.180mm}}{}
\@ifclasswith{\@baseclass}{c3paper}{\setlength{\hscale}{1.542mm}\setlength{\vscale}{1.542mm}}{}
\@ifclasswith{\@baseclass}{c4paper}{\setlength{\hscale}{1.090mm}\setlength{\vscale}{1.090mm}}{}
\@ifclasswith{\@baseclass}{c5paper}{\setlength{\hscale}{0.771mm}\setlength{\vscale}{0.771mm}}{}
\@ifclasswith{\@baseclass}{c6paper}{\setlength{\hscale}{0.542mm}\setlength{\vscale}{0.542mm}}{}
\@ifclasswith{\@baseclass}{b0j}{\setlength{\hscale}{4.904mm}\setlength{\vscale}{4.904mm}}{}
\@ifclasswith{\@baseclass}{b1j}{\setlength{\hscale}{3.467mm}\setlength{\vscale}{3.467mm}}{}
\@ifclasswith{\@baseclass}{b2j}{\setlength{\hscale}{2.452mm}\setlength{\vscale}{2.452mm}}{}
\@ifclasswith{\@baseclass}{b3j}{\setlength{\hscale}{1.733mm}\setlength{\vscale}{1.733mm}}{}
\@ifclasswith{\@baseclass}{b4j}{\setlength{\hscale}{1.226mm}\setlength{\vscale}{1.226mm}}{}
\@ifclasswith{\@baseclass}{b5j}{\setlength{\hscale}{0.867mm}\setlength{\vscale}{0.867mm}}{}
\@ifclasswith{\@baseclass}{b6j}{\setlength{\hscale}{0.613mm}\setlength{\vscale}{0.613mm}}{}
\@ifclasswith{\@baseclass}{ansiapaper}{\setlength{\hscale}{1.028mm}\setlength{\vscale}{0.939mm}}{}
\@ifclasswith{\@baseclass}{ansibpaper}{\setlength{\hscale}{1.328mm}\setlength{\vscale}{1.454mm}}{}
\@ifclasswith{\@baseclass}{ansicpaper}{\setlength{\hscale}{2.057mm}\setlength{\vscale}{1.882mm}}{}
\@ifclasswith{\@baseclass}{ansidpaper}{\setlength{\hscale}{2.662mm}\setlength{\vscale}{2.909mm}}{}
\@ifclasswith{\@baseclass}{ansiepaper}{\setlength{\hscale}{4.114mm}\setlength{\vscale}{3.764mm}}{}
\@ifclasswith{\@baseclass}{letterpaper}{\setlength{\hscale}{1.028mm}\setlength{\vscale}{0.939mm}}{}
\@ifclasswith{\@baseclass}{executivepaper}{\setlength{\hscale}{0.876mm}\setlength{\vscale}{0.898mm}}{}
\@ifclasswith{\@baseclass}{legalpaper}{\setlength{\hscale}{1.028mm}\setlength{\vscale}{1.198mm}}{}
\@ifclasswith{\@baseclass}{smallpocketpaper}{\setlength{\hscale}{0.571mm}\setlength{\vscale}{0.639mm}}{}
\@ifclasswith{\@baseclass}{pocketpaper}{\setlength{\hscale}{0.642mm}\setlength{\vscale}{0.723mm}}{}
\@ifclasswith{\@baseclass}{juvenilepaper}{\setlength{\hscale}{0.738mm}\setlength{\vscale}{0.740mm}}{}
\@ifclasswith{\@baseclass}{smallphotopaper}{\setlength{\hscale}{0.809mm}\setlength{\vscale}{0.572mm}}{}
\@ifclasswith{\@baseclass}{photopaper}{\setlength{\hscale}{1.00mm}\setlength{\vscale}{0.707mm}}{}
\@ifclasswith{\@baseclass}{appendixpaper}{\setlength{\hscale}{1.000mm}\setlength{\vscale}{0.505mm}}{}
\@ifclasswith{\@baseclass}{cookpaper}{\setlength{\hscale}{0.809mm}\setlength{\vscale}{0.740mm}}{}
\@ifclasswith{\@baseclass}{illustratedpaper}{\setlength{\hscale}{0.905mm}\setlength{\vscale}{0.909mm}}{}
\@ifclasswith{\@baseclass}{f24paper}{\setlength{\hscale}{0.762mm}\setlength{\vscale}{0.808mm}}{}
\@ifclasswith{\@baseclass}{a4paperlandscape}{\setlength{\hscale}{1.414mm}\setlength{\vscale}{0.707mm}}{}
\@ifclasswith{\@baseclass}{169paperlandscape}{\setlength{\hscale}{1.414mm}\setlength{\vscale}{0.562mm}}{}

% Set the default page layout
\RequirePackage[
	paperwidth=210\hscale,
	paperheight=297\vscale,
]{geometry}

% Command to choose among the three possible layouts
\DeclareDocumentCommand{\pagelayout}{m}{%
	\ifthenelse{\equal{margin}{#1}}{\marginlayout\marginfloatsetup}{}%
	\ifthenelse{\equal{wide}{#1}}{\widelayout\widefloatsetup}{}%
	\ifthenelse{\equal{fullwidth}{#1}}{\fullwidthlayout\widefloatsetup}{}%
}

\newif\ifwidelayout%
\def\IfWideLayout{%
	\ifwidelayout%
		\expandafter\@firstoftwo%
	\else%
		\expandafter\@secondoftwo%
	\fi%
}

% Layout #1: large margins
\newcommand{\marginlayout}{%
	\newgeometry{
		top=27.4\vscale,
		bottom=27.4\vscale,
		inner=24.8\hscale,
		textwidth=107\hscale,
		marginparsep=6.2\hscale,
		marginparwidth=47.7\hscale,
	}%
	\recalchead%
	\widelayoutfalse%
}

% Layout #2: small, symmetric margins
\newcommand{\widelayout}{%
	\newgeometry{
		top=27.4\vscale,
		bottom=27.4\vscale,
		inner=24.8\hscale,
		outer=24.8\hscale,
		marginparsep=0mm,
		marginparwidth=0mm,
	}%
	\recalchead%
	\widelayouttrue%
}

% Layout #3: no margins and no space above or below the body
\newcommand{\fullwidthpage}{%
	\newgeometry{
		top=0mm,
		bottom=0mm,
		inner=0mm,
		outer=0mm,
		marginparwidth=0mm,
		marginparsep=0mm,
	}%
	\recalchead%
	\widelayouttrue%
}

% Set the default page layout
\AtBeginDocument{\pagelayout{margin}}

%----------------------------------------------------------------------------------------
%	HEADERS AND FOOTERS
%----------------------------------------------------------------------------------------

\RequirePackage{scrlayer-scrpage}		% Customise head and foot regions

% Set the header height to prevent a warning
%\setlength{\headheight}{27.4\vscale}
% Increase the space between header and text
\setlength{\headsep}{11\vscale}

% Define some LaTeX lengths used in the page headers
\newlength{\headtextwidth} % This is the width of the text
\newlength{\headmarginparsep} % This is the width of the whitespace between text and margin
\newlength{\headmarginparwidth} % This is the width of the margin
\newlength{\headtotal} % This is the total width of the header
\newlength{\contentwidth} % An alias for \headtotal
\newcommand{\recalchead}{% Command to recalculate the header-related length when needed
	\setlength{\headtextwidth}{\textwidth}%
	\setlength{\headmarginparsep}{\marginparsep}%
	\setlength{\headmarginparwidth}{\marginparwidth}%
	\setlength{\headtotal}{\headtextwidth+\headmarginparsep+\headmarginparwidth}%
	\setlength{\contentwidth}{\headtotal}%
}

\AtBeginDocument{% Recalculate the header-related lengths
	\recalchead%
}

% Header style with chapter number, chapter title, and page in the header (used throughout the document)
\renewpagestyle{scrheadings}{%
	{\smash{\hspace{-\headmarginparwidth}\hspace{-\headmarginparsep}\makebox[\headtotal][l]{%
					\makebox[7\hscale][r]{\thepage}%
					\makebox[3\hscale]{}\rule[-1mm]{0.5pt}{19\vscale-1mm}\makebox[3\hscale]{}%
					\makebox[\headtextwidth][l]{\leftmark}}}}%
		{\smash{\makebox[0pt][l]{\makebox[\headtotal][r]{%
						\makebox[\headtextwidth][r]{\hfill\rightmark}%
						\makebox[3\hscale]{}\rule[-1mm]{0.5pt}{19\vscale-1mm}\makebox[3\hscale]{}%
						\makebox[7\hscale][l]{\thepage}}}}}%
		{\smash{\makebox[0pt][l]{\makebox[\headtotal][r]{%
						\makebox[\headtextwidth][r]{\hfill\rightmark}%
						\makebox[3\hscale]{}\rule[-1mm]{0.5pt}{19\vscale-1mm}\makebox[3\hscale]{}%
						\makebox[7\hscale][l]{\thepage}}}}}%
}{%
	{}%
		{}%
		{}%
}

% Header style with neither header nor footer (used for special pages)
\renewpagestyle{plain.scrheadings}{%
	{}%
		{}%
		{}%
}{%
	{}%
		{}%
		{}%
}

% Header style with an empty header and the page number in the footer
\newpagestyle{pagenum.scrheadings}{%
	{}%
		{}%
		{}%
}{%
	{\makebox[\textwidth][r]{\thepage}}%
		{\makebox[\textwidth][l]{\thepage}}%
		{\makebox[\textwidth][l]{\thepage}}%
}

% Header style with an empty header and the page number in the footer
\newpagestyle{centeredpagenum.scrheadings}{%
	{}%
		{}%
		{}%
}{%
	{\hspace{-\headmarginparwidth}\hspace{-\headmarginparsep}\makebox[\headtotal][l]{\hfill\thepage\hfill}}
		{\makebox[0pt][l]{\makebox[\headtotal][r]{\hfill\thepage\hfill}}}%
		{\makebox[0pt][l]{\makebox[\headtotal][r]{\hfill\thepage\hfill}}}%
}

% Command to print a blank page
\newcommand\blankpage{%
	\null%
	\thispagestyle{empty}%
	\newpage%
}

% Set the default page style
\pagestyle{plain.scrheadings}

%----------------------------------------------------------------------------------------
%	PARAGRAPH FORMATTING
%----------------------------------------------------------------------------------------

\RequirePackage{ragged2e} % Required to achieve better ragged paragraphs
\RequirePackage{setspace} % Required to easily set the space between lines
\RequirePackage{hyphenat} % Hyphenation for special fonts
\RequirePackage{microtype} % Improves character and word spacing
\RequirePackage{needspace} % Required to prevent page break right after a sectioning command
\RequirePackage{xspace} % Better print trailing whitespace

% TODO: recognize space/indent justified/raggedright class options

% Settings for a normal paragraph
\newcommand{\@body@par}{%
	\justifying% Justify text
	\singlespacing% Set the interline space to a single line
	\frenchspacing% No additional space after periods
	\normalfont% Use the default font
	\normalsize% Use the default size
}

% Settings for paragraphs in the margins
\newcommand{\@margin@par}{%
	\justifying% justify text
	\setlength{\RaggedRightParindent}{0em}% Suppress indentation
	\setlength{\parindent}{0em}% Suppress indentation
	\setlength{\parskip}{0.5pc}% Set the space between paragraphs
	%\singlespacing% Set the space between lines
	\frenchspacing% No additional space after periods
	\normalfont% Use the default font
	\footnotesize% Use a smaller size
}

% By default, use @body@par settings
\@body@par

%----------------------------------------------------------------------------------------
%	WIDE PARAGRAPHS
%----------------------------------------------------------------------------------------

% Environment for a wide paragraph
\NewDocumentEnvironment{widepar}{}{%
	\if@twoside%
	\Ifthispageodd{%
		\begin{addmargin}[0cm]{-\marginparwidth-\marginparsep}%
	}{%
		\begin{addmargin}[-\marginparwidth-\marginparsep]{0cm}%
	}%
	\else%
	\begin{addmargin}[0cm]{-\marginparwidth-\marginparsep}%
		\fi%
		}{%
	\end{addmargin}%
}

% Environment for a full width paragraph
\NewDocumentEnvironment{fullwidthpar}{}{%
	\if@twoside%
	\Ifthispageodd{%
		\begin{addmargin}[-1in-\hoffset-\oddsidemargin]{-\paperwidth+1in+\hoffset+\oddsidemargin+\textwidth}%
	}{%
		\begin{addmargin}[-\paperwidth+1in+\hoffset+\oddsidemargin+\textwidth]{-\paperwidth+1in+\hoffset+\oddsidemargin+\marginparsep+\marginparwidth+\textwidth}%
	}%
	\else%
	\begin{addmargin}[-1in-\hoffset-\oddsidemargin]{-\paperwidth+1in+\hoffset+\oddsidemargin+\textwidth}%
		\fi% 
		}{%
	\end{addmargin}%
}

% Environment for a wide equation
\NewDocumentEnvironment{wideequation}{}{%
	\begin{widepar}%
		\begin{equation}%
			}{%
		\end{equation}%
	\end{widepar}%
}

%----------------------------------------------------------------------------------------
%	FOOTNOTES, MARGINNOTES AND SIDENOTES
%----------------------------------------------------------------------------------------

\RequirePackage[section]{placeins} % Prevent floats to cross sections
\extrafloats{100} % Require more floats

\RequirePackage{marginnote} % Provides options for margin notes
%\RequirePackage{marginfix} % Make marginpars float freely; it should not be loaded as it prevents the marginnotes to stay aligned with the main text
\RequirePackage{sidenotes} % Use sidenotes
\RequirePackage{chngcntr} % Reset counters at sections

% TODO: see also page 440 of the KOMA-script guide
\RequirePackage[
	bottom,
	symbol*,
	hang,
	flushmargin,
	% perpage,
	stable,
]{footmisc} % Required to set up the footnotes
\RequirePackage{footnotebackref} % Creates back references from footnotes to text

% Fix the color of the footnote marker when back-referenced
\patchcmd{\footref}{\ref}{\hypersetup{colorlinks=black}\ref}{}{}%
% Workaround to fix back references
\edef\BackrefFootnoteTag{bhfn:\theBackrefHyperFootnoteCounter}%

% FIXME: I am not able to choose the paragraph layout of footnotes, probably the footnotes package conflicts with scrbook.
%\renewcommand{\footnotelayout}{\@margin@par}

%----------------------------------------------------------------------------------------

% Justify and format margin notes
\renewcommand*{\raggedleftmarginnote}{} % Suppress left margin
\renewcommand*{\raggedrightmarginnote}{} % Suppress right margin
\renewcommand*{\marginfont}{\@margin@par} % Format marginnotes according to \@marginpar (see above)
\renewcommand{\marginnotevadjust}{0.8\vscale} % Bring all marginnotes downwards a bit
%\marginposadjustment=1\vscale % Bring downwards also the marginpars
%\marginheightadjustment=10cm % Adjust the height of the margins for each page
%\RequirePackage[marginnote=true]{snotez} % Provides options for sidenotes

% Copied from snotez's \sidenote
\def\kao@if@nblskip#1{%
	\expandafter\ifx\@car#1\@nil*%
		\expandafter\@firstoftwo%
	\else%
		\expandafter\@secondoftwo%
	\fi%
}

% Command to detect whether we are inside a tcolorbox environment
\newif\ifinfloat % First, set this flag whenever we are in a tcolorbox environment...
\AtBeginEnvironment{tcolorbox}{\infloattrue\renewcommand{\marginnotevadjust}{-1.4\vscale}}
\AtBeginEnvironment{minipage}{\infloattrue}

\def\IfInFloatingEnvir{% ...Then, detect the flag
	\ifinfloat%
		\expandafter\@firstoftwo%
	\else%
		\expandafter\@secondoftwo%
	\fi%
}


% Redefine the command to print marginnotes:
% (a) the optional offset argument goes at the first position
% (b) the offset can also be a multiple of baselineskip, like for snotez's \sidenote
% Usage: \marginnote[<offset>]{Text of the note.}
\let\oldmarginnote\marginnote%
\RenewDocumentCommand\marginnote{ o m }{%
	\IfNoValueOrEmptyTF{#1}{%
		\IfInFloatingEnvir{%
			\oldmarginnote{#2}%
		}{%
			\marginpar{\@margin@par#2}%
		}%
	}{%
		\oldmarginnote{#2}[\kao@if@nblskip{#1}{\@cdr#1\@nil\baselineskip}{#1}]%
	}%
}

% Initially set the sidenote counter to zero instead of 1, and update it before printing the sidenote.
\setcounter{sidenote}{0}%
\RenewDocumentCommand\sidenote{ o o +m }{%
	\IfNoValueOrEmptyTF{#1}{%
		\refstepcounter{sidenote}% This command has been moved here
	}{%
	}%
	\sidenotemark[#1]%
	\sidenotetext[#1][#2]{#3}%
	\@sidenotes@multimarker%
}

% Formatting sidenote markers
\RenewDocumentCommand\@sidenotes@thesidenotemark{ m }{% Format the marker
	\leavevmode%
	\ifhmode%
		\edef\@x@sf{\the\spacefactor}%
		\nobreak%
	\fi%
	\hbox{\@textsuperscript{\normalfont#1}}%
	\ifhmode%
		\spacefactor\@x@sf%
	\fi%
	\relax%
}%

% Formatting the sidenote text
\RenewDocumentCommand\sidenotetext{ o o +m }{% number, offset, text
	\IfNoValueOrEmptyTF{#1}{%
		\marginnote[#2]{\thesidenote:\enskip#3}%
	}{%
		\marginnote[#2]{#1:\enskip#3}%
	}%
}

%----------------------------------------------------------------------------------------
%	FIGURES, TABLES, LISTINGS AND CAPTIONS
%----------------------------------------------------------------------------------------

\RequirePackage{graphicx} % Include figures
\setkeys{Gin}{width=\linewidth,totalheight=\textheight,keepaspectratio} % Improves figure scaling
\RequirePackage{tikz} % Allows to draw custom shapes
\RequirePackage{tikzpagenodes} % Allows to anchor tikz nodes to page elements
\RequirePackage{booktabs} % Nicer tables
\RequirePackage{multirow} % Cells occupying multiple rows in tables
\RequirePackage{multicol} % Multiple columns in dictionary
\RequirePackage{rotating} % Allows tables and figures to be rotated
\RequirePackage{listings} % Print code listings
%\RequirePackage{minted}
\RequirePackage[hypcap=true]{caption} % Correctly placed anchors for hyperlinks
% \RequirePackage{atbegshi}
% \RequirePackage{perpage}
\let\c@abspage\relax
% \newcommand{\pp@g@sidenote}{}
\RequirePackage{floatrow} % Set up captions of floats
%\RequirePackage{dblfloatfix} % Better positioning of wide figures and tables

% Improve the figure placing (see https://www.overleaf.com/learn/latex/Tips)
\def\topfraction{.9}%
\def\textfraction{0.35}%
\def\floatpagefraction{0.8}%

% Set the space between floats and main text
\renewcommand\FBaskip{.4\topskip}%
\renewcommand\FBbskip{\FBaskip}%

% Tighten up space between displays (e.g., equations) and make symmetric (from tufte-latex)
\setlength\abovedisplayskip{6pt plus 2pt minus 4pt}%
\setlength\belowdisplayskip{6pt plus 2pt minus 4pt}%
\abovedisplayskip 10\p@ \@plus2\p@ \@minus5\p@%
\abovedisplayshortskip \z@ \@plus3\p@%
\belowdisplayskip \abovedisplayskip%
\belowdisplayshortskip 6\p@ \@plus3\p@ \@minus3\p@%

\setlength\columnseprule{.4pt} % Set the width of vertical rules in tables

% The marginfix package prevents the margin notes to stay aligned with the main text, so it cannot be used. However, we define the \marginskip command, which is the only command we need from that package.
\newcommand\marginskip[1]{%
	\marginpar{\@margin@par\vspace{#1 - \baselineskip}}% We subtract the \baselineskip that we have in margin pars.
}

\newlength{\kaomarginskipabove} % Specify the space above a marginfigure, margintable or marginlisting
\newlength{\kaomarginskipbelow} % Specify the space below a marginfigure, margintable or marginlisting
\setlength{\kaomarginskipabove}{3mm plus 2pt minus 2pt}
\setlength{\kaomarginskipbelow}{3mm plus 2pt minus 2pt}

% Environment to hold a margin figure (from the sidenotes package)
% We redefine it here because we want to use our own caption formatting.
\RenewDocumentEnvironment{marginfigure}{o}{%
	\FloatBarrier%
	\marginskip{\kaomarginskipabove}%
	\begin{lrbox}{\@sidenotes@marginfigurebox}%
		\begin{minipage}{\marginparwidth}%
			\captionsetup{type=figure}%
			}{%
		\end{minipage}%
	\end{lrbox}%
	\marginnote[#1]{\usebox{\@sidenotes@marginfigurebox}}%
	\marginskip{\kaomarginskipbelow}%
}

% Environment to hold a margin table (from the sidenotes package)
\RenewDocumentEnvironment{margintable}{o}{%
	\FloatBarrier%
	\marginskip{\kaomarginskipabove}%
	\begin{lrbox}{\@sidenotes@margintablebox}%
		\begin{minipage}{\marginparwidth}%
			\captionsetup{type=table}%
			}{%
		\end{minipage}%
	\end{lrbox}%
	\marginnote[#1]{\usebox{\@sidenotes@margintablebox}}%
	\marginskip{\kaomarginskipbelow}%
}

% Environment to hold a margin listing
\newsavebox{\@sidenotes@marginlistingbox}%
\NewDocumentEnvironment{marginlisting}{o}{% The optional parameter is the vertical offset
	\FloatBarrier%
	\marginskip{\kaomarginskipabove}%
	\begin{lrbox}{\@sidenotes@marginlistingbox}%
		\begin{minipage}{\marginparwidth}%
			\captionsetup{type=lstlisting}%
			}{%
		\end{minipage}%
	\end{lrbox}%
	\marginnote[#1]{\usebox{\@sidenotes@marginlistingbox}}%
	\marginskip{\kaomarginskipbelow}%
}

% Change the position of the captions
\DeclareFloatSeparators{marginparsep}{\hskip\marginparsep}%

% Detect whether there is a caption in the current environment by switching the kaocaption toggle when \caption is called. If there is no caption, reset the floatsetup. Without this fix, the floatrow package will align the environment to the main text if there is a caption, but to the margin if there is no caption.
\newtoggle{kaocaption}
\AtBeginEnvironment{figure}{%
	\let\oldcaption\caption%
	\RenewDocumentCommand{\caption}{s o m}{%
		\IfBooleanTF{#1}{%
			\oldcaption*{#3}%
		}{%
			\IfValueTF{#2}{%
				\oldcaption[#2]{#3}%
			}{%
				\oldcaption{#3}%
			}%
		}%
		\toggletrue{kaocaption}%
	}%
}
\AtEndEnvironment{figure}{%
	\iftoggle{kaocaption}{%
	}{%
		\RawFloats%
		\centering%
	}%
	\togglefalse{kaocaption}%
}
\AtBeginEnvironment{table}{%
	\let\oldcaption\caption%
	\RenewDocumentCommand{\caption}{s o m}{%
		\IfBooleanTF{#1}{%
			\oldcaption*{#3}%
		}{%
			\IfValueTF{#2}{%
				\oldcaption[#2]{#3}%
			}{%
				\oldcaption{#3}%
			}%
		}%
		\toggletrue{kaocaption}%
	}%
}
\AtEndEnvironment{table}{%
	\iftoggle{kaocaption}{%
	}{%
		\RawFloats%
		\centering%
	}%
	\togglefalse{kaocaption}%
}

% Change the formatting of the captions
\addtokomafont{captionlabel}{\bfseries} % Bold font for the figure label
% Declare a new style to format the caption according to \@margin@par (see above)
\DeclareCaptionFormat{margin}{\@margin@par #1#2#3}
% Declare a new caption style for lstlistings
\newsavebox\mycap
\DeclareCaptionFormat{llap}{%
	\begin{lrbox}{\mycap}%
		\begin{minipage}{\marginparwidth}%
			\@margin@par #1:#2#3%
		\end{minipage}%
	\end{lrbox}%
	\marginnote[0.2cm]{\usebox\mycap}%
}
% Set the global caption style
\captionsetup{
	format=margin, % Use the style previously declared
	strut=no,%
	%hypcap=true, % Links point to the top of the figure
	singlelinecheck=false,%
	%width=\marginparwidth,
	indention=0pt, % Suppress indentation
	parindent=0pt, % Suppress space between paragraphs
	aboveskip=6pt, % Increase the space between the figure and the caption
	belowskip=6pt, % Increase the space between the caption and the table
}

% Needed to have continued figures and tables (https://en.wikibooks.org/wiki/LaTeX/Floats,_Figures_and_Captions#Figures_in_multiple_parts)
\DeclareCaptionLabelFormat{cont}{#1~#2\alph{ContinuedFloat}}
\captionsetup[ContinuedFloat]{labelformat=cont}

% Captions for the 'margin' layout
\NewDocumentCommand{\marginfloatsetup}{}{%
	\if@twoside%
		\floatsetup[figure]{% Captions for figures
			margins=hangoutside,% Put captions in the margins
			facing=yes,%
			capposition=beside,%
			capbesideposition={bottom,outside},%
			capbesideframe=yes,%
			capbesidewidth=\marginparwidth,% Width of the caption equal to the width of the margin
			capbesidesep=marginparsep,%
			floatwidth=\textwidth,% Width of the figure equal to the width of the text
		}%
		\floatsetup[widefigure]{% Captions for wide figures
			margins=hangoutside,% Put captions below the figure
			facing=yes,%
			capposition=bottom%
		}%
		\floatsetup[table]{% Captions for tables
			margins=hangoutside,% Put captions in the margin
			facing=yes,%
			capposition=beside,%
			capbesideposition={top,outside},%
			%capbesideposition=outside,
			capbesideframe=yes,%
			capbesidewidth=\marginparwidth,% Width of the caption equal to the width of the margin
			capbesidesep=marginparsep,%
			floatwidth=\textwidth,% Width of the figure equal to the width of the text
		}%
		\floatsetup[widetable]{% Captions for wide tables
			margins=hangoutside,% Put captions above the table
			facing=yes,%
			capposition=above%
		}%
		\floatsetup[longtable]{% Captions for longtables
			margins=raggedright,% Overwrite the hangright setting from the `table' environment
			%LTcapwidth=table,% Set the width of the caption equal to the table's
		}%
		\floatsetup[lstlisting]{% Captions for lstlistings
			margins=hangoutside,% Put captions in the margin
			facing=yes,%
			capposition=beside,%
			capbesideposition={top,outside},%
			%capbesideposition=outside,
			capbesideframe=yes,%
			capbesidewidth=\marginparwidth,% Width of the caption equal to the width of the margin
			capbesidesep=marginparsep,%
			floatwidth=\textwidth,% Width of the figure equal to the width of the text
		}%
		\floatsetup[listing]{% Captions for listings (minted package)
			margins=hangoutside,% Put captions in the margin
			facing=yes,%
			capposition=beside,%
			capbesideposition={top,outside},%
			%capbesideposition=outside,
			capbesideframe=yes,%
			capbesidewidth=\marginparwidth,% Width of the caption equal to the width of the margin
			capbesidesep=marginparsep,%
			floatwidth=\textwidth,%Width of the figure equal to the width of the text
		}%
		\captionsetup*[lstlisting]{%
			format=llap,%
			labelsep=space,%
			singlelinecheck=no,%
			belowskip=-0.6cm,%
		}%
	\else%
		\floatsetup[figure]{% Captions for figures
			margins=hangright,% Put captions in the margins
			facing=yes,%
			capposition=beside,%
			capbesideposition={bottom,right},%
			capbesideframe=yes,%
			capbesidewidth=\marginparwidth,% Width of the caption equal to the width of the margin
			capbesidesep=marginparsep,%
			floatwidth=\textwidth,% Width of the figure equal to the width of the text
		}%
		\floatsetup[widefigure]{% Captions for wide figures
			margins=hangright,% Put captions below the figure
			facing=no,%
			capposition=bottom%
		}%
		\floatsetup[table]{% Captions for tables
			margins=hangright,% Put captions in the margin
			facing=yes,%
			capposition=beside,%
			capbesideposition={top,right},%
			%capbesideposition=outside,
			capbesideframe=yes,%
			capbesidewidth=\marginparwidth,% Width of the caption equal to the width of the margin
			capbesidesep=marginparsep,%
			floatwidth=\textwidth,% Width of the figure equal to the width of the text
		}%
		\floatsetup[widetable]{% Captions for wide tables
			margins=hangright,% Put captions above the table
			facing=no,%
			capposition=above%
		}%
		\floatsetup[longtable]{% Captions for longtables
			margins=raggedright,% Overwrite the hangright setting from the `table' environment
			%LTcapwidth=table,% Set the width of the caption equal to the table's
		}%
		\floatsetup[lstlisting]{% Captions for lstlisting
			margins=hangright,% Put captions in the margin
			facing=yes,%
			capposition=beside,%
			capbesideposition={top,right},%
			%capbesideposition=outside,
			capbesideframe=yes,%
			capbesidewidth=\marginparwidth,% Width of the caption equal to the width of the margin
			capbesidesep=marginparsep,%
			floatwidth=\textwidth,% Width of the figure equal to the width of the text
		}%
		\floatsetup[listing]{% Captions for listing (minted package)
			margins=hangright,% Put captions in the margin
			facing=yes,%
			capposition=beside,%
			capbesideposition={top,right},%
			%capbesideposition=outside,
			capbesideframe=yes,%
			capbesidewidth=\marginparwidth,% Width of the caption equal to the width of the margin
			capbesidesep=marginparsep,%
			floatwidth=\textwidth,% Width of the figure equal to the width of the text
		}%
		\captionsetup*[lstlisting]{%
			format=llap,%
			labelsep=space,%
			singlelinecheck=no,%
			belowskip=-0.6cm,%
		}%
	\fi%
}

% Captions for the 'wide' layout
\NewDocumentCommand{\widefloatsetup}{}{%
	\floatsetup[figure]{ % Captions for figures
		capposition=bottom,%
		margins=centering,%
		floatwidth=\textwidth%
	}
	\floatsetup[widefigure]{ % Captions for wide figures
		margins=hangoutside, % Put captions below the figure
		facing=yes,%
		capposition=bottom%
	}
	\floatsetup[table]{ % Captions for tables
		capposition=above,%
		margins=centering,%
		floatwidth=\textwidth%
	}
	\floatsetup[widetable]{ % Captions for wide tables
		margins=hangoutside, % Put captions above the table
		facing=yes,%
		capposition=above%
	}
	\floatsetup[lstlisting]{ % Captions for lstlistings
		capposition=above,%
		margins=centering,%
		floatwidth=\textwidth%
	}
	\floatsetup[listing]{ % Captions for listings (minted package)
		capposition=above,%
		margins=centering,%
		floatwidth=\textwidth%
	}
	\captionsetup*[lstlisting]{% Captions style for lstlistings
		%format=margin,%
		labelsep=colon,%
		strut=no,%
		singlelinecheck=false,%
		indention=0pt,%
		parindent=0pt,%
		aboveskip=6pt,%
		belowskip=6pt,%
		belowskip=-0.1cm%
	}
}

%----------------------------------------------------------------------------------------
%	TOC, LOF & LOT
%----------------------------------------------------------------------------------------

\RequirePackage{tocbasic} % Required to customise the TOC

% Show an entry for the TOC in the TOC
\setuptoc{toc}{totoc}

% Choose the levels in table of contents
\setcounter{tocdepth}{\subsectiontocdepth}

% Customise the list of listings
\renewcommand{\lstlistlistingname}{List of Listings}% Change the title
\newcommand{\lstlistingtocdepth}{\sectiontocdepth}% Set the depth
\newcommand{\listoflistings}{\lstlistoflistings}% Provide the alias \listoflistings
\newcommand{\listoflstlistings}{\lstlistoflistings}% Provide the alias \listoflstlistings

% Define the style for toc entries
\@ifpackagelater{scrbase}{2019/10/11}{%
	\DeclareTOCStyleEntries[indent=0em,numwidth=2em,dynnumwidth=yes,pagenumberwidth=2.1em]{tocline}{figure,table,lstlisting}%
	\DeclareTOCStyleEntries[dynnumwidth=yes]{tocline}{subsubsection,subsection,section,chapter,part}%
	\DeclareTOCStyleEntries[pagenumberwidth=2.5em]{tocline}{chapter,part}%
	\DeclareTOCStyleEntries[pagenumberwidth=2.1em]{tocline}{subsubsection,subsection,section}%
}{%
	\DeclareTOCStyleEntries[indent=0em,numwidth=2em,dynnumwidth=yes]{tocline}{figure,table,lstlisting}%
	\DeclareTOCStyleEntries[dynnumwidth=yes]{tocline}{subsubsection,subsection,section,chapter,part}%
}

% Define the names for the headings
% \renewcaptionname{english}{\contentsname}{Detailed Contents}
% \renewcaptionname{english}{\listfigurename}{Figures}
% \renewcaptionname{english}{\listtablename}{Tables}
% \newcaptionname{english}{\listtheoremname}{Theorems}

%----------------------------------------------------------------------------------------
%	MARGIN TOC
%----------------------------------------------------------------------------------------

\RequirePackage{etoc} % Required to insert local tables of contents

\newcounter{margintocdepth} % Set the depth of the margintoc
\setcounter{margintocdepth}{\subsectiontocdepth} % By default to subsections

\newlength{\mtocshift} % Length of the vertical offset used for margin tocs
\setlength{\mtocshift}{1\vscale}% \mtocshift is overridden by \setchapterstyle

% Optional title for margintoc (by hCarlFelix, 
% https://github.com/fmarotta/kaobook/issues/101)
% We want to create an additional entries in the toc which is to be used for the margintoc
% We define these as mtocsection and mtocsubsection for section and subsection`
\newcommand{\mtocsection}[1]{
	\etoctoccontentsline{mtocsection}{%
		\ifnum\value{secnumdepth}>0 \protect\numberline{\thesection}%
		\else \protect\nonumberline%
		\fi #1}%
}
\newcommand{\mtocsubsection}[1]{
	\etoctoccontentsline{mtocsubsection}{%
		\ifnum\value{secnumdepth}>1 \protect\numberline{\thesubsection}%
		\else \protect\nonumberline%
		\fi #1}%
}

% Next, we redefine \section and \subsection so that they accept an additional parameter
% \section[alternative-title-for-toc]{title-as-written-in-text}[alternative-title-for-margintoc]

% Adapted from Frank Mittelbach's answer at Stackexchange
% https://tex.stackexchange.com/a/109560/226693
\let\oldsection\section	% save the old command
\let\oldsubsection\subsection	% save the old command

\RenewDocumentCommand\section{s o m o}{%
  \IfBooleanTF{#1}{%
	  \oldsection*{#3}
	  \IfNoValueF{#2}{% if TOC arg is given create a TOC entry
		  \addxcontentsline{toc}{section}[\thesection]{#2}%
	  }%
  }{% no star given
	  \IfNoValueTF{#2}{%
		  \oldsection{#3}%
	  }{% no TOC arg
		  \oldsection[#2]{#3}%
	  }%
	  \IfNoValueTF{#4}{% optional label given, if not we do nothing
		  % \mtocsection{#3}%
		  \IfNoValueTF{#2}{%
			  \mtocsection{#3}% when no optional toc title, use main title
		  }{% no TOC arg
			  \mtocsection{#2}% when toc optional title is given, use it
		  }%
	  }{%
		  \mtocsection{#4}%
	  }%
  }%
 }

\RenewDocumentCommand\subsection{s o m o}{%
	\IfBooleanTF{#1}{%
		\oldsubsection*{#3}%
		\IfNoValueF{#2}{% if TOC arg is given create a TOC entry
			\addxcontentsline{toc}{subsection}[\thesubsection]{#2}%
		}%
	}{% no star given
		\IfNoValueTF{#2}{%
			\oldsubsection{#3}%
		}{% no TOC arg
			\oldsubsection[#2]{#3}%
		}%
		\IfNoValueTF{#4}{% optional label given, if not we do nothing
			\IfNoValueTF{#2}{%
				\mtocsubsection{#3}% when no optional toc title, use main title
			}{% no TOC arg
				\mtocsubsection{#2}% when toc optional title is given, use it
			}%
		}{%
			\mtocsubsection{#4}%
		}%
	}%
}

\etocsetlevel{mtocsection}{6}% dummy sectioning level
\etocsetlevel{mtocsubsection}{6}% dummy sectioning level

% Command to print a table of contents in the margin
\NewDocumentCommand{\margintoc}{O{\mtocshift}}{ % The first parameter is the vertical offset; by default it is \mtocshift
	\begingroup%
	% Move regular section and subsection to level 6 so that they won't be included and instead set let the mtoc versions take their place.
	% Adapted from https://tex.stackexchange.com/a/133559/226693
	\etocsetlevel{section}{6}
	\etocsetlevel{subsection}{6}
	\etocsetlevel{mtocsection}{1}
	\etocsetlevel{mtocsubsection}{2}

	% Define default widths
	\def\margintocnumwidth{-.8mm}%
	\def\margintocpagenumwidth{8pt}%
	\setlength{\RaggedRightParfillskip}{0pt}

	% Dry run to get the needed widths
	\etocsetstyle{mtocsection}%
	{}%
	{\setbox0\hbox{{\usekomafont{section}\small\etocthenumber\kern.8mm}}%%
		\setbox1\hbox{{\usekomafont{section}\small\etocthepage}}}%
	{\ifdim\wd0>\margintocnumwidth \edef\margintocnumwidth{\the\wd0} \fi%%
		\ifdim\wd1>\margintocpagenumwidth \edef\margintocpagenumwidth{\the\wd1} \fi}%
	{}%
	\etocsetstyle{mtocsubsection}%
	{}%
	{\setbox0\hbox{{\usekomafont{section}\small\mdseries\etocthenumber\kern.8mm}}%
		\setbox1\hbox{{\usekomafont{section}\small\mdseries\etocthepage}}}%
	{\ifdim\wd0>\margintocnumwidth \edef\margintocnumwidth{\the\wd0} \fi%
		\ifdim\wd1>\margintocpagenumwidth \edef\margintocpagenumwidth{\the\wd1} \fi}%
	{}%
	\etocsetstyle{subsubsection}%
	{}%
	{}%
	{}%
	{}%
	\etocsetstyle{paragraph}%
	{}%
	{}%
	{}%
	{}%
	\etocsettocstyle{}{%
		\global\let\margintocnumwidth\margintocnumwidth%
		\global\let\margintocpagenumwidth\margintocpagenumwidth%
	}%
	\localtableofcontents%

	% Set the style for section entries
	\etocsetstyle{mtocsection}%
	{\parindent 0pt \parskip 2.5pt \parfillskip 0pt \RaggedRight}%
	{\leftskip \margintocnumwidth \rightskip \margintocpagenumwidth}%
	{\makebox[0pt][r]{\makebox[\margintocnumwidth][l]{\etocnumber}}\etocname\nobreak\leaders\hbox{\hbox to 1.5ex {\hss.\hss}}\hfill\rlap{\makebox[\margintocpagenumwidth][r]{\etocpage}}\par}%
	{}%
	% Set the style for subsection entries
	\etocsetstyle{mtocsubsection}%
	{\parindent 0pt \parskip 0pt \parfillskip 0pt \RaggedRight}%
	{\leftskip \margintocnumwidth \rightskip \margintocpagenumwidth}%
	{\makebox[0pt][r]{\makebox[\margintocnumwidth][l]{\mdseries\etocnumber}}{\mdseries\etocname\nobreak\leaders\hbox{\hbox to 1.5ex {\hss.\hss}}\hfill\rlap{\makebox[\margintocpagenumwidth][r]{\mdseries\etocpage}}}\par}%
	{\parskip 2.5pt}%
	% Set the global style of the toc
	\etocsettocstyle{\usekomafont{section}\small}{}%
	\etocsetnexttocdepth{\themargintocdepth}%
	% Print the table of contents in the margin
	\marginnote[#1]{\localtableofcontents}%
	\FloatBarrier%
	\endgroup%
}

%----------------------------------------------------------------------------------------
%	ENCODING AND FONTS
%----------------------------------------------------------------------------------------

\newcommand{\kao@fontmethodModern}{%
	\RequirePackage{amssymb} % Must be loaded before unicode-math
	\RequirePackage[force]{filehook} % Fixes an error
	\RequirePackage{unicode-math} % Math fonts in xetexorluatex
	\setromanfont[ % Libertinus Serif font
		Scale=1.04
	]{Libertinus Serif}
	\setsansfont[ % Libertinus Sans font
		Scale=1
	]{Libertinus Sans}
	\setmonofont[ % Libertinus Mono font
		Scale=.89
	]{Liberation Mono}
	\setmathfont{Libertinus Math} % Libertinus Math font
	\ifluatex
	\else
		\RequirePackage{morewrites} % Fix some errors related to floats (not necessary with LuaLaTeX
	\fi%
}
\newcommand{\kao@fontmethodTex}{%
	\RequirePackage[utf8]{inputenc} % utf8 encoding in the input (.tex) file
	\RequirePackage[T1]{fontenc} % utf8 encoding in the output (.pdf) file

	\RequirePackage{amssymb} % Math symbols, including \blacktriangleright, used for bullets
	\RequirePackage[scaled=.97,helvratio=.93,p,theoremfont]{newpxtext} % Serif palatino font
	\RequirePackage[vvarbb,smallerops,bigdelims]{newpxmath} % Math palatino font
	\RequirePackage[scaled=.85]{beramono} % Monospace font
	\RequirePackage[scr=rsfso,cal=boondoxo]{mathalfa} % Mathcal from STIX, unslanted a bit
	\RequirePackage{morewrites} % Fix some errors related to floats
}

\ifthenelse%
{\equal{modern}{\kao@fontmethod}}{\kao@fontmethodModern}%
{\ifthenelse%
	{\equal{tex}{\kao@fontmethod}}{\kao@fontmethodTex}%
	{
		\PackageError{kao}{%
			Invalid fontmethod choice \kao@fontmethod.%
		}{%
			Should be one of "modern" or "tex"%
		}
	}}

% When using the Palatino (newpxtext) font, it is better to use a 
% slightly larger stretch.
%\setstretch{1.10}
\linespread{1.07} % Give Palatino more leading (space between lines)

% Fix for the subequation environment (https://tex.stackexchange.com/questions/27053/too-much-space-between-full-paragraph-and-subequations-env)
\preto\subequations{\ifhmode\unskip\fi}

%----------------------------------------------------------------------------------------
%	HYPERREFERENCES
%----------------------------------------------------------------------------------------

\RequirePackage{hyperref} % Required for hyperlinks
\RequirePackage{bookmark} % Required for pdf bookmarks

\PassOptionsToPackage{hyphens}{url} % Break long URLs and use hyphens to separate the pieces

% Color settings should be done in the next \hypersetup
\hypersetup{ % Set up hyperref options
	unicode, % Use unicode for links
	pdfborder={0 0 0}, % Suppress border around pdf
	%xetex,
	%pagebackref=true,
	%hyperfootnotes=false, % We already use footmisc
	bookmarksdepth=section,
	bookmarksopen=true, % Expand the bookmarks as soon as the pdf file is opened
	%bookmarksopenlevel=4,
	linktoc=all, % Toc entries and numbers links to pages
	breaklinks=true,
	colorlinks=true,
}

% Define a new color for the footnote marks
\def\@footnotecolor{black}
\define@key{Hyp}{footnotecolor}{%
	\HyColor@HyperrefColor{#1}\@footnotecolor%
}
\def\@footnotemark{%
	\leavevmode
	\ifhmode\edef\@x@sf{\the\spacefactor}\nobreak\fi
	\stepcounter{Hfootnote}%
	\global\let\Hy@saved@currentHref\@currentHref
	\hyper@makecurrent{Hfootnote}%
	\global\let\Hy@footnote@currentHref\@currentHref
	\global\let\@currentHref\Hy@saved@currentHref
	\hyper@linkstart{footnote}{\Hy@footnote@currentHref}%
	\@makefnmark
	\hyper@linkend
	\ifhmode\spacefactor\@x@sf\fi
	\relax
}

% Redefine the \thanks command to allow users to use \label within \thanks without getting warnings
\let\oldthanks\thanks
\renewcommand\thanks[1]{%
	\label{bhfn:0}%
	\oldthanks{#1}%
}

% Adjust the colour of the footnotes marks using the colour defined above
\renewcommand\@makefntext[1]{%
	\renewcommand\@makefnmark{%
		\mbox{\textsuperscript{\normalfont%
				\hyperref[\BackrefFootnoteTag]{%
					\color{\@footnotecolor}{\@thefnmark}%
				}}\,%
		}%
	}%
	\BHFN@OldMakefntext{#1}%
}

%----------------------------------------------------------------------------------------
%	COLOURS
%----------------------------------------------------------------------------------------

% Uncomment to have coloured headings
%\addtokomafont{title}{\color{Maroon}}
%\addtokomafont{part}{\color{Maroon}}
%\addtokomafont{chapter}{\color{Maroon}}
%\addtokomafont{section}{\color{Maroon}}
%\addtokomafont{subsection}{\color{Maroon}}
%\addtokomafont{subsubsection}{\color{Maroon}}
%\addtokomafont{paragraph}{\color{Maroon}}
%\addtokomafont{captionlabel}{\color{Blue}}
%\addtokomafont{pagenumber}{\color{Maroon}}

% Choose the default colors
\hypersetup{
	%allcolors=DarkGreen,
	%anchorcolor=Red,
	%citecolor=DarkOrange!70!black,
	citecolor=OliveGreen,
	filecolor=OliveGreen,
	%linkcolor=Blue,
	linkcolor=Black,
	%pagecolor = Blue,
	%menucolor=Red,
	%runcolor=Red,
	urlcolor=OliveGreen,
}

%----------------------------------------------------------------------------------------
%	ITEMS
%----------------------------------------------------------------------------------------

\renewcommand{\labelitemi}{\small$\blacktriangleright$} % Use a black triangle for the first level of \item's
\renewcommand{\labelitemii}{\textbullet} % Use a bullet for the second level of \item's
\RequirePackage[inline]{enumitem} % Used to customise lists (in particular, we don't want to put whitespace between items)
\setlist[itemize]{noitemsep}
\setlist[enumerate]{noitemsep}
\setlist[description]{noitemsep}

%----------------------------------------------------------------------------------------
%	SIMPLE BOXED ENVIRONMENT
%----------------------------------------------------------------------------------------

% kaobox
\RequirePackage[most]{tcolorbox}

% Define a new environment using the style created above
\newtcolorbox{kaobox}[1][]{
	breakable,
	before skip=1.5\topskip,
	after skip=1.5\topskip,
	left skip=0pt,
	right skip=0pt,
	left=4pt,
	right=4pt,
	top=2pt,
	bottom=2pt,
	lefttitle=4pt,
	righttitle=4pt,
	toptitle=2pt,
	bottomtitle=2pt,
	sharp corners,
	boxrule=0pt,
	titlerule=.4pt,
	colback=RoyalBlue!25!White,
	colbacktitle=RoyalBlue!25!White,
	coltitle=black,
	colframe=black,
	fonttitle=\bfseries,
	#1
}

%----------------------------------------------------------------------------------------
%	ENVIRONMENT WITH A COUNTER
%----------------------------------------------------------------------------------------

% Define an environment titled 'Comment' and numbered incrementally
\newenvironment{kaocounter}{
	\refstepcounter{kaocounter}
	\begin{kaobox}[title=Comment~\thekaocounter\autodot]
		}{
	\end{kaobox}
}

% Define the commands to manage the counter for the 'kaocounter' environment
\newcounter{kaocounter}
\counterwithin{kaocounter}{section}
\newcommand*{\kaocounterformat}{% Format for the caption
	Comment~\thekaocounter\csname autodot\endcsname}
\newcommand*{\fnum@kaocounter}{\kaocounterformat}


%----------------------------------------------------------------------------------------
%	FLOATING ENVIRONMENT WITH TOC ENTRIES
%----------------------------------------------------------------------------------------

% Define a floating environment
\newenvironment{kaofloating}{%
	\@float{kaofloating}%
}{%
	\end@float%
}

% Configure the 'kaofloating' environment
\newcommand*{\fps@floatingbox}{tbph}% Allowed positions for the environment (top, bottom, own page, here)
\newcommand*{\ftype@floatingbox}{5}% Set the type of float (floats of the same type cannot change their order; figures and tables are type 1 and 2 respectively)
\newcommand*{\floatingboxformat}{% Set a title of the environment
	Insight~\thefloatingbox\csname autodot\endcsname}
\newcommand*{\fnum@floatingbox}{\floatingboxformat}% Use the environment title
\newcommand*{\ext@floatingbox}{loi}% Choose the extension of the auxiliary file for this environment

\addtotoclist[float]{loi}% Keep track of 'kaofloating' environments for a "List of Insights"
\newcommand*{\listofloiname}{List of Insights}% Choose the title for the "List of Insights"
\newcommand*{\l@floatingbox}{\l@figure}% Format the LOI
\newcommand*{\listofinsights}{\listoftoc{loi}}% User-friendly command to print the LOI

%----------------------------------------------------------------------------------------
%	ADDITIONAL PACKAGES
%----------------------------------------------------------------------------------------

% Productivity
\RequirePackage{pdfpages} % Insert PDF pages
\RequirePackage{subfiles} % Adopt a modular structure
\RequirePackage{todonotes} % Add useful notes in the margins

% Listings code
\RequirePackage{listings} % Code
%\RequirePackage{minted} (must be loaded before scrhack)

% Configure the listings
\definecolor{listingkeywords}{rgb}{0.0, 0.5, 0.0}
\definecolor{listingidentifiers}{rgb}{0, 0, 0}
\definecolor{listingcomments}{rgb}{0.25, 0.5, 0.5}
\definecolor{listingstrings}{rgb}{0.73, 0.13, 0.13}
\definecolor{listingnumbers}{rgb}{0.25, 0.25, 0.25}
% Define a fancy style
\lstdefinestyle{kaolst}{
	aboveskip=0.7\topskip,
	belowskip=0.1\topskip,
	basicstyle=\small\ttfamily,
	commentstyle=\color{listingcomments}\itshape,
	keywordstyle=\color{listingkeywords}\bfseries,
	numberstyle=\scriptsize\color{listingnumbers}\ttfamily,
	stringstyle=\color{listingstrings},
	identifierstyle=\color{listingidentifiers},
	backgroundcolor=\color{White},
	breakatwhitespace=false,
	breaklines=true,
	captionpos=t,
	keepspaces=true,
	showspaces=false,
	showstringspaces=false,
	showtabs=false,
	numbers=left,
	numbersep=1em,
	%frame=lines,
	frame=l,
	framerule=.7pt,
	tabsize=4,
	defaultdialect=[LaTeX]Tex,
}
% Define a plain style as well
\lstdefinestyle{kaolstplain}{
	aboveskip=0.6\topskip,
	belowskip=-0.1\topskip,
	basicstyle=\small\ttfamily,
	commentstyle=\color{listingcomments}\itshape,
	keywordstyle=\color{listingkeywords}\bfseries,
	numberstyle=\scriptsize\color{listingnumbers}\ttfamily,
	stringstyle=\color{listingstrings},
	identifierstyle=\color{listingidentifiers},
	backgroundcolor=\color{White},
	breakatwhitespace=false,
	breaklines=true,
	captionpos=b,
	keepspaces=true,
	showspaces=false,
	showstringspaces=false,
	showtabs=false,
	numbers=none,
	frame=none,
	tabsize=4,
	defaultdialect=[LaTeX]Tex,
}
\lstset{style=kaolst}% Use the fancy style

% Verbatim
%\RequirePackage{fancyvrb} % Customization of verbatim environments
%\fvset{fontsize=\normalsize} % Change here the font size of all 
%verbatim \preto{\@verbatim}{\topsep=0pt \partopsep=0pt }

% Algorithms
\RequirePackage[linesnumbered, ruled, vlined]{algorithm2e} % Algorithms

% Special gliphs
\RequirePackage{ccicons} % Creative Commons icons

% Index, glossary and nomenclature
\RequirePackage{imakeidx}
\RequirePackage[xindy,toc,numberedsection=nameref]{glossaries}
\RequirePackage[intoc]{nomencl}

% Commands to print specific words always in the same way
% TODO: in \Command, automatically escape braces {} and replace backslashes with \textbackslash
\newcommand{\Class}[1]{\texttt{#1}}
\newcommand{\Package}[1]{\texttt{#1}}
\newcommand{\Option}[1]{\texttt{#1}}
\newcommand{\Command}[1]{\texttt{\textbackslash#1}}
\newcommand{\Environment}[1]{\texttt{#1}}
\newcommand{\Path}[1]{\texttt{#1}}

% Print latin words in italics (The xspace package is required but we already loaded it in the class)
\newcommand{\hairsp}{\hspace{1pt}} % Command to print a very short space
\newcommand{\invitro}{\textit{in vitro}\xspace}
\newcommand{\invivo}{\textit{in vivo}\xspace}
\newcommand{\cis}{\textit{cis}\xspace}
\newcommand{\trans}{\textit{trans}\xspace}
\newcommand{\etal}{\textit{et al.}\xspace}
\newcommand{\denovo}{\textit{de novo}\xspace}
\newcommand{\adhoc}{\textit{ad hoc}\xspace}
\newcommand{\etcetera}{\textit{et cetera}\xspace}
\newcommand{\etc}{\textit{etc.}\xspace}
\newcommand{\ie}{\textit{i.\nobreak\hairsp{}e.}\xspace}
\newcommand{\eg}{\textit{e.\nobreak\hairsp{}g.}\xspace}
\newcommand{\vs}{\textit{vs}\xspace}
\newcommand{\cfr}{\textit{cfr.}\xspace}

% Tables
\newcommand{\na}{\quad--} % Used in tables for N/A cells
\newcommand{\hangp}[1]{\makebox[0pt][r]{(}#1\makebox[0pt][l]{)}} % Create parentheses around text in tables which take up no horizontal space - this improves column spacing
\newcommand{\hangstar}{\makebox[0pt][l]{*}} % Create asterisks in tables which take up no horizontal space - this improves column spacing

% A command to print the current month and year (from tufte-latex)
\newcommand{\monthyear}{\ifcase\month\or January\or February\or March\or
		April\or May\or June\or July\or August\or September\or October\or
		November\or December\fi\space\number\year}
