% publist.bbx, biblatex bibliography style by Juergen Spitzmueller
% requires biblatex >= 3.4
%
% This work may be distributed and/or modified under the
% conditions of the LaTeX Project Public License, either version 1.3
% of this license or (at your option) any later version.
% The latest version of this license is in
%   http://www.latex-project.org/lppl.txt
% and version 1.3 or later is part of all distributions of LaTeX
% version 2003/12/01 or later.
%
% This work has the LPPL maintenance status "maintained".
% 
% This Current Maintainer of this work is Jürgen Spitzmüller.
%
% This work consists of the file publist.bbx
%
%
% The purpose of this file is to provide a biblatex bibliography style
% for (numbered) publication lists where the own name is omitted and
% co-authors are marked as such.
%
% Please send suggestions and bug reports to 
% https://github.com/jspitz/biblatex-publist
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\def\bpl@version{2.13}
\def\bpl@rdate{2024/08/21}

\ProvidesFile{publist.bbx}[\bpl@rdate\space v.\bpl@version\space
                           biblatex bibliography style (JSP)]

\@ifpackagelater{biblatex}{2017/11/04}
    {}
    {\PackageError{biblatex-publist}
        {Outdated 'biblatex' package\MessageBreak
         Upgrade to biblatex v3.8 (2017/11/04) or later.\MessageBreak
         I found: '\csuse{ver@biblatex.sty}'.\MessageBreak
         This is a fatal error. I'm aborting now}%
     \endinput}


%
% Bibliography Options and Base Style
%

% Toggles and switches
%
\newif\if@marginyear\@marginyearfalse
\newif\if@hlyear\@hlyeartrue
\newif\if@fixyear\@fixyeartrue
\newif\if@pubstateextra\@pubstateextrafalse
\newif\if@hlauthor\@hlauthorfalse
\newif\if@givenfirst\@givenfirstfalse
\newtoggle{bpl@firstinit}
\newif\if@bpl@numbered\@bpl@numberedtrue
\newif\if@bpl@numberreset\@bpl@numberresetfalse
\newtoggle{bpl@linktitle}
\newtoggle{bpl@linktitleisbn}
\newtoggle{bpl@linktitleissn}
\newtoggle{bpl@linktitleurl}
\newtoggle{bpl@linktitledoi}
\newtoggle{bpl@citinfo}
\newtoggle{bpl@jifinfo}
\newtoggle{bpl@prinfo}
\toggletrue{bpl@prinfo}
\newtoggle{bpl@oainfo}
\newtoggle{bpl@oainfosimple}
\newif\if@bpl@reversenum\@bpl@reversenumfalse
\def\bpl@annots{}

% Valid options
%

% We use l3keys here since we use l3 within the definitions anyway.
\ExplSyntaxOn
\keys_define:nn { bpl }
{
    % plauthorname=<name>
    % Store author family name
    plauthorname.tl_set:N = \bpl@osurname,
    % plauthorfirstname=<name>
    % Store author first name
    plauthorfirstname.tl_set:N = \bpl@ofirstname,
    % plauthornameprefix=<name>
    % Store author name prefix
    plauthornameprefix.tl_set:N = \bpl@ovonpart,
    % marginyear=<true|false>
    % Print year in margin
    marginyear.code:n =
        {
         \str_if_eq:nnTF { #1 } { true }
         {
            \@marginyeartrue
            \reversemarginpar
         }{
            \@marginyearfalse
         }
       },
    marginyear.default:n = { true },
    % hlyear=<true|false>
    % Set year highlighted
    hlyear.legacy_if_set:n = @hlyear,
    % fixyear=<true|false>
    % Fix year at first position
    fixyear.legacy_if_set:n = @fixyear,
    % pubstateextra=<true|false>
    % Extra label for pubstates
    pubstateextra.legacy_if_set:n = @pubstateextra,
    pubstateextra.usage:n = preamble,
    % plauthorhandling=<highlight|omit>
    % Highlight or omit pl author?
    plauthorhandling.choice:,
    % highlight
    plauthorhandling / highlight.code:n =
      { 
       \@hlauthortrue
       \bpl@set@defsorting
      },
    % omit
    plauthorhandling / omit.code:n =
       {
         \@hlauthorfalse
         \bpl@set@defsorting
       },
    plauthorhandling.default:n = { omit },    
    % nameorder=<family-given|given-family>
    % Ordering of plauthor name
    nameorder.choice:,
    % given-family
    nameorder / given-family.code:n = { \@givenfirsttrue },
    % family-given
    nameorder / family-given.code:n = { \@givenfirstfalse },
    nameorder.default:n = { family-given },
    % plsorting=<sortingscheme>
    % Set a sorting scheme
    plsorting.code:n =
      { 
       \bpl@set@defsorting[#1]
      },
    plsorting.default:n = { ydt },
    % plauthorfirstinit=<true|false>
    % Pass initial as first name
    plauthorfirstinit.code:n =
        {
         \str_if_eq:nnTF { #1 } { true }
         {
            \toggletrue{bpl@firstinit}
         }{
            \togglefalse{bpl@firstinit}
         }
       },
    plauthorfirstinit.default:n = { true },
    % plnumbering=<global|local|global-descending|local-descending|none>
    % Select numbering scheme
    plnumbering .choice:,
    % global: use default consecutive numbering
    plnumbering / global .code:n = 
      { \@bpl@numberresetfalse },
    % local: use local numbering
    plnumbering / local .code:n = 
      { \@bpl@numberresettrue },
    % global-descending: use default consecutive numbering
    plnumbering / global-descending .code:n = 
      { 
         \@bpl@numberresetfalse
         \@bpl@reversenumtrue
      },
    % local-descending: use local numbering
    plnumbering / local-descending .code:n = 
      { 
         \@bpl@numberresettrue
         \@bpl@reversenumtrue
      },
    % none: no numbering at all
    plnumbering / none .code:n = 
      { 
         \defbibenvironment{bibliography}
          {\list
           {}
           {\setlength{\leftmargin}{\bibhang}%
            \setlength{\itemindent}{-\leftmargin}%
            \setlength{\itemsep}{\bibitemsep}%
            \setlength{\parsep}{\bibparsep}}%
          }
          {\endlist}
          {\item}%
     },
    plnumbering.default:n = { global },
    plnumbering.usage:n = preamble,
    % annotations=<csv>
    % Store author name prefix
    annotations.tl_set:N = \bpl@annots,
    % linktitles=<all|url|doi|isbn|issn|none>
    linktitles .multichoice:,
    % Link all titles
    linktitles / all.code:n =
        {
             \toggletrue{bpl@linktitleisbn}
             \toggletrue{bpl@linktitleissn}
             \toggletrue{bpl@linktitleurl}
             \toggletrue{bpl@linktitledoi}
             \toggletrue{bpl@linktitle}
        },
    % Link no titles
    linktitles / none.code:n =
        {
             \togglefalse{bpl@linktitleisbn}
             \togglefalse{bpl@linktitleissn}
             \togglefalse{bpl@linktitleurl}
             \togglefalse{bpl@linktitledoi}
             \togglefalse{bpl@linktitle}
        },
    % Link titles with URL
    linktitles / url.code:n =
        {
         \toggletrue{bpl@linktitleurl}
         \toggletrue{bpl@linktitle}
        },
    % Link titles with DOI
    linktitles / doi.code:n =
        {
             \toggletrue{bpl@linktitledoi}
             \toggletrue{bpl@linktitle}
        },
    % Link titles with ISBN
    linktitles / isbn.code:n =
        {
           \toggletrue{bpl@linktitleisbn}
           \toggletrue{bpl@linktitle}
        },
    % Link titles with ISSN
    linktitles / issn.code:n =
        {
             \toggletrue{bpl@linktitleissn}
             \toggletrue{bpl@linktitle}
        },
    linktitles.default:n = { all },
    % citinfo=<true|false>
    % Information about citation numbers
    citinfo.code:n =
        {
         \str_if_eq:nnTF { #1 } { true }
         {
            \toggletrue{bpl@citinfo}
         }{
            \togglefalse{bpl@citinfo}
         }
       },
    citinfo.default:n = { true },
    % jifinfo=<true|false>
    % Impact factor information
    jifinfo.code:n =
        {
         \str_if_eq:nnTF { #1 } { true }
         {
            \toggletrue{bpl@jifinfo}
         }{
            \togglefalse{bpl@jifinfo}
         }
       },
    jifinfo.default:n = { true },
    % oainfo=<verbose|simple|nonr>
    % Output OpenAccess information
    oainfo .choice:,
    oainfo / verbose.code:n =
       {
         \toggletrue{bpl@oainfo}
         \togglefalse{bpl@oainfosimple}
       },
    oainfo / simple.code:n =
       {
         \toggletrue{bpl@oainfo}
         \toggletrue{bpl@oainfosimple}
       },
    oainfo / none.code:n =
       {
         \togglefalse{bpl@oainfo}
         \togglefalse{bpl@oainfosimple}
       },
    oainfo.default:n = { simple },
    % prinfo=<true|false>
    % Output peer-review information
    prinfo.code:n =
        {
         \str_if_eq:nnTF { #1 } { true }
         {
            \toggletrue{bpl@prinfo}
         }{
            \togglefalse{bpl@prinfo}
         }
       },
    prinfo.default:n = { true }
}

%
% Deprecated options
%
\keys_define:nn { bpl-deprecated }
{
    % plnumbered=<true|false|reset>
    % Select numbering scheme
    plnumbered .choice:,
    % false: no numbering at all
    plnumbered / false .code:n = 
      { 
         \defbibenvironment{bibliography}
          {\list
           {}
           {\setlength{\leftmargin}{\bibhang}%
            \setlength{\itemindent}{-\leftmargin}%
            \setlength{\itemsep}{\bibitemsep}%
            \setlength{\parsep}{\bibparsep}}%
          }
          {\endlist}
          {\item}%
     },
    % true: use default consecutive numbering
    plnumbered / true .code:n = 
      { 
        \@bpl@numberresetfalse
      },
    % reset: use local numbering
    plnumbered / reset .code:n = 
      {
        \@bpl@numberresettrue
      },
    plnumbered.default:n = { true },
    plnumbered.usage:n = preamble,
    % reversenumbering=<true|false>
    % Use descending numbers
    reversenumbering.code:n = 
       { 
         \str_if_eq:nnTF { #1 } { true }
           {
             \@bpl@reversenumtrue
         }{
             \@bpl@reversenumfalse
         }
       },
    reversenumbering.usage:n = preamble,
    % boldyear=<true|false>
    % Set year bold
    boldyear.legacy_if_set:n = @hlyear,
    % linktitleall=<true|false>
    % Link all titles
    linktitleall.code:n =
        {
         \str_if_eq:nnTF { #1 } { true }
         {
             \toggletrue{bpl@linktitleisbn}
             \toggletrue{bpl@linktitleissn}
             \toggletrue{bpl@linktitleurl}
             \toggletrue{bpl@linktitledoi}
             \toggletrue{bpl@linktitle}
         }{
             \togglefalse{bpl@linktitleisbn}
             \togglefalse{bpl@linktitleissn}
             \togglefalse{bpl@linktitleurl}
             \togglefalse{bpl@linktitledoi}
             \togglefalse{bpl@linktitle}
         }
       },
    linktitleall.default:n = { true },
    % linktitleurl=<true|false>
    % Link titles with URL
    linktitleurl.code:n =
        {
         \str_if_eq:nnTF { #1 } { true }
         {
             \toggletrue{bpl@linktitleurl}
             \toggletrue{bpl@linktitle}
         }{
             \togglefalse{bpl@linktitleurl}
         }
       },
    linktitleurl.default:n = { true },
    % linktitledoi=<true|false>
    % Link titles with DOI
    linktitledoi.code:n =
        {
         \str_if_eq:nnTF { #1 } { true }
         {
             \toggletrue{bpl@linktitledoi}
             \toggletrue{bpl@linktitle}
         }{
             \togglefalse{bpl@linktitledoi}
         }
       },
    linktitledoi.default:n = { true },
    % linktitledoi=<true|false>
    % Link titles with ISBN
    linktitleisbn.code:n =
        {
         \str_if_eq:nnTF { #1 } { true }
         {
             \toggletrue{bpl@linktitleisbn}
             \toggletrue{bpl@linktitle}
         }{
             \togglefalse{bpl@linktitleisbn}
         }
       },
    linktitleisbn.default:n = { true },
    % linktitledoi=<true|false>
    % Link titles with ISSN
    linktitleissn.code:n =
        {
         \str_if_eq:nnTF { #1 } { true }
         {
             \toggletrue{bpl@linktitleissn}
             \toggletrue{bpl@linktitle}
         }{
             \togglefalse{bpl@linktitleissn}
         }
       },
    linktitleissn.default:n = { true }
}

% Command to set options
\NewDocumentCommand { \ExecutePublistOptions } { m }
{
  \keys_set:nn { bpl } { #1 }
}

% Command to set deprecated options
\NewDocumentCommand { \ExecuteDepPublistOptions } { m m }
{
  \keys_set:nn { bpl-deprecated } { #1 }
  
  \PackageWarning{biblatex-publist}%
             {The~ option~ `#1'~ is~ deprecated!\MessageBreak
              Please~ use~ the~ option~ `#2'~ instead.}
}

\ExplSyntaxOff

% Biblatex options directly feed into the l3 options
%
\DeclareBibliographyOption{plauthorname}{\ExecutePublistOptions{plauthorname=#1}}
\DeclareBibliographyOption{plauthorfirstname}{\ExecutePublistOptions{plauthorfirstname=#1}}
\DeclareBibliographyOption{plauthornameprefix}{\ExecutePublistOptions{plauthornameprefix=#1}}
\DeclareBibliographyOption{plauthorfirstinit}[true]{\ExecutePublistOptions{plauthorfirstinit=#1}}
\DeclareBibliographyOption{plauthorhandling}[omit]{\ExecutePublistOptions{plauthorhandling=#1}}
\DeclareBibliographyOption{nameorder}[family-given]{\ExecutePublistOptions{nameorder=#1}}
\DeclareBibliographyOption{plsorting}[ydt]{\ExecutePublistOptions{plsorting=#1}}
\DeclareBibliographyOption{annotations}{\ExecutePublistOptions{annotations={#1}}}

\DeclareBibliographyOption{plnumbering}[global]{\ExecutePublistOptions{plnumbering=#1}}
\DeclareBibliographyOption{marginyear}[true]{\ExecutePublistOptions{marginyear=#1}}
\DeclareBibliographyOption{hlyear}[true]{\ExecutePublistOptions{hlyear=#1}}
\DeclareBibliographyOption{fixyear}[true]{\ExecutePublistOptions{fixyear=#1}}
\DeclareBibliographyOption{pubstateextra}[true]{\ExecutePublistOptions{pubstateextra=#1}}
\DeclareBibliographyOption{jifinfo}[true]{\ExecutePublistOptions{jifinfo=#1}}
\DeclareBibliographyOption{oainfo}[simple]{\ExecutePublistOptions{oainfo=#1}}
\DeclareBibliographyOption{prinfo}[true]{\ExecutePublistOptions{prinfo=#1}}
\DeclareBibliographyOption{citinfo}[true]{\ExecutePublistOptions{citinfo=#1}}

\DeclareBibliographyOption{linktitles}[all]{\ExecutePublistOptions{linktitles={#1}}}% Extra braces needed (multichoice)



% Deprecated Options
%
% Deprecated as of v. 1.4
\DeclareBibliographyOption{omitname}{%
    \PackageWarning{biblatex-publist}
        {The omitname option is deprecated!\MessageBreak
         Please use plauthorname instead.}{}%
    \def\bpl@osurname{#1}}
\DeclareBibliographyOption{omitfirstname}{%
    \PackageWarning{biblatex-publist}
         {The omitfirstname option is deprecated!\MessageBreak
          Please use plauthorfirstname instead.}{}%
    \def\bpl@ofirstname{#1}}
\DeclareBibliographyOption{omitnameprefix}{%
    \PackageWarning{biblatex-publist}
        {The omitnameprefix option is deprecated!\MessageBreak
         Please use plauthornameprefix instead.}{}%
    \def\bpl@ovonpart{#1}}
%
% Deprecated as of v. 2.0
\DeclareBibliographyOption{plnumbered}[true]{\ExecuteDepPublistOptions{plnumbered=#1}{plnumbering}}
\DeclareBibliographyOption{reversenumbering}[true]{\ExecuteDepPublistOptions{reversenumbering=#1}{plnumbering}}
\DeclareBibliographyOption{boldyear}[true]{\ExecuteDepPublistOptions{boldyear=#1}{hlyear}}
\DeclareBibliographyOption{linktitleall}[true]{\ExecuteDepPublistOptions{linktitleall=#1}{linktitles}}
\DeclareBibliographyOption{linktitleurl}[true]{\ExecuteDepPublistOptions{linktitleurl=#1}{linktitles}}
\DeclareBibliographyOption{linktitledoi}[true]{\ExecuteDepPublistOptions{linktitledoi=#1}{linktitles}}
\DeclareBibliographyOption{linktitleisbn}[true]{\ExecuteDepPublistOptions{linktitleisbn=#1}{linktitles}}
\DeclareBibliographyOption{linktitleissn}[true]{\ExecuteDepPublistOptions{linktitleissn=#1}{linktitles}}


% Base style
%

% Check if users have defined different base styles
% If not, use authoryear.
\newif\ifbpl@standardbasestyle\bpl@standardbasestylefalse
\@ifundefined{publistbasestyle}{%
    \newcommand*\publistbasestyle{authoryear}
    \bpl@standardbasestyletrue}{}

\RequireBibliographyStyle{\publistbasestyle}

\ExecuteBibliographyOptions{%
    pagetracker=true,
    labelnumber,
    useprefix=false,
    defernumbers=true%
}

\newcommand*\bpl@set@defsorting[1][\empty]{%
    \edef\bpl@scheme{#1}%
    \ifx\bpl@scheme\empty
        % Default sorting depends on plauthorhandling
        \if@hlauthor%
            \edef\bpl@scheme{ydnt}%
        \else
            \edef\bpl@scheme{ydt}%
        \fi
    \fi
    \ifx\@onlypreamble\@notprerr
        \newrefcontext[sorting=\bpl@scheme]
        \AtFollowingRefsections{\newrefcontext[sorting=\bpl@scheme]}
    \else
        \ExecuteBibliographyOptions{sorting=\bpl@scheme}
    \fi
}

% Initialize
\bpl@set@defsorting

% Execute these options only with the standard base style
\ifbpl@standardbasestyle
    \ExecuteBibliographyOptions{%
        maxnames=4,
        dashed=false}
\else
    % This corresponds to bib option dashed=false
    % (dashed option is not defined in every style)
    \providebibmacro*{bbx:savehash}{}%
    \renewbibmacro*{bbx:savehash}{}%
\fi


%
% Helper functions
%

% Only provided by biblatex 3.19ff., so we roll our own
\@ifundefined{AtNextRefsection}{%
   \newrobustcmd*{\AtNextRefsection}{%
      \ifundef\blx@hook@refsection@next
        {\gdef\blx@hook@refsection@next{\global\undef\blx@hook@refsection@next}}
        {}%
      \gappto\blx@hook@refsection@next%
    }
  \patchcmd{\blx@refsection@i}%
     {\csuse{blx@hook@refsectioninit}}%
     {\csuse{blx@hook@refsectioninit}\csuse{blx@hook@refsection@next}}
     {}{\PackageWarning{biblatex-publist}{Patching refsection failed!}}
}{}

% Only provided by biblatex 3.20ff., so we roll our own
\@ifundefined{AtFollowingRefsections}{%
  \newrobustcmd*{\AtFollowingRefsections}{\gappto\blx@hook@refsection@following}
  \patchcmd{\blx@refsection@i}%
     {\csuse{blx@hook@refsectioninit}}%
     {\csuse{blx@hook@refsectioninit}\csuse{blx@hook@refsection@following}}
     {}{\PackageWarning{biblatex-publist}{Patching refsection failed!}}
}{}

% Section count. We use l3 here to split the argument and do calculations
\ExplSyntaxOn

\int_new:N \l_bpl_sec_cnt_int

\NewDocumentCommand \GetSectionCount { >{\SplitList{,}} o }
{
  \IfNoValueTF{#1}{%
    \csnumdef{bpltmprefsection}{\c@refsection}
    \ifcsdef{bpl@secitems:\bpltmprefsection}{\csuse{bpl@secitems:\bpltmprefsection}}{}%
  }{
    \int_zero:N \l_bpl_sec_cnt_int
    \ProcessList{#1}{\__bpl_add_section_count}
    \int_use:N \l_bpl_sec_cnt_int
  }
}

\cs_new:Npn \__bpl_add_section_count #1
{
   \cs_if_exist:cT {bpl@secitems:#1}
        { \int_add:Nn \l_bpl_sec_cnt_int { \use:c{bpl@secitems:#1} } }
}

\ExplSyntaxOff

\newcommand*\GetTotalCount{%
  \csuse{bpl@items}%
}

%
% Removing braces from names (courtesy of egreg at
% http://tex.stackexchange.com/a/79583/19291)
% and normalize spaces
\def\bpl@normalize#1#2{%
    \begingroup
    \blx@indexnamesetup%
    \def\IeC##1{##1}%
    \protected@edef\@tempa{#1}%
    \gdef\@gtempa{}%
    \expandafter\bpl@@normalize\@tempa\@nil
    \endgroup
    \let#2\@gtempa
}
\def\bpl@@normalize#1{%
    \ifx#1\@nil\else
        \expandafter\gdef\expandafter%
        \@gtempa\expandafter{\@gtempa#1}%
        \expandafter\bpl@@normalize
    \fi
}
%
% String comparison methods. We use l3 here since this is more robust.
\ExplSyntaxOn

% 1. Check first token of macro.
%    Based on code by egreg on https://tex.stackexchange.com/a/405005
\prg_new_conditional:Nnn \bpl_firstletterequal:nn { T,F,TF,p }
 {
  % compare the two strings after full expansion:
  % f expansion is used so using explicit
  % strings or macros is the same
  \str_if_eq:eeTF
   { \str_head:f { #1 } }
   { \str_head:f { #2 } }
   { \prg_return_true: }
   { \prg_return_false: }
 }
\cs_generate_variant:Nn \str_head:n { f }

\NewExpandableDocumentCommand{\bpl@iffirstcharequal}{ m m m m }
{
  \bpl_firstletterequal:nnTF { #1 } { #2 } { #3 } { #4 }
}

% 2. Fully expanded macro content comparison
\NewExpandableDocumentCommand{\bpl@ifstreq}{ m m m m }
{
  \str_if_eq:eeTF { \text_purify:n { #1 } } { \text_purify:n { #2 } } { #3 } { #4 }
}

\ExplSyntaxOff
%
% Split plauthors list item
\def\bpl@lsurname{}
\def\bpl@lfirstname{}
\def\bpl@lvonpart{}
\def\bpl@splitpllist#1{%
    \begingroup
    \protected@edef\@tempa{#1}%
    \expandafter\endgroup
    \expandafter\bpl@@splitpllist\@tempa\relax%
}
\def\bpl@@splitpllist#1,#2,#3\relax{%
   \global\def\bpl@lfirstname{#1}%
   \global\def\bpl@lvonpart{#2}%
   \global\def\bpl@lsurname{#3}%
}
%
% Check if we have an entry in plauthors
% \bpl@ifplauthor{firstname}{prefix}{surname}{true}{false}
\newcommand*\bpl@ifplauthor[3]{%
    \newtoggle{checkplauthor}%
    \bpl@normalize{#1}{\bpl@tfirstname}%
    \bpl@normalize{#2}{\bpl@tvonpart}%
    \bpl@normalize{#3}{\bpl@tsurname}%
    \bpl@normalize{\bpl@osurname}{\bpl@esurname}%
    \bpl@normalize{\bpl@ofirstname}{\bpl@efirstname}%
    \bpl@normalize{\bpl@ovonpart}{\bpl@evonpart}%
    % Check if we are dealing with a plauthor
    % First the plauthorname as set via option
    \ifboolexpr{
        test { \bpl@ifstreq{\bpl@esurname}{\bpl@tsurname} }
        and
        ( test { \bpl@ifstreq{\bpl@efirstname}{\bpl@tfirstname} } or test { \ifdefstring{\bpl@ofirstname}{} }
          or ( test { \iftoggle{bpl@firstinit} } and test{ \bpl@iffirstcharequal{\bpl@efirstname}{\bpl@tfirstname} } )
        )
        and
        ( test { \bpl@ifstreq{\bpl@evonpart}{\bpl@tvonpart} } or test { \ifdefstring{\bpl@ovonpart}{} }) }
        {\toggletrue{checkplauthor}}{\togglefalse{checkplauthor}}%
    % Then the name(s) set via macro
    \def\bpl@lsurname{}%
    \def\bpl@lfirstname{}%
    \def\bpl@lvonpart{}%
    \renewcommand*{\do}[1]{%
        \bpl@splitpllist{##1}%
        \bpl@normalize{\bpl@lsurname}{\bpl@elsurname}%
        \bpl@normalize{\bpl@lfirstname}{\bpl@elfirstname}%
        \bpl@normalize{\bpl@lvonpart}{\bpl@elvonpart}%
        \ifboolexpr{
            test { \bpl@ifstreq{\bpl@elsurname}{\bpl@tsurname} }
            and
            ( test { \bpl@ifstreq{\bpl@elfirstname}{\bpl@tfirstname} } or test { \ifdefstring{\bpl@lfirstname}{} }
              or ( test { \iftoggle{bpl@firstinit} } and test{ \bpl@iffirstcharequal{\bpl@lfirstname}{\bpl@tfirstname} } )
            )
            and
            ( test { \bpl@ifstreq{\bpl@elvonpart}{\bpl@tvonpart} } or test { \ifdefstring{\bpl@lvonpart}{} }) }
            {\toggletrue{checkplauthor}}{}%
    }%
    \dolistloop{\bpl@plauthors}%
    \iftoggle{checkplauthor}%
        {\expandafter\@firstoftwo}%
        {\expandafter\@secondoftwo}%
}


%
% Customization settings
%

%
% The name of the publication list author
\def\bpl@osurname{}
\def\bpl@ofirstname{}
\def\bpl@ovonpart{}
%
% List to store multiple pl authors (for highlight only)
\def\bpl@plauthors{}
%
% Manual way to specify publication list author(s) name
\def\plauthorname{%
   \@ifnextchar[%
     {\plauthorname@i}
     {\plauthorname@i[]}%
}
\def\plauthorname@i[#1]{%
   \@ifnextchar[%
     {\plauthorname@ii{#1}}
     {\plauthorname@ii{#1}[]}%
}
\def\plauthorname@ii#1[#2]#3{%
    \listgadd{\bpl@plauthors}{#1,#2,#3}
}

%
% Formatting of year in margin par (if requested)
\providecommand*\plmarginyear[1]{%
    \raggedleft\small\textbf{#1}%
}

%
% Highlighting of the year with hlyear=true
\providecommand*\plyearhl[1]{%
    \mkbibbold{#1}%
}

%
% Highlighting of publist author with plauthorhandling=highlight
\providecommand*\plauthorhl[1]{%
    \mkbibbold{#1}%
}


%
% Field format definitions
%
\DeclareFieldFormat{bibentrysetcount}{\mkbibparens{\mknumalph{#1}}}
\DeclareFieldFormat{labelnumberwidth}{\mkbibbrackets{#1}}
\DeclareFieldFormat{shorthandwidth}{\mkbibbrackets{#1}}
\DeclareFieldFormat{related:parttranslationof}{\mkbibbrackets{#1}}

%
% Delimiters
%
% Omission of names in truncated autor list
\newcommand*\plnameomission{\bibellipsis\addcomma\addspace}
\newcommand*\plextrainfosep{\addsemicolon\addspace}


%
% Deal with numbering (resume numbers in refsections)
%
\csnumgdef{bpl@itemtotal}{0}
\csnumgdef{bpl@currentitem}{0}
\csnumgdef{bpl@saverefsection}{0}
\csnumgdef{bpl@secitems:0}{0}
\csnumgdef{bpl@savesecitems}{0}
\newcounter{bplitems}
\setcounter{bplitems}{0}
\newcounter{bplsecitems}
\setcounter{bplsecitems}{0}
\newcounter{bplbgitems}
\setcounter{bplbgitems}{0}
\newcounter{plnumgroup}
\setcounter{plnumgroup}{0}
\newbool{newsection}
\newbool{needbpxrerun}
\newbool{plnumgroup}
\def\resetplnumgroup{}

\newenvironment{plnumgroup}%
   {%
    \global\booltrue{plnumgroup}%
    \stepcounter{plnumgroup}%
    \setcounter{bplbgitems}{0}%
    \csnumgdef{bpl@numgroup@done}{0}%
    \if@bpl@numberreset%
       \ifbool{@bpl@reversenum}{%
          \csnumgdef{bpl@itemtotal}{\csuse{bpl@savesecitems:\theplnumgroup}}%
       }{}%
    \fi%
   }{%
    \AtNextRefsection{%
      \global\boolfalse{plnumgroup}%
      \stepcounter{plnumgroup}%
      \resetplnumgroup%
    }%
   }%

\preto\blx@refsection{\global\booltrue{newsection}}

% Possibility to manually make the space occupied by the label wider
\newlength\extralabelnumberwidth
\setlength\extralabelnumberwidth{0pt}

\defbibenvironment{bibliography}
    {%
     \addtolength{\labelnumberwidth}{\extralabelnumberwidth}%
     \ifbool{newsection}{\setcounter{bplsecitems}{0}}{}%
     \ifcsundef{bpl@savesecitems:\theplnumgroup}{%
         \csnumgdef{bpl@savesecitems:\theplnumgroup}{0}%
     }{}%
     \list
         {\printtext[labelnumberwidth]{%
          \printfield{labelprefix}%
          \printfield{labelnumber}}%
         }
         {\setlength{\labelwidth}{\labelnumberwidth}%
          \setlength{\leftmargin}{\labelwidth}%
          \setlength{\labelsep}{\biblabelsep}%
          \addtolength{\leftmargin}{\labelsep}%
          \setlength{\itemsep}{\bibitemsep}%
          \setlength{\parsep}{\bibparsep}%
         }%
          \renewcommand*{\makelabel}[1]{\hss##1}%
    }%
    {\endlist
     \if@bpl@numberreset
        \ifbool{manitemreset}{%
           % Set back start number after manually set section
           \global\csnumgdef{bpl@set@itemtotal}{0}%
           \global\boolfalse{manitemreset}%
        }{}%
        \ifnumgreater{\c@refsection}{\bpl@saverefsection}%
           {%
             \csnumdef{blx@labelnumber@\the\c@refsection}{0}%
             \ifbool{@bpl@reversenum}{%
                 \ifbool{plnumgroup}{%
                      \csnumgdef{bpl@numgroup@done}{\csuse{bpl@numgroup@done}+\csuse{bpl@savesecitems}}%
                      \csnumgdef{bpl@itemtotal}{\csuse{bpl@savesecitems:\theplnumgroup}-\csuse{bpl@numgroup@done}}%
                      \gdef\resetplnumgroup{\csnumgdef{bpl@itemtotal}{\csuse{bpl@set@itemtotal}}}%
                 }{%
                      \csnumgdef{bpl@itemtotal}{\csuse{bpl@set@itemtotal}}%
                 }
             }{%
                 \ifbool{plnumgroup}{%
                      \csnumgdef{bpl@itemtotal}{\csuse{bpl@itemtotal}+\csuse{bpl@savesecitems}}%
                      \gdef\resetplnumgroup{\csnumgdef{bpl@itemtotal}{\csuse{bpl@set@itemtotal}}}%
                 }{%
                      \csnumgdef{bpl@itemtotal}{\csuse{bpl@set@itemtotal}}%
                 }
             }%
            }{}%
     \else
        \ifnumgreater{\c@refsection}{\bpl@saverefsection}%
           {\if@bpl@reversenum
              \csnumgdef{bpl@itemtotal}{\csuse{bpl@itemtotal}}%
            \else
              \csnumgdef{bpl@itemtotal}{\csuse{bpl@itemtotal}+\csuse{bpl@currentitem}}%
            \fi%
           }{}%
      \fi
      \csnumgdef{bpl@saverefsection}{\c@refsection}%
      \if@bpl@reversenum%
         % Check if we have a changed value
         \global\boolfalse{needbpxrerun}%
         \ifcsdef{bpl@items:\therefsection}{%
             \ifnumequal{\value{bplitems}}{\numexpr\csuse{bpl@items:\therefsection}\relax}{}{%
                  \global\booltrue{needbpxrerun}
             }
         }{\global\booltrue{needbpxrerun}}
         % Write item count to the bpx file
         \if@filesw%
           \protected@write\bpl@bpxfile{}{%
              \protect\csdef{bpl@items:\therefsection}{\thebplitems}%
              \protect\csdef{bpl@savesecitems:\theplnumgroup}{\thebplbgitems}%
           }%
         \fi
      \fi
      % Write item count to the bpx file
      \if@filesw%
         \protected@write\bpl@bpxfile{}{%
             \protect\csdef{bpl@items}{\thebplitems}%
             \protect\csdef{bpl@secitems:\therefsection}{\thebplsecitems}%
         }%
      \fi
    }
    {%
      % We count all really output items for proper reverse numbering
      % (global and per section) and \GetTotalCount
      \stepcounter{bplitems}%
      \stepcounter{bplsecitems}%
      \ifbool{plnumgroup}{%
         \stepcounter{bplbgitems}%
         \csnumgdef{bpl@savesecitems}{\thebplsecitems}%
      }{}%   
      \item%
    }

\DeclareFieldFormat{labelnumber}{%
    \ifbool{newsection}{%
       % Fix start counter value
       \mkbibsecstart{#1}%
       \global\boolfalse{newsection}%
    }{}%
    \mkbibdesc{#1}%
    \csnumgdef{bpl@currentitem}{#1}%
}

\newrobustcmd{\mkbibdesc}[1]{%
    % Print labelnumber as actual number, plus item total
    \edef\bpl@current@item@no{\number\numexpr\csuse{bpl@itemtotal}+#1+\csuse{bpl@shift@itemtotal}\relax}%
    \bpl@current@item@no%
    % Store number in pbx file
    \if@filesw%
       \protected@write\bpl@bpxfile{}{%
          \csedef{bpl@itemnumber:\thefield{entrykey}}{\bpl@current@item@no}%
          \csedef{bpl@itemsec:\thefield{entrykey}}{\therefsection}%
       }%
    \fi%
}%

% Way to manually shift the numbering
\csnumgdef{bpl@shift@itemtotal}{0}
\newcommand*\shiftplnum[1]{%
    \csnumgdef{bpl@shift@itemtotal}{#1}%
}

% Way to manually set the numbering
\newbool{manitemset}
\newbool{manitemreset}
\csnumgdef{bpl@set@itemtotal}{0}
\newcommand*\setplnum[1]{%
   \csnumgdef{bpl@set@itemtotal}{#1-1}%
   \global\booltrue{manitemset}%
}

\newrobustcmd{\mkbibsecstart}[1]{%
 \ifbool{manitemset}{%
   \csnumgdef{bpl@itemtotal}{\csuse{bpl@set@itemtotal}}%
   \global\boolfalse{manitemset}%
   \if@bpl@numberreset
     \global\booltrue{manitemreset}%
   \fi
 }{%
   \csnumgdef{bpl@itemtotal}{\csuse{bpl@itemtotal}-#1+1}%
 }
}

%
% Reverse numbering
%
\AtBeginDocument{%
  \newread\bpl@read@bpxfile
  \immediate\openin\bpl@read@bpxfile=\jobname.bpx
  \loop\unless\ifeof\bpl@read@bpxfile
      \read\bpl@read@bpxfile to\bpx@data
      \ifeof\bpl@read@bpxfile%
      \else
          \bpx@data
      \fi
  \repeat
  \immediate\closein\bpl@read@bpxfile
  \newwrite\bpl@bpxfile
  \immediate\openout\bpl@bpxfile=\jobname.bpx
  \if@filesw%
      \protected@write\bpl@bpxfile{}{\@percentchar\space biblatex-publist auxiliary file:
                                     count of items for reverse numbering and stats}%
  \fi
  \AtEndDocument{%
     \ifbool{needbpxrerun}{%
         \PackageWarning{biblatex-publist}{Please rerun LaTeX!\MessageBreak
                                           Still counting items}%
     }{}
  }
}

\AtEndOfPackage{%
  \newcounter{prevrefsection}%
  \if@bpl@reversenum
    \renewrobustcmd{\mkbibdesc}[1]{%
       \ifbool{@bpl@numberreset}{%
          % Print the labelnumber as the total number of entries in the
          % current refsection, minus the actual labelnumber, plus one
          \ifbool{plnumgroup}{%
             \xdef\bpl@current@item@no{\number\numexpr\csuse{bpl@itemtotal}-#1+1\relax}%
             \bpl@current@item@no%
          }{%
             \ifcsdef{bpl@secitems:\therefsection}{%
                \xdef\bpl@current@item@no{\number\numexpr\csuse{bpl@secitems:\therefsection}-#1+1%
                         +\csuse{bpl@shift@itemtotal}\relax}%
             \bpl@current@item@no%
             }{%
                \xdef\bpl@current@item@no{\number\numexpr\csuse{bpl@itemtotal}-#1+1\relax}%
                \bpl@current@item@no%
             }%
          }%
       }{%
          % Use decreasing counter
          \ifcsdef{bpl@items:\theprevrefsection}{%
             \xdef\bpl@current@item@no{\number\numexpr\csuse{bpl@itemtotal}-#1+1%
                       -\csuse{bpl@items:\theprevrefsection}\relax}%
             \bpl@current@item@no%
          }{%
             \xdef\bpl@current@item@no{\number\numexpr\csuse{bpl@itemtotal}-#1+1\relax}%
             \bpl@current@item@no%
          }%
       }%
       % Store number in pbx file
       \if@filesw%
          \protected@write\bpl@bpxfile{}{%
             \csedef{bpl@itemnumber:\thefield{entrykey}}{\bpl@current@item@no}%
             \csedef{bpl@itemsec:\thefield{entrykey}}{\therefsection}%
             \csedef{bpl@itemtotal}{\csuse{bpl@itemtotal}}%
          }%
       \fi%
    }%
    \renewrobustcmd{\mkbibsecstart}[1]{%
       \setcounter{prevrefsection}{\therefsection}%
       \addtocounter{prevrefsection}{-1}%
       \ifbool{@bpl@numberreset}{%
          \ifbool{manitemset}{%
             % Start from manually set value and count down
             \csnumgdef{bpl@secitems:\therefsection}{\csuse{bpl@set@itemtotal}+1}\relax%
             \global\boolfalse{manitemset}%
          }{%
            \ifbool{plnumgroup}{%
                \csnumgdef{bpl@itemtotal}{\csuse{bpl@itemtotal}+\csuse{bpl@shift@itemtotal}}%
            }{%
                \csnumgdef{bpl@itemtotal}{\csuse{bpl@shift@itemtotal}}%
            }
          }%
       }{%
          \ifbool{manitemset}{%
             % Start from manually set value and count down
             \csnumgdef{bpl@itemtotal}{\csuse{bpl@set@itemtotal}+1+\csuse{bpl@items:\theprevrefsection}}\relax%
             \csnumgdef{bpl@set@itemtotal}{\csuse{bpl@set@itemtotal}-\csuse{bpl@secitems:\therefsection}}%
          }{%
             \ifcsundef{bpl@items}{%
                 \PackageWarning{biblatex-publist}{Please rerun LaTeX!\MessageBreak
                                                   Still counting items in ref section \therefsection}%
             }{%
                 \csnumgdef{bpl@itemtotal}{\csuse{bpl@items}+\csuse{bpl@shift@itemtotal}}%
             }%
         }%
      }%
   }%
  \fi
}%

%
% Data annotation
%

\newcommand*\mkbplannot[1]{\textsuperscript{#1}}

% Symbol helpers
\ExplSyntaxOn
  \clist_new:N \l_bpl_annot_symbols
  \cs_new_nopar:Npn \SetAnnotSymbols #1
    {
      \clist_gset:Nn \l_bpl_annot_symbols { #1 }
    }
  \SetAnnotSymbols
     { \textasteriskcentered, \textdaggerdbl, \textsection, \textparagraph,
       \textbardbl, \textdagger, {\textasteriskcentered\textasteriskcentered},
       {\textdaggerdbl\textdaggerdbl}, {\textdagger\textdagger}
     }
  % get symbol by position (int)
  \cs_new_nopar:Npn \bpl@get@annot@symbol #1
    {
      \clist_item:Nn \l_bpl_annot_symbols { #1 }
    }
\ExplSyntaxOff

% get symbol by category name
\NewDocumentCommand\GetAnnotSymbol { s m }{
  \edef\tmpa{}%
  \setcounter{annotsymb}{1}%
  \renewcommand*{\do}[1]{%
    \ifstrequal{#2}{##1}
       {\edef\tmpa{\bpl@get@annot@symbol{\theannotsymb}}}%
       {}%
       \stepcounter{annotsymb}%
    }%
    \expandafter\docsvlist\expandafter{\bpl@annots}%
    \IfBooleanTF{#1}{\tmpa}{\mkbplannot{\tmpa}}%
}

% handle the annotations as passed by annotations option
\AtEndOfPackage{%
\ifx\bpl@annots\empty\else
     % helper function for annotations
     \newcounter{annotsymb}
     \newcommand*\bplannot{%
       \setcounter{annotsymb}{1}%
       \renewcommand*{\do}[1]{%
         \ifitemannotation{##1}
            {\mkbplannot{\bpl@get@annot@symbol{\theannotsymb}}}%
            {}%
            \stepcounter{annotsymb}%
         }%
         \expandafter\docsvlist\expandafter{\bpl@annots}%
     }
     % do annotation in family names
     \renewcommand*{\mkbibnamefamily}[1]{\bplannot #1}
\fi
}

%
% New environment for (foreign) reviews
%
\defbibenvironment{reviews}
    {%
     \begin{enumerate}%
     \small\setlength\itemsep{0pt}%
    }
    {\end{enumerate}}
    {\item}


%
% OpenAccess type
%
\DeclareFieldFormat{openaccess}{%
  \iftoggle{bpl@oainfosimple}{%
     \ifbibstring{openaccess:true}%
       {\bibstring{openaccess:true}}%
       {#1}%
  }{%
    \ifbibstring{openaccess:#1}%
       {\bibstring{openaccess:#1}}%
       {\ifbibstring{openaccess:true}%
          {\bibstring{openaccess:true}}%
          {#1}%
       }%
  }%
}

%
% Peer-review type
%
\DeclareFieldFormat{peerreview}{%
   \ifbibstring{peerreview:#1}%
       {\bibstring{peerreview:#1}}%
       {#1}%
}

%
% Citation info
%
\DeclareFieldFormat{citations}{%
   \bibstring{citations}\addcolon\addspace#1%
}

%
% Impact factor
%
\DeclareFieldFormat{impactfactor}{%
   \bibstring{impactfactor}\addcolon\addspace#1%
}

\DeclareFieldFormat{plextrainfo}{\mkbibbrackets{#1}}

%
% Bibliography filter
%
% Inspired by http://tex.stackexchange.com/a/28555/19291
%
\DeclareBibliographyCategory{filtered}

\DeclareIndexNameFormat{authorfiltered}{%
    \bpl@ifplauthor{\namepartgiven}{\namepartprefix}{\namepartfamily}%
       {\addtocategory{filtered}{\thefield{entrykey}}}%
       {}%
}

\DeclareIndexNameFormat{editorfiltered}{%
    \bpl@ifplauthor{\namepartgiven}{\namepartprefix}{\namepartfamily}%
       {\addtocategory{filtered}{\thefield{entrykey}}}%
       {}%
}

\DeclareIndexNameFormat[inbook,inproceedings,incollection]{editorfiltered}{}%

\DeclareDelimFormat{bpl:unfiltered:finalnamedelim}{%
   \ifnumless{\value{listcount}}{\value{liststop}}%
            {\multinamedelim}%
            {\finalnamedelim}%
}%

\DeclareDelimFormat[author]{bplfinalnamedelim}{%
    \ifnumgreater{\value{nonplauthors}}{2}{\finalandcomma}{}%
    \addspace\bibstring{and}\space}

\DeclareDelimFormat[editor]{bplfinalnamedelim}{%
    \ifnumgreater{\value{nonpleditors}}{2}{\finalandcomma}{}%
    \addspace\bibstring{and}\space}
    
\AtDataInput{%
    \indexnames[authorfiltered][-\value{listtotal}]{author}%
    \indexnames[editorfiltered][-\value{listtotal}]{editor}%
}

\defbibfilter{mine}{category=filtered}

%
% bibchecks
%
% check to exclude submitted work (which is under review)
% from publist
\defbibcheck{nosubmitted}{%
  \edef\tmpps{\bibstring{submitted}}%
  \iffieldequals{pubstate}{\tmpps}{\skipentry}{%
    \iffieldequalstr{pubstate}{submitted}{\skipentry}{}}%
}

% check to exclude work in preparation
% from publist
\defbibcheck{noprepared}{%
  \edef\tmpps{\bibstring{inpreparation}}%
  \iffieldequals{pubstate}{\tmpps}{\skipentry}{%
    \iffieldequalstr{pubstate}{inpreparation}{\skipentry}{}}%
}

% check to exclude all work which is not (pre-)published
\defbibcheck{onlypublished}{%
  \iffieldundef{pubstate}{}{%
     \edef\tmpps{\bibstring{prepublished}}%
     \iffieldequals{pubstate}{\tmpps}{%
       \iffieldequalstr{pubstate}{prepublished}{}{\skipentry}%
     }{\skipentry}%
  }%
}

% check to exclude all work which is not accepted or published
\defbibcheck{onlyaccepted}{%
  \iffieldundef{pubstate}{}{%
     \edef\tmpps{\bibstring{prepublished}}%
     \edef\tmppss{\bibstring{forthcoming}}%
     \iffieldequals{pubstate}{\tmpps}{}{%
       \iffieldequals{pubstate}{\tmppss}{}{%
          \iffieldequalstr{pubstate}{prepublished}{}{%
             \iffieldequalstr{pubstate}{forthcoming}{}{%
               \skipentry}%
          }%
       }%
     }%
  }%
}

% check to exclude all work which is not peer-reviewed
\defbibcheck{onlypr}{%
  \iffieldundef{peerreview}{\skipentry}{%
     \edef\tmppr{\bibstring{no}}%
     \iffieldequals{peerreview}{\tmpps}{\skipentry}{%
       \iffieldequalstr{peerreview}{no}{\skipentry}{}%
     }%
  }%
}

% check to exclude all work which *is* peer-reviewed
\defbibcheck{nopr}{%
  \iffieldundef{peerreview}{}{%
     \edef\tmppr{\bibstring{no}}%
     \iffieldequals{peerreview}{\tmpps}{}{%
       \iffieldequalstr{peerreview}{no}{}{\skipentry}
     }%
  }%
}



%
% Count non-plauthors
%

\newcounter{nonplauthors}
\newcounter{nonpleditors}
\newcounter{plauthor}
\newcounter{pleditor}
\newcounter{plauthors}
\newcounter{pleditors}
\newcounter{realliststop}
\newcounter{nonplauthor}
\newcounter{nonpleditor}

\DeclareIndexNameFormat{nonplauthorcount}{%
    \bpl@ifplauthor{\namepartgiven}{\namepartprefix}{\namepartfamily}%
       {\stepcounter{plauthors}}
       {\stepcounter{nonplauthors}}%
}

\DeclareIndexNameFormat{nonpleditorcount}{%
    \bpl@ifplauthor{\namepartgiven}{\namepartprefix}{\namepartfamily}%
       {\stepcounter{pleditors}}%
       {\stepcounter{nonpleditors}}%
}

\AtEveryBibitem{%
    \setcounter{nonplauthors}{0}%
    \setcounter{nonpleditors}{0}%
    \setcounter{plauthor}{0}%
    \setcounter{pleditor}{0}%
    \setcounter{plauthors}{0}%
    \setcounter{pleditors}{0}%
    \setcounter{nonplauthor}{0}%
    \setcounter{nonpleditor}{0}%
    \setcounter{realliststop}{0}%
    \indexnames[nonplauthorcount][-\value{listtotal}]{author}%
    \indexnames[nonpleditorcount][-\value{listtotal}]{editor}%
}

%
% Remove or highlight plauthorname in author and editor lists
%
\newtoggle{plauthorprecedes}
\newtoggle{hadplauthor}
\newtoggle{isplauthor}
\newtoggle{plnameomitted}
\newtoggle{plnameafteromission}

\newbibmacro*{bpl:omissiondelim}[1][author]
{%
    \ifthenelse{\value{listcount}=1}{\global\togglefalse{plnameafteromission}}{%
        % listcount > 1
        \ifnumless{\value{listcount}}{\value{liststop}}%
            {% listcount < liststop
              \ifnumgreater{\value{listcount}}{\value{realliststop}}{%
                % listcount > realliststop
                \iftoggle{plnameomitted}{% [...] precedes
                  \multinamedelim\iftoggle{isplauthor}{\plnameomission\global\togglefalse{plnameomitted}%
                                                       \global\toggletrue{plnameafteromission}}{}%
                }{% an author name precedes
                  \ifnumless{\value{pl#1}}{\value{pl#1s}}{%
                    % more plauthors left
                    \iftoggle{isplauthor}
                        {\multinamedelim\plnameomission\global\togglefalse{plnameomitted}}
                        {\global\toggletrue{plnameomitted}}%
                  }{% last plauthor
                     \iftoggle{isplauthor}
                        {\multinamedelim}
                        {}%
                  }%
                }%
              }{% listcount >= realliststop
                \multinamedelim\global\togglefalse{plnameomitted}%
              }%
            }{% listcount >= liststop
              \ifnumgreater{\value{listcount}}{\value{realliststop}}{% listcount > realliststop
                \iftoggle{isplauthor}{\iftoggle{plnameomitted}{\multinamedelim\plnameomission}{}%
                                      \finalnamedelim\global\togglefalse{plnameomitted}}{}%
              }{% listcount =< realliststop
                \iftoggle{plnameomitted}{%
                     \ifnumequal{\value{listcount}}{\value{liststop}}%
                            {\finalnamedelim}
                            {\multinamedelim\iftoggle{isplauthor}{\global\togglefalse{plnameomitted}}{}}%                  
                }{%
                 \ifnumgreater{\value{listcount}}{\value{realliststop}}{%
                   \ifnumgreater{\value{pl#1}}{\value{pl#1s}}{%
                     \iftoggle{isplauthor}{\plnameomission\global\toggletrue{plnameomitted}}%
                   }{}%
                 }{\finalnamedelim}%
                }%
              }%
            }%
    }%
}

% Add hook to check whether we are in a related entry.
% This is to prevent author omission in such cases.
\newtoggle{isinrelated}
\apptocmd{\abx@macro@begrelated}{\global\toggletrue{isinrelated}}{}%
         {\PackageWarning{biblatex-publist}{Patching begrelated failed!}}
\apptocmd{\abx@macro@endrelated}{\global\togglefalse{isinrelated}}{}%
         {\PackageWarning{biblatex-publist}{Patching endrelated failed!}}

\providecommand*\bplopenoa{\bibopenparen}
\providecommand*\bplcloseoa{\bibcloseparen}

% Omission/highlighting routine
% (common code for authors and editors)
% \usebibmacro{bpl:handlenames}[author|editor]
\newbibmacro{bpl:handlenames}[1][author]{%
    \bpl@ifplauthor{\namepartgiven}{\namepartprefix}{\namepartfamily}%
       {\iftoggle{isinrelated}{\togglefalse{isplauthor}}%
                              {\global\toggletrue{isplauthor}\stepcounter{pl#1}}}%
       {\global\togglefalse{isplauthor}}%
    %
    % Calculate real list stop
    \ifnumless{\value{liststop}}{\value{maxnames}}
         {\setcounter{realliststop}{\theliststop}}
         {\setcounter{realliststop}{\value{minnames}}}%
    %
    % First case: plauthorhandling=highlight
    \if@hlauthor%
        % Highlight plauthor(s)
        \usebibmacro{bpl:omissiondelim}[#1]%
        \iftoggle{isplauthor}{%
            \plauthorhl{%
                \if@givenfirst% given name first
                    \ifgiveninits
                        {\ifdefvoid{\namepartgiveni}{}{\mkbibnamegiven{\namepartgiveni}\addspace}}%
                        {\ifdefvoid{\namepartgiven}{}{\mkbibnamegiven{\namepartgiven}\addspace}}%
                    \ifdefvoid{\namepartprefix}%
                        {}%
                        {\mkbibnameprefix{\namepartprefix}\addspace}%
                    \mkbibnamefamily{\namepartfamily}%
                \else% family name first
                    \ifdefvoid{\namepartprefix}%
                        {}%
                        {\mkbibnameprefix{\namepartprefix}\addspace}%
                    \mkbibnamefamily{\namepartfamily}%
                    \ifgiveninits
                        {\ifdefvoid{\namepartgiveni}{}{\revsdnamepunct\addspace\mkbibnamegiven{\namepartgiveni}\addspace}}%
                        {\ifdefvoid{\namepartgiven}{}{\revsdnamepunct\addspace\mkbibnamegiven{\namepartgiven}\isdot\addspace}}%
                \fi
            }%
            \ifnumequal{\value{listcount}}{\value{liststop}}{}{\usebibmacro{bpl:name:andothers}}%
        }{%
           \ifnumgreater{\value{listcount}}{\value{realliststop}}{}{%
             \if@givenfirst% given name first
                 \ifgiveninits
                     {\ifdefvoid{\namepartgiveni}{}{\mkbibnamegiven{\namepartgiveni}\addspace}}%
                     {\ifdefvoid{\namepartgiven}{}{\mkbibnamegiven{\namepartgiven}\addspace}}%
                 \ifdefvoid{\namepartprefix}%
                     {}%
                     {\mkbibnameprefix{\namepartprefix}\addspace}%
                 \mkbibnamefamily{\namepartfamily}%
             \else% family name first
                 \ifdefvoid{\namepartprefix}%
                       {}%
                       {\mkbibnameprefix{\namepartprefix}\addspace}%
                 \mkbibnamefamily{\namepartfamily}%
                 \ifgiveninits
                    {\ifdefvoid{\namepartgiveni}{}{\revsdnamepunct\addspace\mkbibnamegiven{\namepartgiveni}\addspace}}%
                    {\ifdefvoid{\namepartgiven}{}{\revsdnamepunct\addspace\mkbibnamegiven{\namepartgiven}\isdot\addspace}}%
             \fi
           }%
           \usebibmacro{bpl:name:andothers}%
        }%
    %
    % Second case: plauthorhandling=omit
    \else% \if@hlauthor false
        \ifthenelse{\value{listcount}=1}%
            {\ifthenelse{\value{nonpl#1s}>0\AND{\value{pl#1s}}>0}%
                 {\iftoggle{isinrelated}{}{\bplopenoa\bibstring{with}\addspace}}%
                 {}%
             \iftoggle{isplauthor}%
                 {\global\toggletrue{plauthorprecedes}}%
                 {\global\togglefalse{plauthorprecedes}}%
            }%
            {}%
        % Exclude omitted author
        \iftoggle{isplauthor}%
            {% <- TRUE condition
              \global\toggletrue{hadplauthor}%
              \ifx\bpl@annots\empty\else
                \gdef\bpl@extra@annots{}%
                \renewcommand*{\do}[1]{%
                   \ifitemannotation{##1}
                     {%
                       \iftoggle{bpl@have@extrainfo}%
                            {\gappto\bpl@extra@annots{\plextrainfosep\ifbibstring{annot:##1}%
                                                                       {\bibstring{annot:##1}}%
                                                                       {##1}}%
                            }%
                            {\gappto\bpl@extra@annots{\ifbibstring{annot:##1}%
                                                             {\bibstring{annot:##1}}%
                                                             {##1}}%
                            }%
                        \toggletrue{bpl@have@extrainfo}%
                     }%
                     {}%
                }%
                \expandafter\docsvlist\expandafter{\bpl@annots}%
              \fi%
            }% <- end TRUE condition
            {% <- FALSE condition
              \stepcounter{nonpl#1}%
              \ifthenelse{\value{listcount}=1}%
                   {\global\togglefalse{hadplauthor}}%
                   {%
                     \iftoggle{plauthorprecedes}%
                         {}%
                         {%
                           \ifnumgreater{\value{listcount}}{\value{realliststop}}{}{%
                              \ifnumless{\value{nonpl#1}}{\value{nonpl#1s}}%
                                 {\multinamedelim}%
                                 {\iftoggle{isinrelated}{\printdelim{bpl:unfiltered:finalnamedelim}}%
                                                        {\printdelim[#1]{bplfinalnamedelim}}}%
                            }%
                         }%
                   }%
             \ifnumgreater{\value{listcount}}{\value{realliststop}}{}{%
              \ifgiveninits
                  {\ifdefvoid{\namepartgiveni}{}{\mkbibnamegiven{\namepartgiveni}\addspace}}%
                  {\ifdefvoid{\namepartgiven}{}{\mkbibnamegiven{\namepartgiven}\addspace}}%
              \ifdefvoid{\namepartprefix}{}{\mkbibnameprefix{\namepartprefix}\addspace}%
              \global\togglefalse{plauthorprecedes}%
              \mkbibnamefamily{\namepartfamily}%
             }%
            }% <- end FALSE condition
        %
        \usebibmacro{bpl:name:andothers}%
        \ifthenelse{\value{nonpl#1s}>0\AND{\value{pl#1s}}>0\AND\value{listcount}=\value{liststop}}%
            {\unspace\iftoggle{isinrelated}{}{\bplcloseoa}}%
            {}%
    \fi% end of \if@hlauthor else condition
}

\DeclareNameFormat{author}{%
    \usebibmacro{bpl:handlenames}%
}

\DeclareNameFormat{editor}{%
    \usebibmacro{bpl:handlenames}[editor]%
}

\DeclareNameFormat{bookauthor}{%
    \if@givenfirst% given name first
        \ifgiveninits
            {\ifdefvoid{\namepartgiveni}{}{\mkbibnamegiven{\namepartgiveni}\addspace}}%
            {\ifdefvoid{\namepartgiven}{}{\mkbibnamegiven{\namepartgiven}\addspace}}%
         \ifdefvoid{\namepartprefix}{}{\mkbibnameprefix{\namepartprefix}\addspace}%
         \mkbibnamefamily{\namepartfamily}%
    \else% family name first
         \ifdefvoid{\namepartprefix}{}{\mkbibnameprefix{\namepartprefix}\addspace}%
         \mkbibnamefamily{\namepartfamily}%
         \ifgiveninits
             {\ifdefvoid{\namepartgiveni}{}{\revsdnamepunct\addspace\mkbibnamegiven{\namepartgiveni}\addspace}}%
             {\ifdefvoid{\namepartgiven}{}{\revsdnamepunct\addspace\mkbibnamegiven{\namepartgiven}\isdot\addspace}}%
    \fi
    \ifthenelse{\value{listcount}<\value{liststop}}
        {\ifnumless{\value{listcount}}{\value{liststop}-1}%
            {\multinamedelim}%
            {\finalnamedelim}}%
        {}%
    \usebibmacro{name:andothers}%
}


%
% Macros
%

\renewbibmacro*{author}{%
    \iftoggle{isinrelated}{%
       \usebibmacro{bpl:plain:author}%
    }{%
       \usebibmacro{bpl:author}%
    }%
}


\renewbibmacro*{editor}{%
    \iftoggle{isinrelated}{%
       \usebibmacro{bpl:plain:editor}%
    }{%
       \usebibmacro{bpl:editor}%
    }%
}


\newbibmacro*{bpl:author}{%
    \if@hlauthor
        \ifnameundef{author}
            {}
            {%
             \usebibmacro{bpl:marginyear}%
             \printnames[][-\value{listtotal}]{author}%
             \setunit{\addspace}%
             \iffieldundef{nameaddon}
                 {}
                 {%
                  \mkbibbrackets{%
                      \bibstring{alias}%
                      \addspace\printfield{nameaddon}%
                  }%
                 }%
            }%
        \if@fixyear%
           \adddot\addspace%
           \usebibmacro{bpl:year+labelyear}%
        \fi%
    \else% \if@hlauthor false
        \ifnameundef{author}
            {}
            {%
             \usebibmacro{bpl:marginyear}%
             \if@fixyear%
               \usebibmacro{bpl:year+labelyear}%
               \addspace%
             \fi%
             \ifthenelse{\value{nonplauthors}>0\AND{\value{plauthors}}>0}
                {\printnames[][-\value{listtotal}]{author}%
                 \setunit{\addspace}}%
                {}%
             \iffieldundef{nameaddon}
                 {}
                 {%
                  \mkbibbrackets{%
                      \bibstring{alias}%
                      \addspace\printfield{nameaddon}%
                  }%
                 }%
            }%
    \fi% end of \if@hlauthor else condition
}

\newbibmacro*{bpl:editor}{%
    \if@hlauthor
        \ifnameundef{editor}
            {}
            {%
             \usebibmacro{bpl:marginyear}%
             \printnames[][-\value{listtotal}]{editor}%
             \setunit{\printdelim{editortypedelim}}%
             \usebibmacro{editorstrg}%
            }%
            \if@fixyear%
               \adddot\addspace%
               \usebibmacro{bpl:year+labelyear}%
            \fi%
            \clearname{editor}%
    \else% \if@hlauthor false
        \ifnameundef{editor}
            {}
            {%
             \usebibmacro{bpl:marginyear}%
             \if@fixyear
               \usebibmacro{bpl:year+labelyear}%
               \addspace%
             \fi%
             \printnames[][-\value{listtotal}]{editor}%
             \setunit{\printdelim{editortypedelim}}%
             \usebibmacro{editorstrg}%
             \clearname{editor}%
            }%
    \fi% end of \if@hlauthor else condition
}

\renewbibmacro*{editor+others}{%
    \if@hlauthor
        \ifboolexpr{
            test \ifuseeditor
            and not test {\ifnameundef{editor}}}
            {%
             \usebibmacro{bpl:marginyear}%
             \printnames[][-\value{listtotal}]{editor}%
             \setunit{\printdelim{editortypedelim}}%
             \usebibmacro{editor+othersstrg}%
             \adddot\addspace%
             \usebibmacro{bpl:year+labelyear}%
             \clearname{editor}%
            }
            {}%
    \else% \if@hlauthor false
        \ifboolexpr{
            test \ifuseeditor
            and not test {\ifnameundef{editor}}}
            {%
             \usebibmacro{bpl:marginyear}%
             \usebibmacro{bpl:year+labelyear}%
             \addspace%
             \printnames[][-\value{listtotal}]{editor}%
             \setunit{\printdelim{editortypedelim}}%
             \usebibmacro{editor+othersstrg}%
             \clearname{editor}%
            }
            {}%
    \fi% end of \if@hlauthor else condition
}

\newbibmacro*{bpl:name:andothers}{%
    \ifthenelse{\value{listcount}=\value{liststop}\AND\value{liststop}>\value{realliststop}}
        {%
         \ifboolexpr{
            test {\ifnumgreater{\value{realliststop}}{1}}
            or
            test {\iftoggle{plnameafteromission}}
         }{\finalandcomma}{}%
         \andothersdelim\biblcstring{andothers}%
        }
        {}%
}


\ifbpl@standardbasestyle
    % Work around issue in authoryear.bbx:
    % test for empty year before printing parens
    \renewbibmacro*{issue+date}{%
        \ifboolexpr{test {\iffieldundef{year}}
                    and test {\iffieldundef{issue}}}
            {}
            {%
             \printtext[parens]{%
             \printfield{issue}%
             \setunit*{\addspace}%
             \if@fixyear\else%
                % turn of mergedate, as this doesn't play well with us.
                \renewbibmacro*{bbx:ifmergeddate}{\@secondoftwo}%
             \fi%
             \usebibmacro{date}}%
            }%
        \newunit%
    }
\fi

\AtEndOfPackage{%
  \if@pubstateextra
     % Include pubstate in extradate
     \DeclareExtradate{%
       \scope{
         \field{pubstate}
         \field{labelyear}
         \field{year}
       }
    }
  \fi
}

\newbibmacro*{bpl:date:makedate}{%
    \printtext{%
        \iffieldundef{year}{%
            \iffieldundef{pubstate}%
                {}
                {%
                 \printfield{pubstate}%
                 \if@pubstateextra
                   \printfield{extradate}%
                 \fi%
                }%
        }{%
            \iffieldundef{month}%
                {\printdateextra}%
                {\printdate}%
        }%
    }%
}

\newbibmacro*{bpl:date:labeldate+extradate}{%
   \if@hlyear
      \plyearhl{\usebibmacro{bpl:date:makedate}}%
   \else
      \usebibmacro{bpl:date:makedate}%
   \fi%
}

\newbibmacro*{bpl:marginyear}{%
    \if@marginyear%
        \iffieldundef{year}{%
            \iffieldundef{pubstate}%
                {}%
                {\iffieldequals{pubstate}{\bbx@lasthash}%
                     {}%
                     {%
                      \printtext{\marginpar{\small\plmarginyear{\bibsentence\printfield{pubstate}}}}%
                      \if@fixyear\else\savefield{pubstate}{\bbx@lasthash}\fi%
                     }%
                }%
        }{%
            \iffieldequals{year}{\bbx@lasthash}%
                {}%
                {%
                 \printtext{\marginpar{\small\plmarginyear{\bibsentence\printfield{year}}}}%
                 \if@fixyear\else\savefield{year}{\bbx@lasthash}\fi%
                }%
        }%
    \fi
}

\newbibmacro*{bpl:year+labelyear}{%
    \iffieldundef{year}{%
        \iffieldundef{pubstate}%
            {\let\bbx@lasthash\undefined}%
            {%
             \usebibmacro{bpl:date:labeldate+extradate}%
             \savefield{pubstate}{\bbx@lasthash}%
             \clearfield{pubstate}%
            }%
    }{%
         \usebibmacro{bpl:date:labeldate+extradate}%
         \savefield{year}{\bbx@lasthash}%
         \clearfield{year}%
    }%
}

\newbibmacro*{bpl:plain:author/label}{%
    \ifnameundef{author}
        {\usebibmacro{label}}
        {\usebibmacro{bpl:plain:author}}
}

\newbibmacro*{bpl:plain:author}{%
    \ifnameundef{author}
        {\let\bbx@lasthash\undefined}
        {%
         \ifthenelse{\iffieldequals{namehash}{\bbx@lasthash}\AND\NOT\iffirstonpage}
             {\bibnamedash}
             {%
              \savefield{namehash}{\bbx@lasthash}%
              \printnames{author}%
              \setunit{\addspace}%
             }%
        }%
    \iffieldundef{nameaddon}
        {}
        {%
         \mkbibbrackets{\bibstring[\unspace]{alias}\addspace\printfield{nameaddon}}%
         \addspace%
        }%
    \usebibmacro{bpl:plain:year+labelyear}%
}

\newbibmacro*{bpl:plain:editor}{%
   \ifnameundef{editor}
       {}
       {%
        \printnames{editor}%
        \setunit{\printdelim{editortypedelim}}%
        \usebibmacro{editorstrg}%
       }%
       \adddot\addspace%
       \usebibmacro{bpl:plain:year+labelyear}%
       \clearname{editor}%
}

\newbibmacro*{bpl:plain:year+labelyear}{%
    \iffieldundef{year}
        {}
        {%
         \printtext[parens]{%
             \printfield{labelyear}%
             \printfield{extradate}%
         }%
        }%
}

%
% Extra information
%

\def\bpl@extra@annots{}

\newtoggle{bpl@have@extrainfo}

\renewbibmacro*{addendum+pubstate}{%
  \togglefalse{bpl@have@extrainfo}%
  \printfield{addendum}%
  \newunit\newblock
  \printfield{pubstate}%
  \ifboolexpr{ (
                 not test {\iffieldundef{peerreview}}
                 and test {\iftoggle{bpl@prinfo}}
               )
               or
               (
                 not test {\iffieldundef{openaccess}}
                 and test {\iftoggle{bpl@oainfo}}
               )
               or
               (
                 not test {\iffieldundef{impactfactor}}
                 and test {\iftoggle{bpl@jifinfo}}          
               )
               or
               (
                 not test {\iffieldundef{citations}}
                 and test {\iftoggle{bpl@citinfo}}          
               )
               or
               (
                 not test {\ifcsvoid{bpl@extra@annots}}
               )
            }{%
                \newunit\newblock%
                \printtext[plextrainfo]{%
                   \ifx\bpl@extra@annots\empty\else
                      \bpl@extra@annots%
                      \toggletrue{bpl@have@extrainfo}%
                   \fi
                   \ifboolexpr{ not test {\iffieldundef{peerreview}}
                      and test {\iftoggle{bpl@prinfo}}
                   }{%
                      \iftoggle{bpl@have@extrainfo}{\plextrainfosep}{}%
                      \printfield{peerreview}%
                      \toggletrue{bpl@have@extrainfo}%
                   }{}%
                   \ifboolexpr{ not test {\iffieldundef{citations}}
                      and test {\iftoggle{bpl@citinfo}}
                   }{%
                      \iftoggle{bpl@have@extrainfo}{\plextrainfosep}{}%
                      \printfield{citations}%
                      \toggletrue{bpl@have@extrainfo}%
                   }{}%
                   \ifboolexpr{ not test {\iffieldundef{openaccess}}
                      and test {\iftoggle{bpl@oainfo}}
                   }{%
                      \iftoggle{bpl@have@extrainfo}{\plextrainfosep}{}%
                      \printfield{openaccess}%
                      \toggletrue{bpl@have@extrainfo}%
                   }{}%
                   \ifboolexpr{ not test {\iffieldundef{impactfactor}}
                      and test {\iftoggle{bpl@jifinfo}}
                   }{%
                      \iftoggle{bpl@have@extrainfo}{\plextrainfosep}{}%
                      \printfield{impactfactor}%
                   }{}%
               }%
            }{}%
}

%
% l7n
%

\DeclareLanguageMappingSuffix{-publist}

% publist-specific bibstrings
\NewBibliographyString{citations}
\NewBibliographyString{with}
\NewBibliographyString{parttranslationof}
\NewBibliographyString{impactfactor}
\NewBibliographyString{openaccess:true}
\NewBibliographyString{openaccess:gold}
\NewBibliographyString{openaccess:green}
\NewBibliographyString{peerreview:sb}
\NewBibliographyString{peerreview:db}
\NewBibliographyString{peerreview:op}
\NewBibliographyString{peerreview:co}
\NewBibliographyString{peerreview:cc}
\NewBibliographyString{peerreview:tp}
\NewBibliographyString{peerreview:pp}
\NewBibliographyString{peerreview:no}
\NewBibliographyString{annot:main}
\NewBibliographyString{annot:corresponding}


%
% New driver for reviews
%

\DeclareBibliographyDriver{review}{%
    \usebibmacro{bpl:plain:author/label}%
    \setunit*{\addcolon\space}%
    \usebibmacro{title}%
    \newunit\newblock
    \usebibmacro{in:}%
    \usebibmacro{journal+issuetitle}%
    \newunit\newblock
    \printfield{note}%
    \setunit{\addcomma\space}%
    \printfield{pages}
    \newunit\newblock
    \printfield{issn}%
    \newunit\newblock
    \printfield{doi}%
    \setunit{\addspace}
    \usebibmacro{addendum+pubstate}%
    \newunit\newblock
    \usebibmacro{url+urldate}%
    \newunit\newblock
    \usebibmacro{pageref}%
    \newunit\newblock
    \usebibmacro{related}%
    \usebibmacro{finentry}%
}

%
% Sorting schemes
%

% Consider the whole date (year-month-day)
% Sorting date (descending), name, title
\DeclareSortingTemplate{ddnt}{
    \sort{
        \field{presort}
    }
    \sort[final]{
        \field{sortkey}
    }
    \sort[direction=descending]{
        \field[strside=left,strwidth=4]{sortyear}
        \field[strside=left,strwidth=4]{year}
        \literal{9999}
    }
    \sort[direction=descending]{
        \field[padside=left,padwidth=2,padchar=0]{month}
        \literal{00}
    }
    \sort[direction=descending]{
        \field[padside=left,padwidth=2,padchar=0]{day}
        \literal{00}
    }
    \sort{
        \field{sortname}
        \field{author}
        \field{editor}
        \field{translator}
        \field{sorttitle}
        \field{title}
    }
    \sort{
        \field{sorttitle}
        \field{title}
    }
}

% Sorting year (descending), month, day, name, title
\DeclareSortingTemplate{ydmdnt}{
    \sort{
        \field{presort}
    }
    \sort[final]{
        \field{sortkey}
    }
    \sort[direction=descending]{
        \field[strside=left,strwidth=4]{sortyear}
        \field[strside=left,strwidth=4]{year}
        \literal{9999}
    }
    \sort{
        \field[padside=left,padwidth=2,padchar=0]{month}
        \literal{00}
    }
    \sort{
        \field[padside=left,padwidth=2,padchar=0]{day}
        \literal{00}
    }
    \sort{
        \field{sortname}
        \field{author}
        \field{editor}
        \field{translator}
        \field{sorttitle}
        \field{title}
    }
    \sort{
        \field{sorttitle}
        \field{title}
    }
}

% Sorting date (ascending), name, title
\DeclareSortingTemplate{dnt}{
    \sort{
        \field{presort}
    }
    \sort[final]{
        \field{sortkey}
    }
    \sort{
        \field[strside=left,strwidth=4]{sortyear}
        \field[strside=left,strwidth=4]{year}
        \literal{9999}
    }
    \sort{
        \field[padside=left,padwidth=2,padchar=0]{month}
        \literal{00}
    }
    \sort{
        \field[padside=left,padwidth=2,padchar=0]{day}
        \literal{00}
    }
    \sort{
        \field{sortname}
        \field{author}
        \field{editor}
        \field{translator}
        \field{sorttitle}
        \field{title}
    }
    \sort{
        \field{sorttitle}
        \field{title}
    }
}

% Sorting schemes without name

% Sorting year (descending), title
\DeclareSortingTemplate{ydt}{
    \sort{
        \field{presort}
    }
    \sort[final]{
        \field{sortkey}
    }
    \sort[direction=descending]{
        \field[strside=left,strwidth=4]{sortyear}
        \field[strside=left,strwidth=4]{year}
        \literal{9999}
    }
    \sort{
        \field{sorttitle}
        \field{title}
    }
}

% Consider the whole date (year-month-day)
% Sorting date (descending), title
\DeclareSortingTemplate{ddt}{
    \sort{
        \field{presort}
    }
    \sort[final]{
        \field{sortkey}
    }
    \sort[direction=descending]{
        \field[strside=left,strwidth=4]{sortyear}
        \field[strside=left,strwidth=4]{year}
        \literal{9999}
    }
    \sort[direction=descending]{
        \field[padside=left,padwidth=2,padchar=0]{month}
        \literal{00}
    }
    \sort[direction=descending]{
        \field[padside=left,padwidth=2,padchar=0]{day}
        \literal{00}
    }
    \sort{
        \field{sorttitle}
        \field{title}
    }
}

% Sorting year (descending), month, day, title
\DeclareSortingTemplate{ydmdt}{
    \sort{
        \field{presort}
    }
    \sort[final]{
        \field{sortkey}
    }
    \sort[direction=descending]{
        \field[strside=left,strwidth=4]{sortyear}
        \field[strside=left,strwidth=4]{year}
        \literal{9999}
    }
    \sort{
        \field[padside=left,padwidth=2,padchar=0]{month}
        \literal{00}
    }
    \sort{
        \field[padside=left,padwidth=2,padchar=0]{day}
        \literal{00}
    }
    \sort{
        \field{sorttitle}
        \field{title}
    }
}

% Sorting date (ascending), title
\DeclareSortingTemplate{dt}{
    \sort{
        \field{presort}
    }
    \sort[final]{
        \field{sortkey}
    }
    \sort{
        \field[strside=left,strwidth=4]{sortyear}
        \field[strside=left,strwidth=4]{year}
        \literal{9999}
    }
    \sort{
        \field[padside=left,padwidth=2,padchar=0]{month}
        \literal{00}
    }
    \sort{
        \field[padside=left,padwidth=2,padchar=0]{day}
        \literal{00}
    }
    \sort{
        \field{sorttitle}
        \field{title}
    }
}


% Define bibmacro that applies a hypertext reference
% Inspired by https://tex.stackexchange.com/a/48506/19291
\newbibmacro*{bpl:linked}[1]{%
  \ifboolexpr{ test {\ifhyperref} and not test {\ifentrytype{online}} }
    {\iffieldundef{doi}
       {\iffieldundef{url}
          {\iffieldundef{isbn}
             {\iffieldundef{issn}
                {#1}
                {\iftoggle{bpl@linktitleissn}{\href{\plissnlink{\thefield{issn}}}{#1}}{#1}}}
             {\iftoggle{bpl@linktitleisbn}{\href{\plisbnlink{\thefield{isbn}}}{#1}}{#1}}}
          {\iftoggle{bpl@linktitleurl}{\href{\thefield{url}}{#1}}{#1}}}
       {\iftoggle{bpl@linktitledoi}{\href{https://doi.org/\thefield{doi}}{#1}}{#1}}}
    {#1}%
}

% URL for ISBN/ISSN queries
\newcommand*\plisbnlink[1]{https://www.worldcat.org/search?qt=worldcat_org_all&q=#1}
\newcommand*\plissnlink[1]{https://www.worldcat.org/search?qt=worldcat_org_all&q=#1}


%
% Mappings (biber)
%

% Add a dummy constant shortauthor in order to
% ignore author constellation on extralabel assignment.
% Original entries are stored in namea.
\if@hlauthor
\else
    \DeclareStyleSourcemap{
        \maps[datatype=bibtex]{
          \map{
             \step[fieldsource=shortauthor]
             \step[fieldset=namea, origfieldval]
            }
            \map[overwrite]{
                \step[fieldset=shortauthor, fieldvalue={1111}]
            }
        }
    }
    % For proper labelname (e.g., \textcite), write back original
    % shortauthor, author or editor after the extradate has been
    % constructed.
    \AtDataInput{%
       \csgappto\blx@bbl@data{%
           \let\c@shortauthor\c@namea
           \let\abx@name@shortauthor\abx@name@namea
           \ifdefstring\abx@field@labelnamesource{shortauthor}
              {\ifundef\abx@name@shortauthor
              {\ifundef\abx@name@author
              {\def\abx@field@labelnamesource{editor}}
              {\def\abx@field@labelnamesource{author}}%
                  }%
          {}%
          }%
              {}%
        }%
     }%
\fi

% Correctly sort pubstates.
\DeclareStyleSourcemap{
    \maps[datatype=bibtex]{
        \map{
            \step[fieldsource=year, final]
            \step[fieldset=sortyear, origfieldval]
        }
        \map{
           \step[fieldsource=pubstate, match=\regexp{prepublished}, final]
           \step[fieldset=sortyear, fieldvalue={2222}]
        }
        \map{
           \step[fieldsource=pubstate, match=\regexp{forthcoming}, final]
           \step[fieldset=sortyear, fieldvalue={3333}]
        }
        \map{
           \step[fieldsource=pubstate, match=\regexp{inpress}, final]
           \step[fieldset=sortyear, fieldvalue={4444}]
        }
        \map{
           \step[fieldsource=pubstate, match=\regexp{submitted}, final]
           \step[fieldset=sortyear, fieldvalue={5555}]
        }
        \map{
           \step[fieldsource=pubstate, match=\regexp{inpreparation}, final]
           \step[fieldset=sortyear, fieldvalue={6666}]
        }
    }
}

% Link titles if so requested
\AtBeginDocument{%
  \iftoggle{bpl@linktitle}{%
    \DeclareFieldInputHandler{title}{\def\NewValue{\usebibmacro{bpl:linked}{#1}}}
    \DeclareFieldInputHandler{subtitle}{\def\NewValue{\usebibmacro{bpl:linked}{#1}}}
  }{}
}


%
% Deprecated stuff
%

% DEPRECATED as of v.1.4
% Issue a warning if used.
\newtoggle{bpl:omitname}
\def\omitname{%
    \toggletrue{bpl:omitname}%
    \@ifnextchar[%
        {\plauthorname@i}
        {\plauthorname@i[]}%
}

\AtEndPreamble{%
    \iftoggle{bpl:omitname}{%
        \PackageWarning{biblatex-publist}%
            {The \protect\omitname\space macro is deprecated!\MessageBreak
             Please use \protect\plauthorname\space instead.}{}%
    }%
}

% Renamed in v. 2.0
\let\shiftbplnum\shiftplnum

\endinput