%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% CONTAINS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% to-geom.sty
% Extended geometry utilities
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% DESCRIPTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Allows mid-text, consistent changing of
% page geometry.
%
% This file is part of the TeXoffice-suite
% by LDericher
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% PREREQUISITES %%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% package geometry
% package scrpage2
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% PACKAGE OPTIONS %%%%%%%%%%%%%%%%%%%%%%%%%%
%
% twoside:
%   Activate two-sided typesetting.
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% INTERFACE %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Border Margins
%
% \TeXofficeMargin        - Default
%
% \TeXofficeLeftmargin    - Left
% \TeXofficeRightmargin   - Right
% \TeXofficeTopmargin     - Top
% \TeXofficeBottommargin  - Bottom
% \TeXofficeOddsideMargin - Additional inner
%
% Set all margins
%
% \TeXofficeMargin20mm
% \TeXofficeResetmargins{}
%
% ------------------------------------------
%
% Marginal notes
%
% \TeXofficeMarginparsep   - Spacing
% \TeXofficeMarginparwidth - Width
%
% Disable marginal notes
%
% \TeXofficeNomarginpar{}
%
% ------------------------------------------
%
% Header and Footer
%
% \TeXofficeHeadsep       - Header Spacing
% \TeXofficeHeadheight    - Header Height
% \TeXofficeHeadrulegauge - Headrule width
% \TeXofficeHeadrulewidth - Headrule span
% \TeXofficeHeadrulesep   - Headrule Spacing
%
% \TeXofficeFootsep       - Footer Spacing
% \TeXofficeFootheight    - Footer Height
% \TeXofficeFootrulegauge - Footrule width
% \TeXofficeFootrulewidth - Footrule span
% \TeXofficeFootrulesep   - Footrule Spacing
%
% Disable rules
%
% \TeXofficeNoheadrule{}
% \TeXofficeNofootrule{}
%
% Disable everything
%
% \TeXofficeNoheader{}
% \TeXofficeNofooter{}
%
% Setting Header and Footer
%
% \TeXofficeHeader
%   {content}
% \TeXofficeFooter
%   {content}
% \TeXofficeAdjustheader
%   {content}
% \TeXofficeAdjustfooter
%   {content}
% Arguments:
%   content - Content to be placed
%
% ------------------------------------------
%
% Inverse printer scaling
%
% Find this by e.g. printing out a box of
% fixed size:
%
%   \begin{tabular}{@{}|@{}p{100mm}@{}|@{}}%
%     \hline%
%     \begin{minipage}[c][100mm][c]{100mm}%
%     \end{minipage} \tabularnewline%
%     \hline%
%   \end{tabular}%
%
% Then measure the resulting distance. If
% that example results in 98mm on a printed
% page, TeXofficePrintScale should be set to
%
%   98/100 = .98
%
% Default value works fine most of the time.
%
% \TeXofficePrintscale
%
% ------------------------------------------
%
% Measurements
%
% \@TOGeomGetheight
%   {variable}
%   {content}
% \@TOGeomGetwidth
%   {variable}
%   {content}
% Arguments:
%   variable - length type variable to set
%   content - any content to be measured
% Measure height or width of any content
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% AUTHOR %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Joern-Michael 'LDericher' Miehe
%  jmm@jmmworks.de
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% EXAMPLES %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Typesetting default-margined page(s) with
% default LaTeX-size header and footer:
%
%   \documentclass[a4paper]{scrreprt}
%   \usepackage{to-geom}
%   \usepackage{lipsum}
%
%   \begin{document}
%     \section{Section}
%     \lipsum
%   \end{document}
%
%-------------------------------------------
%
% Changing layout in mid-text
%
%   \usepackage{to-geom}
%   \usepackage{lipsum}
%
%   \section{Section}
%   % Default header, no marginal notes,
%   % default footer
%   \lipsum
%
%   \TeXofficeHeadheight12pt
%   \TeXofficeGeometry
%   % Smaller header, no marginal notes,
%   % default footer
%   \lipsum
%
%   \TeXofficeMarginparwidth1in
%   \TeXofficeNofooter
%   \pagestyle{empty}
%   \TeXofficeGeometry
%   % Smaller header, 1in of marginal notes,
%   % no footer
%   \lipsum
%
%-------------------------------------------
%
% Saving and loading layouts works
% as defined by package 'geometry'
%
%   \usepackage{to-geom}
%   \usepackage{lipsum}
%
%   \section{Section}
%   % Default header, no marginal notes,
%   % default footer
%   \savegeometry{default}
%   \lipsum
%
%   \TeXofficeMarginparwidth1in
%   \TeXofficeNofooter
%   \TeXofficeGeometry
%   % Default header, 1in of marginal notes,
%   % no footer
%   \savegeometry{fancy}
%   \pagestyle{empty}
%   \lipsum
%
%   \loadgeometry{default}
%   % Default header, no marginal notes,
%   % default footer
%   \pagestyle{plain}
%   \lipsum
%
%   \loadgeometry{fancy}
%   % Default header, 1in of marginal notes,
%   % no footer
%   \pagestyle{empty}
%   \lipsum
%
%-------------------------------------------
%
% For head- and/or footrules, try adding
%
%   \TeXofficeHeadrulegauge.4pt
%   \TeXofficeFootrulegauge.4pt
%   \TeXofficeGeometry % Apply!
%
% somewhere.
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\NeedsTeXFormat{LaTeX2e}
\ProvidesPackage{to-geom}[2014/03/01 TeXoffice geometry utilities]

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Package options

% Book layout
\DeclareOption{twoside}{%
  \typeout{TOGeom enters twosided typesetting mode.}%
  \def\@TOGeomTwosideSwitch{}%
}

% Eat unknown options
\DeclareOption*{%
  \typeout{TOGeom eats \CurrentOption.}%
  \PackageWarningNoLine{to-geom}{Script devoured the unknown: \CurrentOption}%
}

% Finalize TeXoffice options
\ProcessOptions\relax

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Packages

\RequirePackage{geometry}
\RequirePackage{scrlayer-scrpage}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Customizing header and footer

% Use normal font in header and footer
\setkomafont{pageheadfoot}{\normalfont}
% Reset fields
\clearscrheadings
% Use header and footer everywhere
\pagestyle{scrheadings}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Use header and footer on title page

\let\@TOGeomOldmaketitle\maketitle    % Rename \maketitle to \@TOGeomOldmaketitle
\let\@TOGeomOldtoc\tableofcontents    % Rename \maketitle to \@TOGeomOldmaketitle

\renewcommand{\maketitle}{%     % Redefine \maketitle by ...
  \@TOGeomOldmaketitle%         % ... using old \maketitle
  \thispagestyle{scrheadings}%  % ... and setting the usual pagestyle
}

\renewcommand{\tableofcontents}{% Redefine \tableofcontents by ...
  \@TOGeomOldtoc%               % ... using old \maketitle
  \thispagestyle{scrheadings}%  % ... and setting the usual pagestyle
}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Variables

\newlength\TeXofficeMargin                % Default border margin

\newlength\TeXofficeOddsideMargin         % Inner/Left binding offset
\newlength\TeXofficeLeftmargin            % Left   margin
\newlength\TeXofficeRightmargin           % Right  margin
\newlength\TeXofficeTopmargin             % Top    margin
\newlength\TeXofficeBottommargin          % Bottom margin

\newlength\TeXofficeMarginparsep          % Maximum marginal notes spacing
\newlength\TeXofficeMarginparwidth        % Marginal notes width

\newlength\TeXofficeHeadsep               % Maximum header spacing
\newlength\TeXofficeHeadheight            % Header height

\newlength\TeXofficeHeadrulegauge         % Header separation rule thickness
\newcommand{\TeXofficeHeadrulewidth}      % Header separation rule span
  {\textwidth}                            % % Defaults to full text width
\newcommand{\TeXofficeHeadrulesep}        % Header separation rule spacing
  {.5\TeXofficeHeadsep}                   % % Defaults to half the headsep

\newlength\TeXofficeFootsep               % Maximum footer spacing
\newlength\TeXofficeFootheight            % Footer height

\newlength\TeXofficeFootrulegauge         % Footer separation rule thickness
\newcommand{\TeXofficeFootrulewidth}      % Footer separation rule span
  {\textwidth}                            % % Defaults to full text width
\newcommand{\TeXofficeFootrulesep}        % Footer separation rule spacing
  {.5\TeXofficeFootsep}                   % % Defaults to half the footsep

\newcommand{\TeXofficePrintscale}         % Printer specific scaling (default conditions)
  {0.964912281}
\renewcommand{\TeXofficePrintscale}{1}    % Printer specific scaling (perfect conditions)

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Commands for geometry

% Internal, hidden variables
\newlength\@TOGeomHeadHeight      % Header height
\newlength\@TOGeomFootHeight      % Footer height
\newlength\@TOGeomHeadSep         % Header spacing
\newlength\@TOGeomFootSep         % Footer spacing
\newlength\@TOGeomFootSkip        % Footer skipping
\newlength\@TOGeomOddsideMargin   % Inner/Left binding offset
\newlength\@TOGeomLeftMargin      % Left border margin
\newlength\@TOGeomTopMargin       % Top border margin
\newlength\@TOGeomRightMargin     % Right border margin
\newlength\@TOGeomBottomMargin    % Bottom border margin
\newlength\@TOGeomMarginparSep    % Marginal notes spacing
\newlength\@TOGeomMarginparWidth  % Marginal notes width

% Flush settings
\newcommand{\TeXofficeGeometry}{%
  % Normally, just use the set headheight value
  \@TOGeomHeadHeight\TeXofficeHeadheight%
  % If headheight is defined (>0)
  \ifdim\@TOGeomHeadHeight>\z@%
    % Then use set spacing value
    \@TOGeomHeadSep\TeXofficeHeadsep%
    % If a headrule should be drawn
    \ifdim\TeXofficeHeadrulegauge>\z@%
      % Add space for the headrule
      \addtolength{\@TOGeomHeadHeight}{\TeXofficeHeadrulegauge}%
      \addtolength{\@TOGeomHeadHeight}{\TeXofficeHeadrulesep}%
      % Take space from the head spacing
      \addtolength{\@TOGeomHeadSep}{-\TeXofficeHeadrulegauge}%
      \addtolength{\@TOGeomHeadSep}{-\TeXofficeHeadrulesep}%
    \fi%
  \else%
    % Else use no spacing
    \@TOGeomHeadSep\z@%
  \fi%
  % Adapt values to printer
  \@TOGeomOddsideMargin\TeXofficePrintscale\TeXofficeOddsideMargin%
  \@TOGeomLeftMargin\TeXofficePrintscale\TeXofficeLeftmargin%
  \@TOGeomTopMargin\TeXofficePrintscale\TeXofficeTopmargin%
  \@TOGeomRightMargin\TeXofficePrintscale\TeXofficeRightmargin%
  \@TOGeomBottomMargin\TeXofficePrintscale\TeXofficeBottommargin%
  \@TOGeomMarginparWidth\TeXofficePrintscale\TeXofficeMarginparwidth%
  % Normally, just use the set footheight value
  \@TOGeomFootHeight\TeXofficeFootheight%
  % If footheight is defined (>0)
  \ifdim\@TOGeomFootHeight>\z@%
    % Then use set spacing value
    \@TOGeomFootSep\TeXofficeFootsep%
    % If a footrule should be drawn
    \ifdim\TeXofficeFootrulegauge>\z@%
      % Add space for the footrule
      \addtolength{\@TOGeomFootHeight}{\TeXofficeFootrulegauge}%
      \addtolength{\@TOGeomFootHeight}{\TeXofficeFootrulesep}%
      % Take space from the foot spacing
      \addtolength{\@TOGeomFootSep}{-\TeXofficeFootrulegauge}%
      \addtolength{\@TOGeomFootSep}{-\TeXofficeFootrulesep}%
    \fi%
    % Then use separation and height for skip value
    \@TOGeomFootSkip\@TOGeomFootSep%
    \addtolength{\@TOGeomFootSkip}{\@TOGeomFootHeight}%
    % Because footer centers around footskip line
    % placement must be adjusted relative to textheight
    \addtolength{\@TOGeomFootSkip}{-.5\@TOGeomFootHeight}%
    % ... and relative to paper bottom
    \addtolength{\@TOGeomBottomMargin}{.5\@TOGeomFootHeight}%
  \else%
    % Else use no spacing
    \@TOGeomFootSkip\z@%
  \fi%
%
  % If TeXofficemarginparwidth is defined (>0)
  \ifdim\TeXofficeMarginparwidth>\z@%
    % Then use set spacing value
    \@TOGeomMarginparSep\TeXofficeMarginparsep%
  \else%
    % Else use no spacing
    \@TOGeomMarginparSep\z@%
  \fi%
%
  \def\@TOGeomTwoside{twoside=false}%
  \ifdefined\@TOGeomTwosideSwitch%
    \def\@TOGeomTwoside{twoside=true}%
  \fi%
%
  % Create and use new geometry
  \expandafter\newgeometry\expandafter{%
    % with orientation,
    \@TOGeomTwoside, bindingoffset=\@TOGeomOddsideMargin,
    % margins,
    left=\@TOGeomLeftMargin, right=\@TOGeomRightMargin, top=\@TOGeomTopMargin, bottom=\@TOGeomBottomMargin,%
    % header definitions,
    headheight=\@TOGeomHeadHeight, headsep=\@TOGeomHeadSep,%
    % footer definitions,
    footskip=\@TOGeomFootSkip,%
    % margin notes definitions and
    marginparsep=\@TOGeomMarginparSep, marginparwidth=\@TOGeomMarginparWidth,%
    % include every content into that
    includeall,%
    % showframe,%
  }%
}

% Propagate default border margin to margin variables
\newcommand{\TeXofficeResetmargins}{%
  % reset variable to default
  \TeXofficeLeftmargin\TeXofficeMargin%
  \TeXofficeRightmargin\TeXofficeMargin%
  \TeXofficeTopmargin\TeXofficeMargin%
  \TeXofficeBottommargin\TeXofficeMargin%
}

% Remove headrule from layout
\newcommand{\TeXofficeNoheadrule}{%
  \TeXofficeHeadrulegauge\z@%
}

% Remove footrule from layout
\newcommand{\TeXofficeNofootrule}{%
  \TeXofficeFootrulegauge\z@%
}

% Remove header from layout
\newcommand{\TeXofficeNoheader}{%
  % alter layout
  \TeXofficeNoheadrule%
  \TeXofficeHeadheight\z@%
  % empty
  \@TOGeomHeadOut{}%
}

% Remove footer from layout
\newcommand{\TeXofficeNofooter}{%
  % alter layout
  \TeXofficeNofootrule%
  \TeXofficeFootheight\z@%
  % empty
  \@TOGeomFootOut{}%
}

% Remove marginal notes from layout
\newcommand{\TeXofficeNomarginpar}{%
  \TeXofficeMarginparwidth\z@%
}

% Internal, hidden variables
\newlength\@TOGeomAdditionalDepth     % Height deviation by depth component

% Measure full height (including below baseline)
\newcommand{\@TOGeomGetheight}[2]{%
  % Measure height of input (above baseline)
  \settoheight{#1}{\vbox{#2}}%
  % Measure depth of input (below baseline)
  \settodepth{\@TOGeomAdditionalDepth}{\vbox{#2}}%
  % Return
  \addtolength{#1}{\@TOGeomAdditionalDepth}%
}

% Measure full width (including below baseline)
\newcommand{\@TOGeomGetwidth}[2]{%
  % Measure width of input (above baseline)
  \settowidth{#1}{\hbox{#2}}%
}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Commands for header/footer output

% Use commands from scrpage2
\let\@TOGeomHeadOut\chead
\let\@TOGeomFootOut\cfoot

% Internal command for setting header
\newcommand{\@TOGeomHeader}[1]{%
  \@TOGeomHeadOut{%
    % Use total headheight and textwidth
    \begin{minipage}[t][\@TOGeomHeadHeight][t]{\textwidth}%
      % Output content
      #1%
      % If a headrule should be present
      \ifdim\TeXofficeHeadrulegauge>\z@%
        % draw it at the bottom of our minipage
        \vfill%
        \kern\z@\hfill\rule{\TeXofficeHeadrulewidth}{\TeXofficeHeadrulegauge}\hfill\kern\z@%
      \fi%
    \end{minipage}%
  }%
}

% Internal command for setting footer
\newcommand{\@TOGeomFooter}[1]{%
  \@TOGeomFootOut{%
    % Use total footheight and textwidth
    \begin{minipage}[t][\@TOGeomFootHeight][t]{\textwidth}%
      % If a footrule should be present
      \ifdim\TeXofficeFootrulegauge>\z@%
        % draw it at the top of our minipage
        \kern\z@\hfill\rule{\TeXofficeFootrulewidth}{\TeXofficeFootrulegauge}\hfill\kern\z@%
        \vfill%
      \fi%
      % Output content
      #1%
    \end{minipage}%
  }%
}

% Stretch content into the present header
\newcommand{\TeXofficeHeader}[1]{%
  % Output to header
  \@TOGeomHeader{%
    % Use usable headheight and full textwidth
    \begin{minipage}[t][\TeXofficeHeadheight][t]{\textwidth}%
      % Output content
      #1%
    \end{minipage}%
  }%
}

% Stretch content into the present footer
\newcommand{\TeXofficeFooter}[1]{%
  % Output to footer
  \@TOGeomFooter{%
    % Use usable footheight and full textwidth
    \begin{minipage}[t][\TeXofficeFootheight][t]{\textwidth}%
      % Output content
      #1%
    \end{minipage}%
  }%
}

% Create header snugly holding the content
\newcommand{\TeXofficeAdjustheader}[1]{%
  % Measure rendered height of input
  \@TOGeomGetheight{\TeXofficeHeadheight}{#1}%
  % Setting a minimum improves this
  \ifdim\TeXofficeHeadheight<14.0675pt%
    % Value generated by bisection testing
    \TeXofficeHeadheight14.0675pt%
  \fi%
  % Recalculate geometry
  \TeXofficeGeometry%
  % Output to header
  \TeXofficeHeader{#1}%
}

% Create footer snugly holding the content
\newcommand{\TeXofficeAdjustfooter}[1]{%
  % Measure rendered height of input
  \@TOGeomGetheight{\TeXofficeFootheight}{#1}%
  % Recalculate geometry
  \TeXofficeGeometry%
  % Output to footer
  \TeXofficeFooter{#1}%
}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Default Values
% Mostly as in default KOMAscript a4 page setup

\TeXofficeHeadheight18pt        % Header height 18 points
\TeXofficeHeadsep21pt           % Header margin 21 points
\TeXofficeHeadrulegauge0pt      % No header separation rule

\TeXofficeFootheight18pt        % Footer height 18 points
\TeXofficeFootsep32pt           % Footer margin 32 points
\TeXofficeFootrulegauge0pt      % No footer separation rule

\TeXofficeMarginparwidth0pt     % No marginal notes section
\TeXofficeMarginparsep12pt      % Marginal notes margin 12 points

\TeXofficeOddsideMargin0pt      % Additional inner margin
\TeXofficeMargin20mm            % Default border margin 2 centimeters
\TeXofficeResetmargins          % Propagate border margins
\TeXofficeLeftmargin25mm        % Left margin 2.5 centimeters

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Create default geometry

\TeXofficeGeometry
