% Template adapted from https://github.com/jgm/pandoc-templates/blob/master/default.latex
% To be used with XeLaTex in memoiR
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% Options for packages loaded elsewhere
\PassOptionsToPackage{unicode=true}{hyperref}
\PassOptionsToPackage{hyphens}{url}
$if(colorlinks)$
\PassOptionsToPackage{dvipsnames,svgnames*,x11names*}{xcolor}
$endif$
% Right to left support
$if(dir)$
  $if(latex-dir-rtl)$
\PassOptionsToPackage{RTLdocument}{bidi}
  $endif$
$endif$
$if(CJKmainfont)$
\PassOptionsToPackage{space}{xeCJK}
$endif$


\documentclass[
  $if(fontsize)$$fontsize$,$endif$
  $if(lang)$$babel-lang$,$endif$
  $if(papersize)$$papersize$paper,$endif$
  $for(classoption)$$classoption$$sep$,$endfor$
  ]{$documentclass$}

% Double (or whatever) spacing
$if(linestretch)$
\usepackage{setspace}
\setstretch{$linestretch$}
$endif$

% Math
\usepackage{amssymb, amsmath}
% mathspec: arbitrary math fonts
$if(mathspec)$
\usepackage{mathspec}
$else$
\usepackage{unicode-math}
$endif$
\defaultfontfeatures{Scale=MatchLowercase}
\defaultfontfeatures[\rmfamily]{Ligatures=TeX,Scale=1}

% Fonts
\usepackage{lmodern}
\usepackage{fontspec}
% Main font
$if(mainfont)$
\setmainfont[$for(mainfontoptions)$$mainfontoptions$$sep$,$endfor$]{$mainfont$}
$endif$
% Specific sanserif font
$if(sansfont)$
\setsansfont[$for(sansfontoptions)$$sansfontoptions$$sep$,$endfor$]{$sansfont$}
$endif$
% Specific monotype font
$if(monofont)$
\setmonofont[$for(monofontoptions)$$monofontoptions$$sep$,$endfor$]{$monofont$}
$endif$
% Specific math font
$if(mathfont)$
  $if(mathspec)$
\setmathfont(Digits,Latin,Greek)[$for(mathfontoptions)$$mathfontoptions$$sep$,$endfor$]{$mathfont$}
  $else$
\setmathfont[$for(mathfontoptions)$$mathfontoptions$$sep$,$endfor$]{$mathfont$}
  $endif$
$endif$
% Chinese, Japanese, Corean fonts
$if(CJKmainfont)$
  \usepackage{xeCJK}
  \setCJKmainfont[$for(CJKoptions)$$CJKoptions$$sep$,$endfor$]{$CJKmainfont$}
$endif$

% Use upquote for straight quotes in verbatim environments
\usepackage{upquote}
% Use microtype
\usepackage[$for(microtypeoptions)$$microtypeoptions$$sep$,$endfor$]{microtype}
\UseMicrotypeSet[protrusion]{basicmath} % disable protrusion for tt fonts

% Verbatim in note
$if(verbatim-in-note)$
\usepackage{fancyvrb}
\VerbatimFootnotes % allows verbatim text in footnotes
$endif$

% Color links
$if(colorlinks)$
\usepackage{xcolor}
$endif$

% Strikeout
$if(strikeout)$
\usepackage[normalem]{ulem}
% avoid problems with \sout in headers with hyperref:
\pdfstringdefDisableCommands{\renewcommand{\sout}{}}
$endif$

% Necessary for code chunks
$if(highlighting-macros)$
$highlighting-macros$
$endif$

% Listings package
$if(listings)$
\usepackage{listings}
\newcommand{\passthrough}[1]{#1}
$endif$

% Tables
$if(tables)$
\usepackage{longtable,booktabs,tabu}
% Fix footnotes in tables (requires footnote package)
\IfFileExists{footnote.sty}{\usepackage{footnote}\makesavenoteenv{longtable}}{}
$endif$

% Graphics
$if(graphics)$
\usepackage{graphicx,grffile}
\graphicspath{{images/}}
\makeatletter
\def\maxwidth{\ifdim\Gin@nat@width>\linewidth\linewidth\else\Gin@nat@width\fi}
\def\maxheight{\ifdim\Gin@nat@height>\textheight\textheight\else\Gin@nat@height\fi}
\makeatother
% Scale images if necessary, so that they will not overflow the page
% margins by default, and it is still possible to overwrite the defaults
% using explicit options in \includegraphics[width, height, ...]{}
\setkeys{Gin}{width=\maxwidth,height=\maxheight,keepaspectratio}
$endif$

% Prevent overfull lines
\setlength{\emergencystretch}{3em}  
\providecommand{\tightlist}{%
  \setlength{\itemsep}{0pt}\setlength{\parskip}{0pt}}

% Number sections for memoir (secnumdepth counter is ignored)
$if(secnum-depth)$
\setsecnumdepth{$secnum-depth$}
$endif$

% Set default figure placement to htbp
\makeatletter
\def\fps@figure{htbp}
\makeatother

% Spacing in lists
\usepackage{enumitem}

% Polyglossia
$if(lang)$
\usepackage{polyglossia}
\setmainlanguage{$lang$}
$for(otherlangs)$
\setotherlanguage{$otherlangs$}
$endfor$
$endif$

% localized quotes
\usepackage[strict,autostyle]{csquotes}

% BibLaTeX
$if(biblatex)$
\usepackage[$for(biblatexoptions)$$biblatexoptions$$sep$,$endfor$]{biblatex}
$for(bibliography)$
\addbibresource{$bibliography$}
$endfor$
$endif$

% cslreferences environment required by pandoc > 2.7
$if(csl-refs)$
\newlength{\cslhangindent}
\setlength{\cslhangindent}{1.5em}
\newenvironment{cslreferences}%
  {$if(csl-hanging-indent)$\setlength{\parindent}{0pt}%
  \everypar{\setlength{\hangindent}{\cslhangindent}}\ignorespaces$endif$}%
  {\par}
$endif$



%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% memoiR format

% Chapter Summary environment 
\usepackage[tikz]{bclogo}
\newenvironment{Summary}
  {\begin{bclogo}[logo=\bctrombone, noborder=true, couleur=lightgray!50]{$chaptersummary$}\parindent0pt}
  {\end{bclogo}}
% Syntax:
%
%```{block, type='Summary'}
% Deliver message here.
% ```

% scriptsize code 
\let\oldverbatim\verbatim
\def\verbatim{\oldverbatim\scriptsize}
% Applies to code blocks and R code results
% code chunk options size='scriptsize' applies only to R code and results
% if the code chunk sets a different size, \def\verbatim{...} is prioritary for code results 


% memoiR dalef3 chapter style 
% https://ctan.crest.fr/tex-archive/info/latex-samples/MemoirChapStyles/MemoirChapStyles.pdf
\usepackage{soul}
\definecolor{nicered}{rgb}{.647,.129,.149}
\makeatletter
\newlength\dlf@normtxtw
\setlength\dlf@normtxtw{\textwidth}
\def\myhelvetfont{\def\sfdefault{mdput}}
\newsavebox{\feline@chapter}
\newcommand\feline@chapter@marker[1][4cm]{%
  \sbox\feline@chapter{%
    \resizebox{!}{#1}{\fboxsep=1pt%
	  \colorbox{nicered}{\color{white}\bfseries\sffamily\thechapter}%
	}}%
  \rotatebox{90}{%
    \resizebox{%
	  \heightof{\usebox{\feline@chapter}}+\depthof{\usebox{\feline@chapter}}}%
	{!}{\scshape\so\@chapapp}}\quad%
  \raisebox{\depthof{\usebox{\feline@chapter}}}{\usebox{\feline@chapter}}%
 }
\newcommand\feline@chm[1][4cm]{%
  \sbox\feline@chapter{\feline@chapter@marker[#1]}%
  \makebox[0pt][l]{% aka \rlap
    \makebox[1cm][r]{\usebox\feline@chapter}%
  }}
\makechapterstyle{daleif1}{
  \renewcommand\chapnamefont{\normalfont\Large\scshape\raggedleft\so}
  \renewcommand\chaptitlefont{\normalfont\huge\bfseries\scshape\color{nicered}}
  \renewcommand\chapternamenum{}
  \renewcommand\printchaptername{}
  \renewcommand\printchapternum{\null\hfill\feline@chm[2.5cm]\par}
  \renewcommand\afterchapternum{\par\vskip\midchapskip}
  \renewcommand\printchaptertitle[1]{\chaptitlefont\raggedleft ##1\par}
}
\makeatother


% Layout
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% Based on memoir, style companion
\newcommand{\MemoirChapStyle}{$MemoirChapStyle$}
\newcommand{\MemoirPageStyle}{$MemoirPageStyle$}

% Space between paragraphs
\usepackage{parskip}
  \abnormalparskip{3pt}

% Adjust margin paragraphs vertical position
\usepackage{marginfix}


% Margins
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% allow use of '-',+','/' ans '*' to make simple length computation
\usepackage{calc}

% Full-width figures utilities
\newlength\widthw % full width
\newlength{\rf}
\newcommand*{\definesHSpace}{
  \strictpagecheck % slower but efficient detection of odd/even pages
  \checkoddpage
  \ifoddpage
  \setlength{\rf}{0mm}
  \else
  \setlength{\rf}{\marginparsep+\marginparwidth}
  \fi
}

\makeatletter
% 1" margins for the front matter.
\newcommand*{\SmallMargins}{
  \setlrmarginsandblock{$spinemargin$}{$smallmargin$}{*}
  \setmarginnotes{0.1in}{0.1in}{0.1in}
 \setulmarginsandblock{$uppermargin$}{$lowermargin$}{*}
  \checkandfixthelayout
  \ch@ngetext
  \clearpage
  \setlength{\widthw}{\textwidth+\marginparsep+\marginparwidth}
  \footnotesatfoot
  \chapterstyle{\MemoirChapStyle}  % Chapter and page styles must be recalled
  \pagestyle{\MemoirPageStyle}
}

% 3" outer margin for the main matter
$if(largemargins)$
\newcommand*{\LargeMargins}{
  \setlrmarginsandblock{$spinemargin$}{$largemargin$}{*}
  \setmarginnotes{0.2in}{$marginnote$}{0.1in}
  \setsidecaps{0.2in}{$marginnote$}
  \setulmarginsandblock{$uppermargin$}{$lowermargin$}{*}
  \checkandfixthelayout
  \ch@ngetext
  \clearpage
  \setlength{\widthw}{\textwidth+\marginparsep+\marginparwidth}
  \footnotesinmargin
  \chapterstyle{\MemoirChapStyle}  % Chapter and page styles must be recalled
  \pagestyle{\MemoirPageStyle}
}
$else$
\newcommand{\LargeMargins}{\SmallMargins}
$endif$
\makeatother

% Figure captions and footnotes in outer margins
$if(largemargins)$
\usepackage[margincaption,outercaption,ragged,wide]{sidecap}
$endif$


% Local toc
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\usepackage{titletoc}
\newcommand{\toc}[1]{%
  \startcontents[chapters]%
  \printcontents[chapters]{}{1}[#1]{}%
  ~\newline%
}


% Text boxes
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% Define a style for mdframed boxes
\mdfdefinestyle{boxstyle}{
	skipabove=1.5\topskip,
	skipbelow=.5\topskip,
	rightmargin=0pt,
	leftmargin=0pt,
	innerrightmargin=7pt,
	innerleftmargin=7pt,
	topline=false,
	bottomline=false,
	rightline=false,
	leftline=false,
	frametitlerule=true,
	linecolor=black,
	fontcolor=black,
	frametitlealignment=\noindent
}


% Main title page with filigrane
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

$if(maintitlepage)$
% Text blocks
\usepackage[absolute,overlay]{textpos}
  \setlength{\TPHorizModule}{1mm}
  \setlength{\TPVertModule}{1mm}

\newcommand{\MainTitlePage}[2]{
  \SmallMargins % Margins
  \pagestyle{empty} % No header/footer
  \textblockorigin{\stockwidth-\paperwidth-\trimedge}{\trimtop} % recto
  \begin{textblock*}{2mm}(\spinemargin/2,\uppermargin/2)
    \rule{1pt}{\paperheight-\uppermargin}
  \end{textblock*}
  \begin{textblock*}{\paperwidth*2/3}(\paperwidth/5, \paperheight/5)
    \flushright
    \begin{Spacing}{3}
      {\fontfamily{qtm}\selectfont\fontsize{45}{45}\selectfont\textsc{\thetitle}}
    \end{Spacing}
  \end{textblock*}
  $if(maintitlepage.filigrane)$
  \begin{textblock*}{\paperwidth/2}[1, 1](\paperwidth, \paperheight)
    \includegraphics[width=\paperwidth/2]{$maintitlepage.filigrane$}
  \end{textblock*}
  \begin{textblock*}{\paperwidth*2/3}(\spinemargin, \paperheight/2)
    {\fontfamily{qtm}\huge\theauthor}
  \end{textblock*}
  $else$
  \begin{textblock*}{\paperwidth*2/3}(\paperwidth/5, \paperheight/2)
    \flushright
    {\fontfamily{qtm}\huge\theauthor}
  \end{textblock*}
  $endif$
  \begin{textblock*}{\paperwidth*2/3}[0, 1](\spinemargin, \uppermargin+\textheight)
    \normalfont\thedate
  \end{textblock*}
  ~\\ % Print a character or the page will not exist
  \newpage
  \textblockorigin{\trimedge}{\trimtop} % verso
  \begin{textblock*}{\textwidth}(\paperwidth-\spinemargin-\textwidth, \uppermargin)
    #1
  \end{textblock*}
  \begin{textblock*}{\textwidth}[0,1](\paperwidth-\spinemargin-\textwidth, \uppermargin+\textheight+\footskip)
    \centering
    $if(maintitlepage.logo)$
      \includegraphics[width=\paperwidth/4]{logo}\\ \bigskip
    $endif$
    #2
  \end{textblock*}
  ~\\ % Print a character or the page will not exist
  \newpage
}
$endif$

% Clear page and open an even one (\clearpage opens an odd one)
\newcommand{\evenpage}{
  \clearpage
  \strictpagecheck % slower but efficient detection of odd/even pages
  \checkoddpage
  \ifoddpage
    \thispagestyle{empty}
    ~\\ % Print a character or the page will not exist
    \newpage
  \else
    % do nothing
  \fi
}


%% PDF title page to insert
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

$if(pdftitlepage)$
\usepackage{pdfpages}
$endif$


%% Bibliography
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% Repeated citation as author-year-title instead of author-title (modification of footcite:note in verbose-inote.cbx)
$if(largemargins)$
\renewbibmacro*{footcite:note}{%
  \ifnameundef{labelname}
    {\printfield{label}}
    {\printnames{labelname}}
  \setunit*{\nameyeardelim}
  \iffieldundef{labelyear}
    {}
    {\printtext[parens]{\printfield{labelyear}\printfield{userb}}.}
  \ifsamepage{\the\value{instcount}}{\csuse{cbx@f@\thefield{entrykey}}}
    {}
    {\setunit*{\nametitledelim} \printfield[title]{labeltitle}}
  \setunit*{\addcomma\space}
  \printtext{
    \bibstring{seenote}\addnbspace
    \ref{cbx@\csuse{cbx@f@\thefield{entrykey}}}
    \iftoggle{cbx:pageref}
    {
      \ifsamepage{\the\value{instcount}}  {\csuse{cbx@f@\thefield{entrykey}}}
      {}
      {\addcomma\space\bibstring{page}\addnbspace
      \pageref{cbx@\csuse{cbx@f@\thefield{entrykey}}}
      }
    }
    {}
  }
}
% Normal text in citations, to allow \textcite
\AtEveryCite{\renewcommand*{\mkbibnamefamily}[1]{\textnormal{#1}}}
% Add url's to computer softfware and @Misc in general, delete it in other cases
% in citations...
\AtEveryCitekey{%
  \ifentrytype{misc}{%
  }{%
  \clearfield{url}%
  \clearfield{urldate}%
  }%
}
% ... and in bibliography
\AtEveryBibitem{%
  \ifentrytype{misc}{%
  }{%
  \clearfield{url}%
  \clearfield{urldate}%
}%
}
$endif$

%% Table of Contents
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% fix the typesetting of the part number
\renewcommand\partnumberlinebox[2]{#2\ ---\ }


% Fonts
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

$if(largemargins)$
% Font size of side captions and side notes
\captionnamefont{\scriptsize}
\captiontitlefont{\scriptsize}
\renewcommand{\footnotesize}{\tiny}
$endif$

% Hyperref comes last
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\usepackage{hyperref}
\hypersetup{
$if(title-meta)$
  pdftitle={$title-meta$},
$endif$
$if(author-meta)$
  pdfauthor={$author-meta$},
$endif$
$if(keywords)$
  pdfkeywords={$for(keywords)$$keywords$$sep$, $endfor$},
$endif$
$if(colorlinks)$
  colorlinks=true,
  linkcolor=$if(linkcolor)$$linkcolor$$else$Maroon$endif$,
  citecolor=$if(citecolor)$$citecolor$$else$Blue$endif$,
  urlcolor=$if(urlcolor)$$urlcolor$$else$Blue$endif$,
$else$
  pdfborder={0 0 0},
$endif$
  breaklinks=true}

% Don't use monospace font for urls
\urlstyle{same}


% Title, author, date from YAML to LaTeX
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

$if(title)$
\title{$title$$if(thanks)$\thanks{$thanks$}$endif$}
$endif$

$if(author)$
\author{$for(author)$$author$$sep$ \and $endfor$}
$endif$

\date{$date$}


% Include headers (preamble.tex) here
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
$for(header-includes)$
$header-includes$
$endfor$


% End of preamble
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%


\begin{document}
\frontmatter

% Title page
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

$if(pdftitlepage)$
\includepdf[pages=1]{$pdftitlepage$}
\cleardoublepage
$endif$

$if(maintitlepage)$
\MainTitlePage{$maintitlepage.epigraph$}{$maintitlepage.credits$}
$endif$


% Before Body
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

$for(include-before)$
$include-before$
$endfor$



% Contents
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\LargeMargins
$if(toc)$
{
$if(colorlinks)$
\hypersetup{linkcolor=$if(toccolor)$$toccolor$$else$$endif$}
$endif$
\setcounter{tocdepth}{$toc-depth$}
\tableofcontents
}
$endif$


% Body
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\LargeMargins
$body$


% Bibliography
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\backmatter
\SmallMargins

$if(biblatex)$
$if(longbibliography)$
\twocolumn
\renewcommand*{\bibfont}{\scriptsize}
$endif$
\printbibliography$if(biblio-title)$[title=$biblio-title$]$endif$
\onecolumn
$endif$


% Tables (of tables, of figures)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

$if(lot)$
\cleardoublepage
\LargeMargins
\listoftables
$endif$

$if(lof)$
\cleardoublepage
\LargeMargins
\listoffigures
$endif$


% After-body (LaTeX code inclusion)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

$for(include-after)$
$include-after$
$endfor$


% Back cover
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% Even page, small margins, no running head, no page number.
\evenpage
\SmallMargins
\thispagestyle{empty}

$if(backcoverfontsize)$
\begin{$backcoverfontsize$}
$endif$

$if(backcover)$
\begin{description}

$for(backcover)$
\selectlanguage{$backcover.language$}
\item[$backcover.abstractlabel$]
$backcover.abstract$
\item[$backcover.keywordlabel$]
$for(backcover.keywords)$$backcover.keywords$$sep$, $endfor$.
~\\
$endfor$

\end{description}
$endif$

$if(backcoverfontsize)$
\end{$backcoverfontsize$}
$endif$

$if(cover-image)$
\vspace*{\fill}
\centering\includegraphics[width=.3\textwidth]{images/logo}
$endif$

\end{document}
