\NeedsTeXFormat{LaTeX2e}
\ProvidesPackage{doctools}[2012/12/01 v0.1 commands and packages for documenting LaTeX Code]
%%% === Define Keys ===================================
\RequirePackage{kvoptions-patch}
\RequirePackage{kvoptions}  % options
\RequirePackage{pdftexcmds} % string comparison
\SetupKeyvalOptions{family=doctools,prefix=doctools@}
\DeclareBoolOption[false]{loadHyperref}
\DeclareBoolOption[true]{createIndexEntries}
\DeclareBoolOption[false]{applyLayout}
\ProcessKeyvalOptions{doctools}
%%% ---- Packages ----
%%% Programming
\usepackage{etoolbox}
\usepackage{xstring}
\usepackage{kvsetkeys}
%%% Font packages
\ifdoctools@applyLayout
\usepackage{cmap}
\usepackage[T1]{fontenc} % T1 Schrift Encoding
\usepackage{textcomp}
\fi % end \ifdoctools@applyLayout
%%% listings (must be loaded before \AtBeginDocument)
\@ifpackageloaded{listings}{}{\RequirePackage{listings}}
%%% load all further packages and all commands
%%% at the beginning of the document and thus
%%% after all other packages
\PassOptionsToPackage{table}{xcolor}
\AtBeginDocument{%
%%
%%% Additional packages
\usepackage{xspace}
\@ifpackageloaded{xcolor}{}
 {\usepackage{xcolor}}
%%% listings
\colorlet{doc@stringcolor}{green!40!black!100}
\colorlet{doc@commentcolor}{green!50!black!100}
\colorlet{doc@numbercolor}{white!50!black!100}
\definecolor{doc@keywordcolor}{rgb}{0,0.35,1.0}
\colorlet{doc@demo@backcolor}{white}
\definecolor{doc@rulecolor}{rgb}{0.5,0.5,0.5}
\lstdefinestyle{lstStyleDefault}{
%%% appearance
   ,basicstyle=\small\ttfamily % Standardschrift
%%%  Space and placement
   ,floatplacement=tbp    % is used as float place specifier
   ,aboveskip=\medskipamount % define the space above and
   ,belowskip=\medskipamount % below displayed listings.
   ,lineskip=0pt          % specifies additional space between lines in listings.
   ,boxpos=c              % c,b,t
%%% The printed range
   ,showlines=false       % prints empty lines at the end of listings
%%% characters
   ,extendedchars=true   % allows or prohibits extended characters
                         % in listings, that means (national)
                         % characters of codes 128-255.
   ,upquote=true         % determines printing of quotes
   ,tabsize=2,           % chars of tab
   ,showtabs=false       % do not show tabs
   ,showspaces=false     % do not show spaces
   ,showstringspaces=false % do not show blank spaces in string
%%% Line numbers
   ,numbers=none         % left, right, none
%%% Captions
   ,numberbychapter=true %
   ,captionpos=b         % t,b
   ,abovecaptionskip=\smallskipamount % the vertical space respectively above
   ,belowcaptionskip=\smallskipamount % or below each caption
%%% Margins and line shape
   ,linewidth=\linewidth % defines the base line width for listings.
   ,xleftmargin=0pt      % extra margins
   ,xrightmargin=0pt     %
   ,resetmargins=false   % indention from list environments like enumerate
                         % or itemize is reset, i.e. not used.
   ,breaklines=true      % line breaking of long lines.
   ,breakatwhitespace=false % allows line breaks only at white space.
   ,breakindent=0pt     % is the indention of the second, third, ...
                         % line of broken lines.
   ,breakautoindent=true % apply intendation
   ,columns=flexible     %
   ,keepspaces=true      %
}

\lstset{style=lstStyleDefault}

\lstdefinestyle{lstDocStyleBase}{
%%% base style
   ,style=lstStyleDefault
%%% appearance
   ,commentstyle=\slshape
%%% Line numbers
   ,numbers=left         % left, right, none
   ,stepnumber=1         % seperation between numbers
   ,numberfirstline=false % number first line always
   ,numberstyle=\tiny\color{doc@numbercolor}    % style of numbers
   ,numbersep=5pt        % distance to text
   ,numberblanklines=true %
%%% language
   ,language = [LaTeX]TeX
%%% commands
   % LaTeX programming
   ,moretexcs={setlength,usepackage,newcommand,renewcommand,providecommand,RequirePackage,SelectInputMappings,ifpdftex,ifpdfoutput,AtBeginEnvironment,ProvidesPackage},
   % other commands
   ,moretexcs={maketitle,text,includegraphics,chapter,section,subsection,
     subsubsection,paragraph,textmu,enquote,blockquote,ding,mathds,ifcsdef,Bra,Ket,Braket,subcaption,lettrine,mdfsetup,captionof,listoffigures,listoftables,tableofcontents,appendix}
   % tables
   ,moretexcs={newcolumntype,rowfont,taburowcolors,rowcolor,rowcolors,bottomrule,
     toprule,midrule,}
   % hyperref
   ,moretexcs={hypersetup}
   % glossaries
   ,moretexcs={gls,printglossary,glsadd,newglossaryentry,newacronym}
   % Koma
   ,moretexcs={mainmatter,frontmatter,geometry,KOMAoptions,setkomafont,addtokomafont}
   % SI, unit
   ,moretexcs={si,SI,sisetup,unit,unitfrac,micro}
   % biblatex package
   ,moretexcs={newblock,ExecuteBibliographyOptions,addbibresource}
   % math packages
   ,moretexcs={operatorname,frac,sfrac,dfrac,DeclareMathOperator,mathcal,underset}
   % demo package
   ,moretexcs={democodefile,package,cs,command,env,DemoError,PrintDemo}
   % tablestyles
   ,moretexcs={theadstart,tbody,tsubheadstart,tsubhead,tend}
   % code section package
   ,moretexcs={DefineCodeSection,SetCodeSection,BeginCodeSection,
     EndCodeSection}
   % template tools package
   ,moretexcs={IfDefined,IfUndefined,IfElseDefined,IfElseUndefined,IfMultDefined,IfNotDraft,IfNotDraftElse,IfDraft,IfPackageLoaded,IfElsePackageLoaded,IfPackageNotLoaded,IfPackagesLoaded,IfPackagesNotLoaded,ExecuteAfterPackage,ExecuteBeforePackage,IfTikzLibraryLoaded,IfColumntypeDefined,IfColumntypesDefined,IfColorDefined,IfColorsDefined,IfMathVersionDefined,SetTemplateDefinition,UseDefinition,IfFileExists,iflanguage}
   % tablestyles
   ,moretexcs={setuptablefontsize,tablefontsize,setuptablestyle,tablestyle,  setuptablecolor,tablecolor,disablealternatecolors,   tablealtcolored,tbegin,tbody,tend,thead, theadstart,tsubheadstart,tsubhead,theadrow,tsubheadrow,resettablestyle,theadend,tsubheadend,tableitemize,PreserveBackslash}
   % todonotes
   ,moretexcs={todo,missingfigure}
   % listings
   ,moretexcs={lstloadlanguages,lstdefinestyle,lstset}
   % index
   ,moretexcs={indexsetup}
   % glossaries
   ,moretexcs={newglossarystyle,glossarystyle,deftranslation,newglossary}
   % tikz
   ,moretexcs={usetikzlibrary}
   % color
   ,moretexcs={definecolor,colorlet}
   % caption
   ,moretexcs={captionsetup,DeclareCaptionStyle}
   % floatrow
   ,moretexcs={floatsetup}
   % doc.sty
   ,moretexcs={EnableCrossrefs,DisableCrossrefs,PageIndex,CodelineIndex,CodelineNumbered}
   % refereces
   ,moretexcs={cref,Cref,vref,eqnref,figref,tabref,secref,chapref}
}

\lstdefinestyle{lstDemoStyleLaTeXCode}{ %
%%% base style
   ,style=lstDocStyleBase
%%% Line numbers
   ,numbers=none         % left, right, none
%%% colors
   ,stringstyle=\color{doc@stringcolor}
   ,keywordstyle=\color{doc@keywordcolor}
   ,commentstyle=\color{doc@commentcolor}
   ,backgroundcolor=\color{doc@demo@backcolor}
   ,rulecolor=\color{doc@rulecolor}
%%% frame
   ,frame=single         % none, leftline, topline, bottomline, lines
                         % single, shadowbox
   ,framesep=3pt
   ,rulesep=2pt          % control the space between frame and listing
                         % and between double rules.
   ,framerule=0.4pt      % controls the width of the rules.
}

\colorlet{doc@code@backcolor}{gray!5}
\colorlet{doc@code@keywordcolor}{black}
\colorlet{doc@code@commentcolor}{black!60}

\lstdefinestyle{lstDocStyleLaTeXCode}{%
%%% base style
   ,style=lstDocStyleBase
%%% colors
   ,stringstyle=\color{doc@stringcolor}
   ,keywordstyle=\color{doc@code@keywordcolor} %
   ,commentstyle=\color{doc@code@commentcolor}
   ,backgroundcolor=\color{doc@code@backcolor}
   ,rulecolor=\color{doc@rulecolor}
%%% frame
   ,frame=none         % none, leftline, topline, bottomline, lines
                         % single, shadowbox
   ,framesep=3pt
   ,rulesep=2pt          % control the space between frame and listing
                         % and between double rules.
   ,framerule=0.4pt      % controls the width of the rules.
%%% numbers
   ,firstnumber=last
}

\lstloadlanguages{[LaTeX]TeX}
%%% hyperref
\ifdoctools@loadHyperref
\makeatletter
\@ifpackageloaded{hyperref}{}
   % load hyperref only if package
   % hypdoc is not loaded, which
   % loads hyperref itself
   {\usepackage[
     ,backref=page%
     ,pagebackref=false%
     ,hyperindex=true%
     ,hyperfootnotes=false%
     ,bookmarks=true%
     ,pdfpagelabels=true%
   ]{hyperref}}
\makeatother
\usepackage[]{bookmark}
\definecolor{pdfanchorcolor}{named}{black}
\definecolor{pdfmenucolor}{named}{red}
\definecolor{pdfruncolor}{named}{cyan}
\definecolor{pdfurlcolor}{rgb}{0,0,0.6}
\definecolor{pdffilecolor}{rgb}{0.7,0,0}
\definecolor{pdflinkcolor}{rgb}{0,0,0.6}
\definecolor{pdfcitecolor}{rgb}{0,0,0.6}
\hypersetup{
   ,draft=false, % all hypertext options are turned off
   ,final=true   % all hypertext options are turned on
   ,debug=false  % extra diagnostic messages are printed in the log file
   ,hypertexnames=true % use guessable names for links
   ,naturalnames=false % use LATEX-computed names for links
   ,setpagesize=true   % sets page size by special driver commands
   ,raiselinks=true    % forces commands to reflect the real height of the link
   ,breaklinks=true    % Allows link text to break across lines
   ,pageanchor=true    % Determines whether every page is given an implicit
   ,plainpages=false   % Forces page anchors to be named by the arabic
   ,linktocpage=true   % make page number, not text, be link on TOC, LOF and LOT
   ,colorlinks=true    % Colors the text of links and anchors.
   ,linkcolor  =pdflinkcolor   % Color for normal internal links.
   ,anchorcolor=pdfanchorcolor % Color for anchor text.
   ,citecolor  =pdfcitecolor   % Color for bibliographical citations in text.
   ,filecolor  =pdffilecolor   % Color for URLs which open local files.
   ,menucolor  =pdfmenucolor   % Color for Acrobat menu items.
   ,runcolor   =pdfruncolor    % Color for run links (launch annotations).
   ,urlcolor   =pdfurlcolor    % color magenta Color for linked URLs.
   ,bookmarksopen=true     % If Acrobat bookmarks are requested, show them
   ,bookmarksopenlevel=2   % level (\maxdimen) to which bookmarks are open
   ,bookmarksnumbered=true %
   ,bookmarkstype=toc      %
   ,pdfpagemode=UseOutlines %
   ,pdfstartpage=1         % Determines on which page the PDF file is opened.
   ,pdfstartview=FitH      % Set the startup page view
   ,pdfremotestartview=Fit % Set the startup page view of remote PDF files
   ,pdfcenterwindow=false  %
   ,pdffitwindow=false     % resize document window to fit document size
   ,pdfnewwindow=false     % make links that open another PDF file
   ,pdfdisplaydoctitle=true  % display document title instead of file name
} % end: hypersetup
\fi % end \ifdoctools@loadHyperref
%%% color setup
\ifcsdef{colorlet}{%
\colorlet{tablebodycolor}{white!100}
\colorlet{tablerowcolor}{gray!10}
\colorlet{tableheadcolor}{gray!25}
}{}
%%% Set document layout / variables
\ifdoctools@applyLayout%
  \setlength{\parindent}{0pt}
  \setlength{\parskip}{0.5\baselineskip}
  \setcounter{secnumdepth}{2}
  \setcounter{tocdepth}{2}
\fi % end \ifdoctools@applyLayout%
%%% ---- Internal Variables ----
%% Font for Index Headings
\newcommand{\doctools@indexHeadFont}[1]{\textsc{#1}}
%%% ---- Commands ----
%% \bs
\newcommand{\bs}{\textbackslash}
%% \command
\newcommand{\command}[1]{%
\texttt{\textbackslash{}#1}\relax%
\ifdoctools@createIndexEntries%
  \index{\doctools@indexHeadFont{Command}!\textbackslash{}#1}%
\fi%
}%
%% \cs (shortcut for \command)
%% \cs might be defined by ltxdoc, therefore it needs to be deleted
%% before it can be redefined.
\ifcsdef{cs}{\csundef{cs}}{}%
\let\cs\command%
%% \environment
\ifcsdef{environment}{\csundef{environment}}{}
\newcommand{\environment}[1]{%
\texttt{#1}%
\ifdoctools@createIndexEntries
  \index{\doctools@indexHeadFont{Environment}!#1}%
\fi
}%
%% \env
\newcommand{\env}[1]{\environment{#1}}
%% \package
\newcommand{\package}[1]{%
\texttt{#1}%
\ifdoctools@createIndexEntries
\index{\doctools@indexHeadFont{Package}!#1}%
\fi
}%
%% \ltxclass
\newcommand{\ltxclass}[1]{%
\texttt{#1}%
\ifdoctools@createIndexEntries
\index{\doctools@indexHeadFont{Class}!#1}%
\fi
}%
%% \marg
\ifcsdef{marg}{}{% if not defined
\ifcsdef{meta}%
  {\newcommand\marg[1]{\texttt{\{}\meta{#1}\texttt{\}}}}%
  {\newcommand\marg[1]{%
\texttt{\{}%
$\langle${\normalfont\slshape#1}$\rangle$%
\texttt{\}}}}%
}%
%% \oarg
\ifcsdef{oarg}{}{% if not defined
\ifcsdef{meta}%
  {\newcommand\oarg[1]{\texttt{[}\meta{#1}\texttt{]}}}%
  {\newcommand\oarg[1]{%
\texttt{[}%
$\langle${\normalfont\slshape#1}$\rangle$%
\texttt{]}}}%
}%
%% \arg
\ifcsdef{arg}{%
  \csundef{arg}%
  \newcommand\arg[1]{\{\texttt{#1}\}}%
}{}%
%% \option
\newcommand{\option}[1]{%
\texttt{#1}%
\ifdoctools@createIndexEntries%
\index{option!#1}%
\fi
}%
%% \parameter
\newcommand{\parameter}[1]{%
\texttt{#1}%
}%
%% \person
\newcommand{\person}[1]{\textsc{#1}}
%% \AfterLastParam
\newcommand{\AfterLastParam}{\par\noindent}
%% \Default
\newcommand{\Default}[1]{\par Default: \texttt{#1} \par}
%% \Example
\newcommand{\Example}[1]{\par Example: \texttt{#1} \par}
\newenvironment{Optionlist}{%
\begin{flushleft}%
\vspace{-2\parskip}
%%  Style  changes
\small\renewcommand{\arraystretch}{1.4}%
%%  table
\begin{tabular} {>{\ttfamily}l<{\normalfont}p{0.7\textwidth}}%
}{% end of environment
\end{tabular}%
\end{flushleft}%
}%
%%% ---- engine names ----
%% \latex
\newcommand{\latex}{\LaTeX\xspace}
%%% ---- doc.sty modifications ----
\colorlet{doctools@ColorCodeNames}{blue!50!black}
%%% Overwrite font for \meta
\def\meta@font@select{\normalfont\slshape} % original: \itshape
\ifcsdef{PrintMacroName}
   {\def\PrintMacroName#1{\strut \MacroFont %
   \color{doctools@ColorCodeNames}\string #1\ }}{}
\newcounter{MacroName} % hyperref uses \theH<counter>
\providecommand*{\theHMacroName}{\theMacroName}
%% create label
\ifcsdef{PrintDescribeMacro}
   {\def\PrintDescribeMacro#1{%
   \strut \MacroFont %
   \color{doctools@ColorCodeNames} \string #1\ }}{}
\ifcsdef{PrintDescribeEnv}
   {\def\PrintDescribeEnv#1{\strut \MacroFont %
   \color{doctools@ColorCodeNames} #1\ }}{}
\ifcsdef{PrintEnvName}
   {\def\PrintEnvName#1{\strut \MacroFont %
   \color{doctools@ColorCodeNames} #1\ }}{}
%%% disable the index preamble if index entries are generated by this package
\ifdoctools@createIndexEntries
\ifcsdef{index@prologue}
     {\def\index@prologue{\section*{Index}\markboth{Index}{Index}}}
     {}
\fi
%%% ---- listings environments for LaTeX code
%%% Overwriting the environment macrocode for printing the code in a dtx file.
\ifcsdef{macrocode}{\csundef{macrocode}}{}
\lstnewenvironment{macrocode}{\lstset{style=lstDocStyleLaTeXCode}}{}
%%% environment code examples.
\lstnewenvironment{latexcode}{\lstset{style=lstDemoStyleLaTeXCode}}{}
\newcounter{lstFirstLine}
\newcounter{lstLastLine}
\setcounter{lstLastLine}{0}
\setcounter{lstFirstLine}{0}
\newcommand{\printCodeFromFile}[3][]{%
\ifstrempty{#1}{}{%
  \setcounter{lstFirstLine}{#1}%
}%
\setcounter{lstLastLine}{#2}%
\lstinputlisting[%
  firstnumber=\thelstFirstLine,%
  firstline=\thelstFirstLine,%
  lastline=\thelstLastLine,%
  nolol=true,
  style=lstDemoStyleLaTeXCode]%
  {#3}%
%% set counter to lastLine + 1
\setcounter{lstFirstLine}{\thelstLastLine}
\addtocounter{lstFirstLine}{1}
}
%% Command for printing the filename
\ifcsdef{urlstyle}{}{\usepackage{url}}
\DeclareUrlCommand{\PrintFileName}{\urlstyle{tt}}
%%
\newcounter{file}
%% hyperref uses \theH<counter>
\providecommand*{\theHfile}{\thefile}
%% code from tex.stackexchange with the
%% the help from Heiko Oberdiek.
\newcommand*{\labelfile}[1]{%
  %% convert all "/" to "/," (comma list) and save in \IndexFileA
  \StrSubstitute{#1}{/}{/,}[\IndexFileA]%
  %% define \IndexFileB as empty (used for the output string)
  \let\IndexFileB\@empty
  %% parse and convert \IndexFileA using \@AddFileEntry
  \expandafter
  \comma@parse@normalized\expandafter{\IndexFileA}\@AddFileEntry
  %% create label and print to index
  \@bsphack
  \renewcommand*{\theHfile}{#1}%
  \refstepcounter{file}%
  \ifcsdef{phantomsection}{\phantomsection}{}
  \label{file:#1}%
  \ifdoctools@createIndexEntries
  \index{\textsc{Files}!\IndexFileB}%
  \fi
  \@esphack
}
%% add entries of comma list to the index.
\newcommand*{\@AddFileEntry}[1]{%
  \ifx\IndexFileB\@empty
    %% add first entry to index with lexEntry@{printEntry}
    \def\IndexFileB{#1@#1}%
  \else
    \expandafter\def\expandafter\IndexFileB\expandafter{%
    %% add following entries to index with
    %% previousEntries!lexEntry@{printEntry}
\IndexFileB!%
#1@#1%
    }%
  \fi
}
%% Print out filename and create a link if the label exists.
\newcommand*{\file}[1]{%
  \ifcsdef{hyperref}%
    {\hyperref[file:#1]{\PrintFileName{#1}}}%
    {\PrintFileName{#1}}%
}%
%%
} % end of \AtBeginDocument

\endinput
%%
%% End of file `doctools.sty'.
