%D \module
%D   [       file=publ-imp-apa,
%D        version=2013.12.12,
%D          title=APA bibliography style,
%D       subtitle=Publications,
%D         author=Alan Braslau and Hans Hagen,
%D           date=\currentdate,
%D      copyright={PRAGMA ADE \& \CONTEXT\ Development Team}]
%C
%C This module is part of the \CONTEXT\ macro||package and is therefore copyrighted
%D by \PRAGMA. See mreadme.pdf for details.

\startbtxrenderingdefinitions[apa]

\ifdefined\c!translate \else \def\c!translate{translate} \fi

%D Reference:
%D \startTEX
%D @Book{APA2010,
%D     title    ={Publication Manual of the American Psychological Association},
%D     year     ={2010},
%D     edition  ={Sixth},
%D     address  ={Washington, DC},
%D     publisher={American Psychological Association},
%D     Xpages   ={291},
%D     url      ={http://www.apa.org/books/},
%D }
%D \stopTEX

% set ALL specific APA compliant values

\definebtx
  [apa]
  [\c!default=default,
   \c!specification=apa,
   \c!otherstext={\btxspace\btxlabeltext{apa:others}},
   %c!journalconversion=\v!normal,
   \c!monthconversion=\v!month]

% First, define list and rendering parameters

% The APA style sorts the unnumbered rendered list by authoryear

\definebtxrendering
  [apa]
  [\c!specification=apa,
   \c!sorttype=authoryear,
   \c!numbering=\v!no]

\setupbtxlist
  [apa]
  [\c!alternative=\v!paragraph,
  %\c!width=\v!fit,
  %\c!distance=.5\emwidth,
   \c!margin=3.5\emwidth]

\definebtx
  [apa:\s!list]
  [apa]
  [\c!otherstext={\btxcomma\btxnobreakspace\textellipsis\space},
   \c!etallimit=7,
   \c!etaldisplay=6,
   \c!etaloption=last,
   \c!authorconversion=invertedshort,
   \c!separator:names:2={\btxcomma}, % aka namesep - in this namespace
   \c!separator:names:3={\btxcomma\btxnobreakspace\textampersand\space}, % comma separated list
   \c!separator:names:4={\btxnobreakspace\textampersand\space}] % last of two, no comma!

% First, we define a namespace for a few special fields

\definebtx
  [apa:\s!list:author]
  [apa:\s!list]

\definebtx
  [apa:\s!list:editor]
  [apa:\s!list:author]

\definebtx
  [apa:\s!list:suffix]
  [apa:\s!list]

\definebtx
  [apa:\s!list:url]
  [apa:\s!list]

\definebtx
  [apa:\s!list:doi]
  [apa:\s!list]

\definebtx
  [apa:\s!list:\s!page]
  [apa:\s!list]
  [\c!separator:2={\btxcomma},
   \c!separator:3={\btxcomma\btxlabeltext{apa:and}\space},
   \c!separator:4={\btxspace\btxlabeltext{apa:and}\space},
   \c!left={\btxleftparenthesis},
   \c!right={\btxrightparenthesis},
   \c!command={\wordright}]

\definebtx
  [apa:\s!list:numbering]
  [apa:\s!list]
  [\c!right={\btxspace}]

\definebtx
  [apa:\s!list:numbering:default]
  [apa:\s!list:numbering]

\definebtx
  [apa:\s!list:numbering:num]
  [apa:\s!list:numbering]
  [\c!stopper={.}]

\definebtx
  [apa:\s!list:numbering:short]
  [apa:\s!list:numbering]

\definebtx
  [apa:\s!list:numbering:tag]
  [apa:\s!list:numbering]

\definebtx
  [apa:\s!list:numbering:index]
  [apa:\s!list:numbering]

% Next, we define a namespace for each category

%D In order to be able to get journals expanded (or normalized or abbreviated) you need
%D to load a list:
%D
%D \starttyping
%D \btxloadjournallist[journals.txt] % the jabref list
%D \stoptyping

\definebtx
  [apa:\s!list:journal]
  [apa:\s!list]
  [\c!style=\v!italic]
  %command=\btxexpandedjournal] % btxabbreviatedjournal

\definebtx
  [apa:\s!list:volume]
  [apa:\s!list]
  [\c!style=\v!italic]

\definebtx
  [apa:\s!list:title]
  [apa:\s!list]
  [\c!style=\v!italic,
   \c!command=\Word,
   \c!translate=\v!yes]

\definebtx
  [apa:\s!list:title:article]
  [apa:\s!list:title]
  [\c!style=] % journal is set in italics

\definebtx
  [apa:\s!list:title:magazine]
  [apa:\s!list:title]

\definebtx
  [apa:\s!list:title:newspaper]
  [apa:\s!list:title]

\definebtx
  [apa:\s!list:title:periodical]
  [apa:\s!list:title]

\definebtx
  [apa:\s!list:title:standard]
  [apa:\s!list:title]

\definebtx
  [apa:\s!list:title:book]
  [apa:\s!list:title]

\definebtx
  [apa:\s!list:title:inbook]
  [apa:\s!list:title]

\definebtx
  [apa:\s!list:title:incollection]
  [apa:\s!list:title]
  [\c!style=] % booktitle is set in italics

\definebtx
  [apa:\s!list:title:proceedings]
  [apa:\s!list:title]

\definebtx
  [apa:\s!list:title:inproceedings]
  [apa:\s!list:title]
  [\c!style=] % booktitle is set in italics

\definebtx
  [apa:\s!list:title:conference]
  [apa:\s!list:title]
  [\c!style=] % booktitle is set in italics

\definebtx
  [apa:\s!list:title:thesis]
  [apa:\s!list:title]

\definebtx
  [apa:\s!list:title:phdthesis]
  [apa:\s!list:title]

\definebtx
  [apa:\s!list:title:mastersthesis]
  [apa:\s!list:title]

\definebtx
  [apa:\s!list:title:booklet]
  [apa:\s!list:title]

\definebtx
  [apa:\s!list:title:manual]
  [apa:\s!list:title]

\definebtx
  [apa:\s!list:title:techreport]
  [apa:\s!list:title]

\definebtx
  [apa:\s!list:title:unpublished]
  [apa:\s!list:title]

\definebtx
  [apa:\s!list:title:patent]
  [apa:\s!list:title]

\definebtx
  [apa:\s!list:title:electronic]
  [apa:\s!list:title]

\definebtx
  [apa:\s!list:title:music]
  [apa:\s!list:title]

\definebtx
  [apa:\s!list:title:film]
  [apa:\s!list:title]

\definebtx
  [apa:\s!list:title:other]
  [apa:\s!list:title]

\definebtx
  [apa:\s!list:title:misc]
  [apa:\s!list:title]

\definebtx
  [apa:\s!list:title:literal]
  [apa:\s!list:title]

\definebtx
  [apa:\s!list:type]
  [\c!command=\Word]

% Then define and set cite parameters.

\definebtx
  [apa:\s!cite]
  [apa]
  [\c!alternative=authoryear,
   \c!otherstext={\btxcomma\btxlabeltext{apa:others}},
   \c!etallimit=5,
   \c!etaldisplay=1, % TODO: when 2-4, show all first time, etaldisplay subsequently...
   \c!authorconversion=\v!name,
   \c!sorttype=normal,
   \c!compress=\v!yes, % note that cite sorts only work with compress=yes.
   \c!separator:names:2={\btxcomma},
   \c!separator:names:3={\btxcomma\btxlabeltext{apa:and}\space}, % not \textampersand
   \c!separator:names:4={\btxspace\btxlabeltext{apa:and}\space}] % not \textampersand

\definebtx
  [apa:\s!cite:name]
  [apa:\s!cite]
  [\c!authorconversion=\v!name]

\definebtx
  [apa:\s!cite:inverted]
  [apa:\s!cite]
  [\c!authorconversion=\v!invertedshort]

\definebtx
  [apa:\s!cite:invertedshort]
  [apa:\s!cite]
  [\c!authorconversion=\v!invertedshort]

\definebtx
  [apa:\s!cite:normalshort]
  [apa:\s!cite]
  [\c!authorconversion=\v!normalshort]

\definebtx
  [apa:\s!cite:normal]
  [apa:\s!cite]
  [\c!authorconversion=\v!normal]

\definebtx
  [apa:\s!cite:author]
  [apa:\s!cite]

\definebtx
  [apa:\s!cite:authoryear]
  [apa:\s!cite:author]
  [\c!left={(},
   \c!right={)},
   \c!inbetween={\btxcomma}]

\definebtx
  [apa:\s!cite:default]
  [apa:\s!cite:authoryear]

\definebtx
  [apa:\s!cite:authoryears]
  [apa:\s!cite:authoryear]
  [\c!left=,
   \c!right=,
   \c!inbetween={\btxspace}]

\definebtx
  [apa:\s!cite:authornum]
  [apa:\s!cite:author]
  [\c!left={(},
   \c!right={)}]

\definebtx
  [apa:\s!cite:author:num] % todo
  [apa:\s!cite:authornum]
  [\c!left={\btxspace[},
   \c!right={]}]

\definebtx
  [apa:\s!cite:author:year] % todo
  [apa:\s!cite]

\definebtx
  [apa:\s!cite:author:years] % todo
  [apa:\s!cite:authoryears]
  [\c!inbetween=,
   \c!left={\btxspace(},
   \c!right={)}]

\definebtx
  [apa:\s!cite:year]
  [apa:\s!cite]
  [\c!separator:2={\btxcomma}, % :0 and :1 - between items of a list
   \c!separator:3={\btxcomma\btxlabeltext{apa:and}\space}, % not \textampersand
   \c!separator:4={\btxspace\btxlabeltext{apa:and}\space}] % not \textampersand

\definebtx
  [apa:\s!cite:title]
  [apa:\s!cite]
  [\c!separator:2={\btxcomma}, % :0 and :1 - between items of a list
   \c!separator:3={\btxcomma\btxlabeltext{apa:and}\space}, % not \textampersand
   \c!separator:4={\btxspace\btxlabeltext{apa:and}\space}, % not \textampersand
   \c!command={\language[\currentbtxlanguage]}, % BAH
   \c!sorttype=none,
   \c!style=\v!italic]

\definebtx
  [apa:\s!cite:booktitle]
  [apa:\s!cite:title]

\definebtx
  [apa:\s!cite:tag]
  [apa:\s!cite]
  [\c!left={[},
   \c!right={]}]


\definebtx
  [apa:\s!cite:index]
  [apa:\s!cite]
  [\c!left={[},
   \c!right={]}]

\definebtx
  [apa:\s!cite:page]
  [apa:\s!cite]
  [\c!left=,
   \c!right=,
   \c!separator:2={\btxcomma}, % :0 and :1 - between items of a list
   \c!separator:3={\btxcomma\btxlabeltext{apa:and}\space}, % not \textampersand
   \c!separator:4={\btxspace\btxlabeltext{apa:and}\space}] % not \textampersand

\definebtx
  [apa:\s!cite:pages]
  [apa:\s!cite:page]

\definebtx
  [apa:\s!cite:keywords]
  [apa:\s!cite]

\definebtx
  [apa:\s!cite:short]
  [apa:\s!cite]
  [\c!left={[},
   \c!right={]}]

\definebtx
  [apa:\s!cite:category]
  [apa:\s!cite]

\definebtx
  [apa:\s!cite:url]
  [apa:\s!cite]
  [\c!left={[},
   \c!right={]}]

\definebtx
  [apa:\s!cite:doi]
  [apa:\s!cite:url]

\definebtx
  [apa:\s!cite:num]
  [apa:\s!cite]
  [\c!left={[},
   \c!right={]},
   \c!separator:2={,}, % no space
   \c!separator:3=\btxparameter{\c!separator:2},
   \c!separator:4=\btxparameter{\c!separator:2}]

\definebtx
  [apa:\s!cite:textnum]
  [apa:\s!cite:num]
  [\c!left={Ref.\nbsp},
   \c!right=,
   \c!separator:2={\btxcomma},
   \c!separator:3={\btxspace\btxlabeltext{apa:and}\space},
   \c!separator:4={\btxspace\btxlabeltext{apa:and}\space}]

\definebtx
  [apa:\s!cite:entry]
  [apa:\s!cite]
  [\c!left=,
   \c!right=,
   \c!inbetween={\btxspace},
   \c!separator:2={\btxsemicolon},
   \c!separator:3=\btxparameter{\c!separator:2},
   \c!separator:4=\btxparameter{\c!separator:2}]

% Now we setup for the details of the renderings

%D Sometimes we have verbose injections in an entry and these can be language
%D dependent, so we use labels.
%D
%D Because we want to mix rendering (in the manual) we need a namespace in label
%D texts:

\setupbtxlabeltext
  [en]
  [apa:and=and,
   apa:number={no.},
   apa:edition={ed.},
   apa:Editor={Ed.},
   apa:Editors={Eds.},
   apa:Volume={Vol.},
   apa:Volumes={Vols.},
   apa:others={et al.},
   apa:page={p.},
   apa:pages={pp.},
   apa:nd={n.d.},     % no date
   apa:mastersthesis={Master's thesis},
   apa:phdthesis={Doctoral dissertation},
   apa:technicalreport={Tech. Rep.},  % Technical report
   apa:supplement={Suppl.},           % Supplement (not used?)
   apa:patent=Patent,
   apa:MotionPicture={Motion picture},
   apa:Producer=Producer,
   apa:Producers=Producers,
   apa:Director=Director,
   apa:Directors=Directors,
   apa:Recordedby={Recorded by},
   apa:Author=Author,
   apa:Translator={Trans.},           % Translator(s) (not used?)
   apa:Advanced={Advanced online publication},
   apa:Retrieved={Available from},    % {Retrieved from},
   apa:In=In]

\setupbtxlabeltext
  [nl]
  [apa:and=en,
   apa:number={nr.},
   apa:edition={ed.}, % editie
   apa:Editor=Editor, % Ed./Eds.
   apa:Editors=Editors,
   apa:Volume={Vol.},
   apa:Volumes={Vols.},
   apa:others={et al.},
   apa:page={p.},
   apa:pages={pp.},
   apa:nd={g.d.}      % geen datum
   apa:mastersthesis=Masterproef,
   apa:phdthesis=Proefschrift,
   apa:technicalreport={Technisch rapport},  % Technical report
   apa:supplement=Supplement,
   apa:patent=Octrooi,
   apa:MotionPicture=Film, % ?
   apa:Producer=Producent,   % ?
   apa:Producers=Producents, % ?
   apa:Director=Directeur,
   apa:Directors=Directeurs,
   apa:Recordedby={Opgenomen door}, % ?
   apa:Author=Auteur,
   apa:Translator=Vertaler,
   apa:Advanced={Geavanceerde online publicatie},
   apa:Retrieved={Beschikbaar vanaf},    % {Ontvangen van},
   apa:In=In]

\setupbtxlabeltext
  [fr]
  [apa:and=et,
   apa:number={n\high{o}},
   apa:edition={édition},
   apa:Editor=Éditeur,
   apa:Editors=Éditeurs,
   apa:Volume=Volume,
   apa:Volumes=Volumes,
   apa:others={et al.},
   apa:page={p.},
   apa:pages={pp.},
   apa:nd={s.d.}      % sans date
   apa:mastersthesis={Thèse de master (DEA, DESS, master)},
   apa:phdthesis={Thèse de doctorat},
   apa:technicalreport={Rapport technique},
   apa:supplement=Supplément,
   apa:patent=Brevet,
   apa:MotionPicture={Film cinématographique},
   apa:Producer=Producteur,
   apa:Producers=Producteurs,
   apa:Director=Réalisateur,
   apa:Directors=Réalisateurs,
   apa:Recordedby={Enregistré par},
   apa:Author=Auteur,
   apa:Translator=Traducteur,
   apa:Advanced={Publication en ligne anticipée},
   apa:Retrieved={Disponible à},      % {Téléchargé de},
   apa:In=Dans]

\setupbtxlabeltext
  [de]
  [apa:and=und,
   apa:number={nr.},
   apa:edition=Auf\/lage,
   apa:Editor=Herausgeber, % Hrsg./Hg.
   apa:Editors=Herausgeber,
   apa:Volume=Band,        % Bd.
   apa:Volumes={Bände},
   apa:others={et al.},
   apa:page={S.},
   apa:pages={S.},
   apa:nd={o.D.},          % ohne Datum (mostly: o.J. / ohne Jahr)
   apa:mastersthesis={Masterarbeit},
   apa:phdthesis={Dissertation},
   apa:technicalreport={Technischer Bericht},
   apa:supplement={Beilage},          % Supplement
   apa:patent=Patent,
   apa:MotionPicture=Kinofilm, % ?
   apa:Producer=Producer,      % ?
   apa:Producers=Produzenten,  % ?
   apa:Director=Director,      % ?
   apa:Directors=Directors,    % ?
   apa:Recordedby={per Einschreiben}, % ?
   apa:Author=Autor,
   apa:Translator={Übersetzer},       % Übers.
   apa:Advanced={Erweiterte Online-Publikation},
   apa:Retrieved={heruntergeladen von},
   apa:In=In]

% thanks: Andrea Valle

\setupbtxlabeltext
  [it]
  [apa:and=e,
   apa:number={nº},
   apa:edition={ed.}, % edizione
   apa:Editor={A cura di},
   apa:Editors={A cura di},
   apa:Volume={Vol.},  % Volume
   apa:Volumes={Vol.}, % Volumi
   apa:others={et al.},
   apa:page={p.},
   apa:pages={pp.},
   apa:nd={s.d.},     % senza data
   apa:mastersthesis={Tesi di laurea},
   apa:phdthesis={Tesi di dottorato},
   apa:technicalreport={Relazione tecnica},
   apa:supplement={Supplemento},
   apa:patent=Brevetto,
   apa:MotionPicture=Film, % ?
   apa:Producer=Produttore,
   apa:Producers=Produttori,
   apa:Director=Direttore,
   apa:Directors=Direttori,
   apa:Recordedby={Registrato da},
   apa:Author=Autore,
   apa:Translator={Trad.},                        % Translator(s)
   apa:Advanced={Pre-pubblicazione on line},
   apa:Retrieved={Accessible online},
   apa:In=In]

\setupbtxlabeltext
  [es]
  [apa:and=y,
   apa:number={nº},
   apa:edition={ed.}, % edición
   apa:Editor=Editor, % Ed./Eds.
   apa:Editors=Editores,
   apa:Volume={Vol.},   % Volumen
   apa:Volumes={Vols.}, % Volúmenes
   apa:others={et al.},
   apa:page={p.},
   apa:pages={pp.},
   apa:nd={s.f.},     % sin fecha
   apa:mastersthesis={Tesis de maestría},
   apa:phdthesis={Tesis doctoral},
   apa:technicalreport={Informe técnico},
   apa:supplement=Suplemento,
   apa:patent=Patente,
   apa:MotionPicture=Cinematográfica,
   apa:Producer=Productor,
   apa:Producers=Productores,
   apa:Director=Director,
   apa:Directors=Directores,
   apa:Recordedby={Grabada por},
   apa:Author=Autor,
   apa:Translator=Traductor,
   apa:Advanced={Publicación en línea avanzada},
   apa:Retrieved={Disponible desde},    % {Obtenido de},
   apa:In=En]

% cite setups

% The following differs from the default returning n.d. if year is empty

\startsetups btx:apa:nd
    \btxlabeltext{apa:nd}
\stopsetups

\startsetups btx:apa:cite:author:year
    \texdefinition{\s!btx:\s!cite:concat}
   %\btxparameter\c!left
    \ifx\currentbtxfirst\empty
        \fastsetup{btx:apa:nd}
    \else
        \texdefinition {\s!btx:\s!cite:inject} {
            \btxcitereference
            \currentbtxfirst
        }
        \ifx\currentbtxsecond\empty \else
            \btxparameter\c!range
            \texdefinition {\s!btx:\s!cite:inject} {
                \currentbtxsecond
            }
        \fi
        \btxflushsuffix
    \fi
   %\btxparameter\c!right
\stopsetups

\startsetups btx:apa:cite:author:years
    \fastsetup{btx:apa:cite:author:year}
\stopsetups

% used in publ-imp-page.mkvi

\startsetups [btx:apa:list:page-or-pages]
    \ifx\currentbtxlastpage\empty
        \btxlabeltext{apa:page}
    \else
        \btxlabeltext{apa:pages}
    \fi
    \btxnbsp
\stopsetups

% The sameauthor feature may not be APA compliant
% (there is nothing in the manual cited above).
% It can be removed using the command:
% \resetsetups [apa:list:sameauthor]

% :rule, :empty or :ditto ...

\startsetups apa:list:sameauthor
    \fastsetup{apa:list:sameauthor:rule}
\stopsetups

\startsetups apa:list:sameauthor:rule
    \blackrule
      [\c!width=\dimexpr\listparameter\c!margin-\interwordspace\relax,
       \c!height=1.5\linewidth]% \linewidth is just too thin with respect to font strokes...
\stopsetups

\startsetups [apa:list:sameauthor:\v!empty]
    \kern\dimexpr\listparameter\c!margin-\interwordspace\relax
\stopsetups

% horrible !

\startsetups apa:list:sameauthor:ditto
    \inframed
      [\c!width=\dimexpr\listparameter\c!margin-\interwordspace\relax,
       \c!frame=\v!off,
       \c!align=\v!middle]
      {\doubleprime}
\stopsetups

%D Instead of texdefinitions without arguments, we could have used setups but in my
%D editor (hh, scite) the commands stand out better. It also saves an additional
%D component in the name (e.g. common:) because commands and setups have a different
%D namespace, so similar calls don't clash. Performance of definitions is somewhat
%D better.

%D We use "texdefinitions" (with eventual arguments) for helpers that are used
%D in the rendering "setups" defined for each category below.

%D Note that \btxdoif... and \btxflush rely on the definitions in
%D publ-imp-apa.lua: fields that are not listed as required nor optional are
%D IGNORED. We also make heavy use of the notion of sets - comma-separated lists
%D of alternative fields to be used in hierarchal order. For example:
%D author = { "author", "editor", "publisher", "title" }, will return the
%D author field if it exists; if not, the editor field will be returned, if it
%D exists; if not, the publisher field will be returned, if it exists; if not,
%D the title field will be returned, it it exists; if not, nothing will be
%D returned. In lua syntax, it can be understood as
%D author or editor or publisher or title or ""

% #title can be title or booktitle

\starttexdefinition btx:apa:translated-title #title
    \ifx\currentbtxlanguage\empty
        % no need for an extra
    \else\ifx\mainbtxlanguage\currentbtxlanguage
        % no need for an extra
    \else
        \btxdoif {#title:\mainbtxlanguage} {
            \begingroup
                \language[\mainbtxlanguage]
                \btxleftbracket
                \btxusecommand [apa:\s!list:title:\currentbtxcategory] {
                    \btxflush{#title:\mainbtxlanguage}
                }
                \btxrightbracket
            \endgroup
        }
    \fi\fi
\stoptexdefinition

\starttexdefinition btx:apa:composed-title #title
    \btxstartstyleandcolor [apa:\s!list:title:\currentbtxcategory]
        \begingroup
            \language[\currentbtxlanguage]
            \btxusecommand [apa:\s!list:title:\currentbtxcategory] {
                \btxflush{#title}
                \btxdoif {sub#title} {
                    \btxcolon
                    \btxflush{sub#title}
                }
            }
        \endgroup
        % which namespace?
        %\doif{\btxparameter{translate}}\v!yes {
            \texdefinition{btx:apa:translated-title}{#title}
        %}
    \btxstopstyleandcolor
\stoptexdefinition

\starttexdefinition btx:apa:title
    \setmode{btx:apa:title-placed}
    % we make the title active, opening "file"
    \btxdoifelse {file} {
        \texdefinition{btx:format:inject}
            {url(file:\btxflush{file})}
            {
                \texdefinition{btx:apa:composed-title}{title}
            }
    } {
        \texdefinition{btx:apa:composed-title}{title}
    }
    \btxdoif {title} {
        \btxperiod
        % TODO: this period may NOT be wanted, as in: Title (2nd ed.).
    }
\stoptexdefinition

\starttexdefinition btx:apa:title-if-not-placed
    \doifelsemode {btx:apa:title-placed} {
        \resetmode{btx:apa:title-placed}
    } {
        \btxdoif {title} {
            \btxspace
            \texdefinition {btx:apa:title}
        }
    }
\stoptexdefinition

\starttexdefinition btx:apa:suffixedyear
    \btxdoifelse {year} {
        \btxflush{year}
        \btxflushsuffix
    } {
        \fastsetup{btx:apa:nd}
        % Hans: the following won't work but should.
        \btxdoif {suffix} {
            \btxspace
            \btxflushsuffix
            % Hans: similarly, why can't \btxflush{suffix} be made to work?
        }
    }
\stoptexdefinition

% #author may be author(set) or editor

\starttexdefinition btx:apa:author-or-editor #author
    \btxdoif {#author} {
        \btxflush{#author}
        \doifelse {\btxfoundname{#author}} {editor} {
            \btxleftparenthesis
            \btxsingularorplural {editor} {
                \btxlabeltext{apa:Editor}
            } {
                \btxlabeltext{apa:Editors}
            }
            \btxrightparenthesisperiod
        } {
            \doifelse {\btxfoundname{#author}} {producer} {
                \btxleftparenthesis
                \btxsingularorplural {producer} {
                    \btxlabeltext{apa:Producer}
                } {
                    \btxlabeltext{apa:Producers}
                }
                \btxrightparenthesis
                \btxdoifelse {director} {
                    \removeunwantedspaces
                    \btxparameter{\c!separator:names:3}
                    \btxflush{director}
                    \btxleftparenthesis
                    \btxsingularorplural {director} {
                        \btxlabeltext{apa:Director}
                    } {
                        \btxlabeltext{apa:Directors}
                    }
                    \btxrightparenthesisperiod
                } {
                    \btxperiod
                }
            } {
                \doif {\btxfoundname{#author}} {director} {
                    \btxleftparenthesis
                    \btxsingularorplural {director} {
                        \btxlabeltext{apa:Director}
                    } {
                        \btxlabeltext{apa:Directors}
                    }
                    \btxrightparenthesisperiod
                }
            }
        }
    }
\stoptexdefinition

\starttexdefinition btx:apa:authoryear
    % we make the authoryear active, pointing to the citation
    \texdefinition{btx:format:inject}
        {internal(\currentbtxinternal)}
        {
            \doifelsesetups{apa:list:sameauthor} {
                \btxdoifelsesameasprevious {author} {
                    \fastsetup{apa:list:sameauthor}
                } {
                    \texdefinition{btx:apa:author-or-editor} {author}
                }
            } {
                \texdefinition{btx:apa:author-or-editor} {author}
            }
            \btxleftparenthesis
            \texdefinition{btx:apa:suffixedyear}
            \btxrightparenthesis
        }
    % outside of interaction
    \btxperiod
    \doif {\btxfoundname{author}} {title} {
        \setmode{btx:apa:title-placed}
    }
\stoptexdefinition

\starttexdefinition btx:apa:editor-in
    \btxdoif {booktitle} {
        \btxlabeltext{apa:In}
        \doifnot {\btxfoundname{author}} {editor} {
            \btxspace
            \texdefinition{btx:apa:author-or-editor} {editor}
        }
        \btxspace
        \texdefinition{btx:apa:composed-title} {booktitle}
        \btxperiod
    }
\stoptexdefinition

% TODO: The title is terminated with period. However,
% we probably don't want this before the parenthesis.

\starttexdefinition btx:apa:leftparenthesis-or-comma
    \doifelsemode {btx:apa:editionset-is-empty} {
        \btxleftparenthesis
        \resetmode{btx:apa:editionset-is-empty}
    } {
        \btxcomma
    }
\stoptexdefinition

\starttexdefinition btx:apa:editionset
    \setmode{btx:apa:editionset-is-empty}
    \doif {\currentbtxcategory} {techreport} {
        \texdefinition{btx:apa:leftparenthesis-or-comma}
        \btxdoifelse {type} {
            \btxusecommand [apa:\s!list:type] {
                \btxflush{type}
            }
        } {
            \btxlabeltext{apa:technicalreport}
        }
    }
    \btxdoif {volume} {
        \texdefinition{btx:apa:leftparenthesis-or-comma}
        \btxoneorrange {volume} {
            \btxlabeltext{apa:Volume}
        } {
            \btxlabeltext{apa:Volumes}
        }
        \btxspace
        \btxflush{volume}
    }
    \btxdoif {number} {
        \texdefinition{btx:apa:leftparenthesis-or-comma}
        \btxlabeltext{apa:number}
        \btxspace
        \btxflush{number}
    }
    \btxdoif {edition} {
        \texdefinition{btx:apa:leftparenthesis-or-comma}
        \btxflush{edition}
        \btxspace
        \btxlabeltext{apa:edition}
    }
    \btxdoif {pages} {
        \texdefinition{btx:apa:leftparenthesis-or-comma}
        \btxoneorrange {pages} {
            \btxlabeltext{apa:page}
        } {
            \btxlabeltext{apa:pages}
        }
        \btxnbsp
        \btxflush{pages}
    }
    \doifnotmode {btx:apa:editionset-is-empty} {
        \btxrightparenthesisperiod
    }
\stoptexdefinition

\starttexdefinition btx:apa:journal
    \btxstartstyleandcolor[apa:\s!list:journal]
        \btxusecommand [apa:\s!list:journal] {
            \btxflush{journal}
        }
    \btxstopstyleandcolor
\stoptexdefinition

\starttexdefinition btx:apa:volume
    \btxstartstyleandcolor[apa:\s!list:volume]
        \btxflush{volume}
    \btxstopstyleandcolor
\stoptexdefinition

 % this could be simplified!

\starttexdefinition btx:apa:journal-volume-number-pages
    \btxdoif {journal} {
        \btxspace
        \texdefinition{btx:apa:journal}
        \btxdoifelse {volume} {
            \btxcomma
            \texdefinition{btx:apa:volume}
            \btxdoif {number} {
                %\btxleftparenthesis
                (\btxflush{number}
                \btxrightparenthesis
            }
        } {
            \btxdoif {number} {
                \btxcomma
                \btxleftparenthesis
                \btxflush{number}
                \btxrightparenthesis
            }
        }
        \btxdoif {pages} {
            \btxcomma
            \doif {\currentbtxcategory} {newspaper} {
                \btxoneorrange {pages} {
                    \btxlabeltext{apa:page}
                } {
                    \btxlabeltext{apa:pages}
                }
                \btxnbsp
            }
            \btxflush{pages}
        }
        \btxperiod
        \doifnot {\currentbtxcategory} {newspaper} {
            \btxdoifnot {volume} {
                \btxdoifnot {number} {
                    \btxdoifnot {pages} {
                        \btxdoif {doi} {%set: doi or url
                            \btxspace
                            \btxlabeltext{apa:Advanced}
                            \btxperiod
                        }
                    }
                }
            }
        }
    }
\stoptexdefinition

\starttexdefinition btx:apa:wherefrom-publisher
    \btxdoifelse {address} {
        \btxflush{address}
        \btxdoif {country} {
            \btxcomma
            \btxflush{country}
        }
        \btxcolon
    } {
        \btxdoif {country} {
            \btxflush{country}
            \btxcolon
        }
    }
    \doifelse {\btxfoundname{author}} {\btxfoundname{publisher}} {
        \btxlabeltext{apa:Author}
    } {
        \btxdoifelse {publisher} {
            \btxflush{publisher}
        } {
            \btxlabeltext{apa:Author}
        }
    }
    \btxperiod
\stoptexdefinition

\definebreakpoints[doi]
\definebreakpoint [doi][:][nleft=3,type=1]
\definebreakpoint [doi][/][nleft=3,type=1]
\definebreakpoint [doi][-][nleft=3,type=1]
\definebreakpoint [doi][.][nleft=3,type=1]

% use \btxentry here?

\starttexdefinition btx:apa:url
    \btxspace
    \btxlabeltext{apa:Retrieved}
    \btxspace
    \begingroup
        \setbreakpoints[doi]
        \ifconditional\btxinteractive
            \goto {
                \hyphenatedurl{\btxflush{url}}
            } [
                url(\btxflush{url})
            ]
        \else
            \hyphenatedurl{\btxflush{url}}
        \fi
    \endgroup
\stoptexdefinition

% use \btxentry here?

\starttexdefinition btx:apa:doi
    \btxspace
    \begingroup
        \setbreakpoints[doi]
        \ifconditional\btxinteractive
            \goto {
                \hyphenatedurl{doi:\btxflush{doi}}
            } [
                url(http://dx.doi.org/\btxflush{doi})
            ]
        \else
            \hyphenatedurl{doi:\btxflush{doi}}
        \fi
    \endgroup
\stoptexdefinition

\starttexdefinition btx:apa:note
    \btxdoif {note} {
        \btxleftparenthesis
        \btxflush{note}
        \btxrightparenthesis
    }
\stoptexdefinition

\starttexdefinition btx:apa:url-doi-note
    \doif {\btxfoundname{doi}} {url} {
        \texdefinition{btx:apa:url}
    }
    \doif {\btxfoundname{doi}} {doi} {
        \texdefinition{btx:apa:doi}
    }
    \texdefinition{btx:apa:note}
    \removeunwantedspaces
\stoptexdefinition

% Then setups, by category

% An article from a journal
% Required fields: author or editor or title, journal, (year).
% Optional fields: volume, number, pages, type, doi, url, note.
% Note that bibtex (and tools) do not include editor (e.g. special issue or section)

\startsetups btx:apa:list:article
    \texdefinition{btx:apa:authoryear}
    \texdefinition{btx:apa:title-if-not-placed}
    \btxdoif {type} {
        \btxleftbracket
        \btxflush{type}
        \btxrightbracketperiod
    }
    \texdefinition{btx:apa:journal-volume-number-pages}
    \texdefinition{btx:apa:url-doi-note}
\stopsetups

% An article from a magazine.
% Required fields: author or title, journal, (year).
% Optional fields: number, pages, type, month, day, doi, url, note.

\startsetups btx:apa:list:magazine
    \fastsetup{btx:apa:list:article}
\stopsetups

% An article from a newspaper.
% Required fields: author or title, journal, (year).
% Optional fields: volume, number, pages, type, month, day, doi, url, note.

\startsetups btx:apa:list:newspaper
    \fastsetup{btx:apa:list:article}
\stopsetups

% A complete issue of a periodical, such as a special issue of a journal.
% Required fields: title, year
% Optional fields: editor, publisher, subtitle, series, volume, number, month, organization, doi, url, issn, note

% needs to be tuned...

\startsetups btx:apa:list:periodical
    \fastsetup{btx:apa:list:article}
\stopsetups

% National and international standards issued by a standards body
% Required fields: author, institution, or organization, year, title
% Optional fields: subtitle, doi, url, note

\startsetups btx:apa:list:standard
    \texdefinition{btx:apa:authoryear}
    \texdefinition{btx:apa:title-if-not-placed}
    \texdefinition{btx:apa:url-doi-note}
\stopsetups

% A book with an explicit publisher.
% Required fields: author or editor or publisher, title, (year).
% Optional fields: volume or number, series, address, edition, month, day, note.
% APA ignores: month, day

% todo: series?

\startsetups btx:apa:list:book
    \texdefinition{btx:apa:authoryear}
    \texdefinition{btx:apa:title-if-not-placed}
    \texdefinition{btx:apa:editionset}
    \texdefinition{btx:apa:wherefrom-publisher}
    \texdefinition{btx:apa:url-doi-note}
\stopsetups

% There is some debate about how inbook should differ from incollection

% A part of a book, which may be a chapter (or section or whatever) and/or a range of pages.
% (note that inbook is handled differently by bibtex and biblatex)
% Required fields: author or editor, title, chapter and/or pages, publisher, year.
% Optional fields: volume or number, series, type, address, edition, month, note.
% We add optional: booktitle.
% APA ignores: chapter, month

\startsetups btx:apa:list:inbook
    \texdefinition{btx:apa:authoryear}
    \texdefinition{btx:apa:title-if-not-placed}
    \texdefinition{btx:apa:editor-in}
    \texdefinition{btx:apa:editionset}
    \texdefinition{btx:apa:wherefrom-publisher}
    \texdefinition{btx:apa:url-doi-note}
\stopsetups

% A part of a book having its own title.
% Required fields: author, title, booktitle, publisher, year.
% Optional fields: editor, volume or number, series, type, chapter, pages, address, edition, month, note.
% APA ignores: chapter, month

\startsetups btx:apa:list:incollection
    \fastsetup{btx:apa:list:inbook}
\stopsetups

% The proceedings of a conference.
% Required fields: title, year.
% Optional fields: editor, volume or number, series, address, month, organization, publisher, note.
% todo: series?

\startsetups btx:apa:list:proceedings
    \fastsetup{btx:apa:list:book}
\stopsetups

% An article in a conference proceedings.
% Required fields: author, title, booktitle, year.
% Optional fields: editor, volume or number, series, pages, address, month, organization, publisher, note.

\startsetups btx:apa:list:inproceedings
    \texdefinition{btx:apa:authoryear}
    \texdefinition{btx:apa:title-if-not-placed}
    \texdefinition{btx:apa:editor-in}
    \texdefinition{btx:apa:editionset}
    \btxdoif {organization} {
        \btxspace
        \btxflush{organization}
        \btxcomma
    }
    \texdefinition{btx:apa:wherefrom-publisher}
    \texdefinition{btx:apa:url-doi-note}
\stopsetups

\startsetups btx:apa:list:conference
    \fastsetup{btx:apa:list:inproceedings}
\stopsetups

% A thesis.
% Required fields: author, title, school, year.
% Optional fields: type, address, month, note.

\startsetups btx:apa:list:thesis
    \texdefinition{btx:apa:authoryear}
    \texdefinition{btx:apa:title-if-not-placed}
    \btxleftparenthesis
    \btxdoifelse {type} {
        \btxusecommand [apa:\s!list:type] {
            \btxflush{type}
        }
    } {
        \btxlabeltext{apa:\currentbtxcategory}
    }
    \btxrightparenthesis
    \btxdoif {school} {
        \btxperiod
        \btxflush{school}
    }
    \btxdoif {address} {
        \btxdoifelse {school} {
            \btxcomma
        } {
            \btxperiod
        }
        \btxflush{address}
        \btxdoif {country} {
            \btxcomma
            \btxflush{country}
        }
    }
    \btxperiod
    \texdefinition{btx:apa:url-doi-note}
\stopsetups

\startsetups btx:apa:list:phdthesis
    \fastsetup{btx:apa:list:thesis}
\stopsetups

\startsetups btx:apa:list:mastersthesis
    \fastsetup{btx:apa:list:thesis}
\stopsetups

% A work that is printed and bound, but without a named publisher or sponsoring institution.
% Required field: title.
% Optional fields: author, howpublished, address, month, year, note.

\startsetups btx:apa:list:booklet
    \fastsetup{btx:apa:list:book}
\stopsetups

% Technical documentation.
% Required field: title.
% Optional fields: author, organization, address, edition, month, year, note.

\startsetups btx:apa:list:manual
    \fastsetup{btx:apa:list:book}
\stopsetups

% A report published by a school or other institution, usually numbered within a series.
% Required fields: author, title, institution, year.
% Optional fields: type, number, address, month, note.

\startsetups btx:apa:list:techreport
    \fastsetup{btx:apa:list:book}
\stopsetups

% A document having an author and title, but not formally published.
% Required fields: author, title, note.
% Optional fields: month, year.

\startsetups btx:apa:list:unpublished
    \fastsetup{btx:apa:list:book}
\stopsetups

% A patent. Note that this category was not defined with BIBTEX. Below from JabRef:
% Required fields: nationality, number, year, yearfiled
% Optional fields: author, title, assignee, address, type, number, day, dayfiled, month, monthfiled, note, url
% Also optional: publisher

% todo: yearfiled, monthfiled, dayfiled

\startsetups btx:apa:list:patent
    \texdefinition{btx:apa:authoryear}
    \texdefinition{btx:apa:title-if-not-placed}
    \begingroup
        \it
        \btxdoif {nationality} {
            \btxspace
            \btxflush{nationality}
        }
        \btxspace
        \btxlabeltext{apa:patent}
        \btxdoif {number} {
            \btxspace
            \btxlabeltext{apa:number}
            \btxspace
            \btxflush{number}
        }
        \btxperiod
        \italiccorrection
    \endgroup
    \texdefinition{btx:apa:wherefrom-publisher}
    \texdefinition{btx:apa:url}
    \texdefinition{btx:apa:note}
\stopsetups

% Electronic. Note that this category was not defined with BIBTEX. Below from JabRef:
% Required fields: title
% Optional fields: address, author, howpublished, month, note, organization, url, year, doi
% Also optional: type

% Like Misc below but includes organization.

\startsetups btx:apa:list:electronic
    \texdefinition{btx:apa:authoryear}
    \texdefinition{btx:apa:title-if-not-placed}
    \btxdoif {organization} {
        \btxspace
        \btxflush{organization}
        \btxperiod
    }
    \btxdoif {howpublished} {
        \btxspace
        \btxflush{howpublished}
        \btxperiod
    }
    \texdefinition{btx:apa:url-doi-note}
\stopsetups

% Film. Note that this category was not defined with BIBTEX.
% Required fields: producer, director, title, year, address, publisher
% Optional fields: subtitle, type, note, url, doi

\startsetups btx:apa:list:film
    \texdefinition{btx:apa:authoryear}
    \texdefinition {btx:apa:title}
    \btxleftbracket
        \btxdoifelse {type} {
            \btxflush{type}
        } {
            \btxlabeltext{apa:MotionPicture}
        }
    \btxrightbracketperiod
    \texdefinition{btx:apa:wherefrom-publisher}
    \texdefinition{btx:apa:url-doi-note}
\stopsetups

% Music. Note that this category was not defined with BIBTEX.
% Required fields: composer, artist, title, album, year, address, publisher
% Optional fields: subtitle, type, note, url, doi

\startsetups btx:apa:list:music
    \texdefinition{btx:apa:authoryear}
    \texdefinition{btx:apa:title-if-not-placed}
    \doifnot {\btxfoundname{author}} {artist} {
        \btxdoif {artist} {
            \btxleftbracket
            \btxlabeltext{apa:Recordedby}
            \btxspace
            \btxflush{artist}
            \btxrightbracketperiod
        }
    }
    \doifnot {\btxfoundname{title}} {album} {
        \btxdoif {album} {
            \btxlabeltext{apa:In}
            \btxspace
            \btxflush{album}
            \btxperiod
        }
    }
    \btxdoif {type} {
        \btxleftbracket
        \btxflush{type}
        \btxrightbracketperiod
    }
    \texdefinition{btx:apa:wherefrom-publisher}
    \texdefinition{btx:apa:url-doi-note}
\stopsetups

% Other. Note that this category was not defined with BIBTEX. Below from JabRef:
% Required fields: author or title, year
% Optional fields: note, doi, url

\startsetups btx:apa:list:other
    \fastsetup{btx:apa:list:book}
\stopsetups

% Use this type when nothing else fits.
% Required fields: none.
% Optional fields: author, title, howpublished, month, year, note.

\startsetups btx:apa:list:misc
    \texdefinition{btx:apa:authoryear}
    \texdefinition{btx:apa:title-if-not-placed}
    \btxdoif {howpublished} {
        \btxspace
        \btxflush{howpublished}
        \btxperiod
    }
    \texdefinition{btx:apa:url-doi-note}
\stopsetups

% If all else fails to match:

\startsetups btx:apa:list:literal
    %\btxleftparenthesis
    \removeunwantedspaces(
    \btxflush{tag}
    \btxrightparenthesis
    \btxdoif {text} {
        \btxflush{text}
    }
\stopsetups

% HH: an example of setting up translations using a sub rendering. Keep it here
% till we find another spot as otherwise I forget about it and I don't want to
% waste hours reinventing a wheel when something like this is needed.
%
% \definebtx
%   [apa:cite:title:translated]
%   [apa:cite:title]
%   [left=\btxleftbracket,
%    right=\btxrightbracket,
%    style=\v!bolditalic]
%
% \startsetups btx:apa:cite:title
%     % need to add concat, etc.
%     \btxcitereference
%     \currentbtxfirst
%     \doifmode {btx:apa:translatedtitles} {
%         \ifx\currentbtxlanguage\empty
%             % no need for an extra
%         \else\ifx\mainbtxlanguage\currentbtxlanguage
%             % no need for an extra
%         \else
%             \btxdoif {title:\mainbtxlanguage} {
%                 \btxstartciterendering[title:translated]
%                     \language[\mainbtxlanguage]
%                     \btxflush{title:\mainbtxlanguage}
%                 \btxstopciterendering
%             }
%         \fi\fi
%     }
% \stopsetups

\stopbtxrenderingdefinitions
