# -*- mode: Perl -*-
# /=====================================================================\ #
# |  revtex4 support                                                    | #
# | Implementation for LaTeXML                                          | #
# |=====================================================================| #
# | Part of LaTeXML:                                                    | #
# |  Public domain software, produced as part of work done by the       | #
# |  United States Government & not subject to copyright in the US.     | #
# |---------------------------------------------------------------------| #
# | Thanks to Catalin David <c.david@jacobs-university.de>              | #
# | of the arXMLiv group for initial implementation                     | #
# |    http://arxmliv.kwarc.info/                                       | #
# | Released to the Public Domain                                       | #
# |---------------------------------------------------------------------| #
# | Bruce Miller <bruce.miller@nist.gov>                        #_#     | #
# | http://dlmf.nist.gov/LaTeXML/                              (o o)    | #
# \=========================================================ooo==U==ooo=/ #
package LaTeXML::Package::Pool;
use strict;
use warnings;
use LaTeXML::Package;

RequirePackage('hyperref');
RequirePackage('natbib');    # not necessarily loaded?
RequirePackage('revsymb');
RequirePackage('url');
RequirePackage('longtable');
# Not sure this strictly required
RequirePackage('dcolumn');

# Aligned to RevTeX4 Authors guide (auguide)

#======================================================================
# 4. The Front Matter
#======================================================================

# 4.3
DefMacro('\title[]{}', '\@add@frontmatter{ltx:title}{#2}');

DefMacro('\doauthor{}{}{}', '#1 #2 #3');       # -- ??
DefMacro('\address',        '\affiliation');
# DefMacro('\affiliation','');
DefConstructor('\@@@affiliation{}', "^ <ltx:contact role='affiliation'>#1</ltx:contact>");
DefMacro('\affiliation{}',  '\@add@to@frontmatter{ltx:creator}{\@@@affiliation{#1}}');
DefMacro('\altaddress',     '\altaffiliation');
DefMacro('\altaffiliation', '\affiliation');
DefMacro('\andname',        'and');
DefMacro('\collaboration',  '');               # Should have a look at this too
DefMacro('\noaffiliation',  Tokens());

DefConstructor('\@@@email{}', "^ <ltx:contact role='email'>#1</ltx:contact>");
DefMacro('\email [] Semiverbatim', '\@add@to@frontmatter{ltx:creator}{\@@@email{#2}}');
DefConstructor('\@@@homepage{}', "^ <ltx:contact role='url'>#1</ltx:contact>");
DefMacro('\homepage Semiverbatim', '\@add@to@frontmatter{ltx:creator}{\@@@homepage{#1}}');

DefMacro('\firstname', '');                    # \let\firstname\@firstofone ??
DefConstructor('\surname{}', "#1");

# 4.4
DefMacro('\abstractname', 'Abstract');

# 4.5
DefMacro('\pacs{}', '\@add@frontmatter{ltx:classification}[scheme=pacs]{#1}');

# 4.6
DefMacro('\keywords{}', '\@add@frontmatter{ltx:keywords}{#1}');

# 4.7
DefMacro('\preprint{}', '\@add@frontmatter{ltx:note}[role=preprint]{#1}');

# Extra stuff
DefMacro('\blankaffiliation', '');
DefMacro('\checkindate',      '\today');

DefMacro('\received[]{}',  '\@add@frontmatter{ltx:date}[role=received]{#2}');
DefMacro('\revised[]{}',   '\@add@frontmatter{ltx:date}[role=revised]{#2}');
DefMacro('\accepted[]{}',  '\@add@frontmatter{ltx:date}[role=accepted]{#2}');
DefMacro('\published[]{}', '\@add@frontmatter{ltx:date}[role=published]{#2}');

#======================================================================
# 5. The body of the paper
#======================================================================

# 5.3
DefMacro('\widetext',    '');
DefMacro('\endwidetext', '');
# These are called obsolete, but I can't even find them in earlier RevTeX's!
DefMacro('\narrowtext',    '');
DefMacro('\endnarrowtext', '');
DefMacro('\mediumtext',    '');
DefMacro('\endmediumtext', '');

# 5.5
# Normally, we'd define the acknowledgements environment simply as:
# DefEnvironment('{acknowledgements}',
#              "<ltx:acknowledgements>#body</ltx:acknowledgements>");
# However, people seem to insist on "misusing" it, by just saying
# \acknowledgements... which actually "works".
# So, we just open it, and let it autoclose.
DefConstructor('\acknowledgments', "<ltx:acknowledgements name='#name'>",
  properties => sub { (name => Digest(T_CS('\acknowledgmentsname'))); });
DefConstructor('\endacknowledgments', "</ltx:acknowledgements>");
DefMacro('\acknowledgmentsname', 'Acknowledgements');
Let('\acknowledgements',    '\acknowledgments');
Let('\endacknowledgements', '\endacknowledgments');
Tag("ltx:acknowledgements", autoClose => 1);

# Extra stuff
DefMacro('\thesection', '\Roman{section}');    # Apparently the desired style.

DefMacro('\thepagegrid',       'one');
DefMacro('\onecolumngrid',     '');
DefMacro('\twocolumngrid',     '');
DefMacro('\restorecolumngrid', '');
DefPrimitive('\twocolumn', undef);
DefConstructor('\rotatebox{Number}{}', '#2');    # dummy defn, unless graphics loaded
DefMacro('\pagesofar', '');

# endnotes handled like footnotes
NewCounter('endnote');
DefConstructor('\endnote[]{}',
  "<ltx:note role='endnote' mark='#mark' xml:id='#id'>"
    . "#tags"
    . "#2"
    . "</ltx:note>",
  mode         => 'text', bounded => 1,
  beforeDigest => sub { reenterTextMode(1); neutralizeFont(); },
  properties   => sub {
    ($_[1]
      ? (mark => $_[1])
      : (RefStepCounter('endnote'),
        mark => DigestText(T_CS('\theendnote')))) });
DefConstructor('\endnotemark[]',
  "<ltx:note role='endnotemark' mark='#mark' xml:id='#id'>"
    . "#tags"
    . "</ltx:note>",
  mode       => 'text',
  properties => sub {
    ($_[1]
      ? (mark => $_[1])
      : (RefStepCounter('endnote'),
        mark => DigestText(T_CS('\theendnote')))) });
DefConstructor('\endnotetext[]{}',
  "<ltx:note role='endnotetext' mark='#mark' xml:id='#id'>#2</ltx:note>",
  mode       => 'text',
  properties => sub {
    ($_[1]
      ? (mark => $_[1])
      : (mark => Digest(T_CS("\\theendnote")))); });

#======================================================================
# 6. Math and Equations
#======================================================================

# 6.5
# recommends amsmath's {subequations}

# Extra stuff
Let('\case',      '\frac');
Let('\slantfrac', '\frac');
DefConstructor('\text{}', "<ltx:text _noautoclose='true'>#1</ltx:text>", mode => 'text', locked => 1);

# RevTeX3 (obsolete in RevTeX4)
DefConstructor('\bm{}',   '#1', bounded => 1, requireMath => 1, font => { forcebold => 1 });
DefConstructor('\bbox{}', '#1', bounded => 1, requireMath => 1, font => { forcebold => 1 });
DefConstructor('\pmb{}', '#1', bounded => 1, requireMath => 1,
  font => { forcebold => 1, family => 'blackboard',
    series => 'medium', shape => 'upright' });
DefMacro('\eqnum {}', '\lx@equation@settag{\edef\theequation{#2}\lx@make@tags{equation}}', locked => 1);

# Redefined in revtex3_support
DefMacro('\mathletters',    '');
DefMacro('\endmathletters', '');

#======================================================================
# 7. Footnotes
#======================================================================

#======================================================================
# 8. Citations and References
#======================================================================
DefMacro('\onlinecite', '\citealp');

Let('\textcite', '\citet');

# RevTeX3; Obsolete for RevTeX4 (but semi-implemented there)
# Should be a simple environment, but tends to be misused, so define separately
DefConstructor('\references',
  "<ltx:bibliography xml:id='#id' "
    . "bibstyle='#bibstyle' citestyle='#citestyle' sort='#sort'>"
    . "<ltx:title font='#titlefont' _force_font='true'>#title</ltx:title>"
    . "<ltx:biblist>",
  beforeDigest => sub {
    beforeDigestBibliography(); },
  afterDigest => sub { beginBibliography($_[1]); }, locked => 1);

DefConstructor('\endreferences', sub {
    $_[0]->maybeCloseElement('ltx:biblist');
    $_[0]->maybeCloseElement('ltx:bibliography'); },
  locked => 1);
# bibliography and biblist are already set as autoClose.

#======================================================================
# 9. Figures and Artwork
#======================================================================

#======================================================================
# 10. Tables
#======================================================================

# Used to put double rules before & after a tabular.
DefEnvironment('{ruledtabular}', '#body');

# No idea what this is really for, but this seems to be the jist of it.
DefEnvironment('{quasitable}', '#body',
  beforeDigest => sub {
    Let("\\begin{tabular}", "\\begin{longtable}");
    Let("\\end{tabular}",   "\\end{longtable}");
    Let("\\tabular",        "\\longtable");
    Let("\\endtabular",     "\\endlongtable"); });

DefMacro('\squeezetable', '');    #presentational

# Extra stuff
DefMacro('\toprule', '\hline\hline');
DefMacro('\colrule', '\hline');
DefMacro('\botrule', '\hline\hline');
DefMacro('\frstrut', '');
DefMacro('\lrstrut', '');
Let('\tableftsep',  '\tabcolsep');
Let('\tabmidsep',   '\tabcolsep');
Let('\tabrightsep', '\tabcolsep');

Let('\tablenote',     '\footnote');
Let('\tablenotemark', '\footnotemark');
Let('\tablenotetext', '\footnotetext');

# RevTeX3 (obsolete in RevTeX4)
Let('\tableline', '\colrule');

# This seems to be implied.
RawTeX('\newcolumntype{d}{D{.}{.}{-1}}');

#======================================================================
# 11. Placement of Figures, Tables and Other Floats
#======================================================================

DefPrimitive('\printfigures OptionalMatch:*', undef);
DefPrimitive('\printtables OptionalMatch:*',  undef);
DefMacro('\oneapage',      '');
DefMacro('\printendnotes', '');

#======================================================================
# 12. Rotating Floats
#======================================================================

# Rotates the page
DefEnvironment('{turnpage}', '#body');

#======================================================================
# 13. RevTeX 4 symbols and the revsymb package
#======================================================================

#======================================================================
# 14.  Other RevTeX 4 Features
#======================================================================

#======================================================================
# XX.  Extra stuff
#======================================================================

DefMacro('\MakeTextLowercase', '\lowercase');
DefMacro('\MakeTextUppercase', '\uppercase');
DefMacro('\NoCaseChange',      '');

# Macro & Control stuff.
#  Are these really intended for authors to use?
DefMacro('\absbox',           '');                                   #what does \newbox\absbox mean?
DefMacro('\addstuff{}{}',     '');
DefMacro('\appdef{}{}',       '');
DefMacro('\gappdef{}{}',      '');
DefMacro('\prepdef{}{}',      '');
DefMacro('\lineloop{}',       '');
DefMacro('\loopuntil{}',      '');
DefMacro('\loopwhile{}',      '');
DefMacro('\traceoutput',      '');
DefMacro('\tracingplain',     '');
DefMacro('\removephantombox', '');
DefMacro('\removestuff',      '');
DefMacro('\replacestuff{}{}', '');
DefMacro('\say[]',            '\typeout{<\noexpand#1=\meaning#1>}');
DefMacro('\saythe[]',         '\typeout{<\noexpand#1=\the#1>}');

# Various extra i18n stuff.
DefMacro('\copyrightname', '??');                # ?? is that ok? that is what the .sty says, but...
DefMacro('\journalname',   '??');
DefMacro('\lofname',       'List of Figures');
DefMacro('\lotname',       'List of Tables');
DefMacro('\notesname',     'Notes');
DefMacro('\numbername',    'number');
DefMacro('\ppname',        'pp');
DefMacro('\tocname',       'Contents');
DefMacro('\volumename',    'volume');

# Apparently some sort of document information?
DefMacro('\volumenumber{}', '#1');
DefMacro('\volumeyear{}',   '#1');
DefMacro('\issuenumber{}',  '#1');
DefMacro('\bibinfo{}{}',    '#2');
DefMacro('\eprint{}',       'eprint #1');
DefMacro('\eid{}',          '#1');
DefMacro('\startpage{}',    '\pageref{FirstPage}{#1}');
DefMacro('\endpage',        '\pageref{LastPage}{#1}');

# Other pointless stuff.
DefMacro('\flushing',          '');
DefMacro('\triggerpar',        '\par');
DefMacro('\fullinterlineskip', '');
DefRegister('\footbox'                 => Box());
DefRegister('\intertabularlinepenalty' => Number('100'));

# These are called obsolete, but I can't even find them in earlier RevTeX's!
DefMacro('\FL',      '');
DefMacro('\FR',      '');
DefMacro('\draft',   '');
DefMacro('\tighten', '');

#======================================================================
# The following really should only be defined for aps substyles
# which include pra, etc.
# I'll just define them all, and hope for no conflicts(?)

DefMacro('\ao',    'Appl.~Opt.~');
DefMacro('\ap',    'Appl.~Phys.~');
DefMacro('\apl',   'Appl.~Phys.~Lett.~');
DefMacro('\apj',   'Astrophys.~J.~');
DefMacro('\bell',  'Bell Syst.~Tech.~J.~');
DefMacro('\jqe',   'IEEE J.~Quantum Electron.~');
DefMacro('\assp',  'IEEE Trans.~Acoust.~Speech Signal Process.~');
DefMacro('\aprop', 'IEEE Trans.~Antennas Propag.~');
DefMacro('\mtt',   'IEEE Trans.~Microwave Theory Tech.~');
DefMacro('\iovs',  'Invest.~Opthalmol.~Vis.~Sci.~');
DefMacro('\jcp',   'J.~Chem.~Phys.~');
DefMacro('\jmo',   'J.~Mod.~Opt.~');
DefMacro('\josa',  'J.~Opt.~Soc.~Am.~');
DefMacro('\josaa', 'J.~Opt.~Soc.~Am.~A ');
DefMacro('\josab', 'J.~Opt.~Soc.~Am.~B ');
DefMacro('\jpp',   'J.~Phys.~(Paris) ');
DefMacro('\nat',   'Nature (London) ');
DefMacro('\oc',    'Opt.~Commun.~');
DefMacro('\ol',    'Opt.~Lett.~');
DefMacro('\pl',    'Phys.~Lett.~');
DefMacro('\pra',   'Phys.~Rev.~A ');
DefMacro('\prb',   'Phys.~Rev.~B ');
DefMacro('\prc',   'Phys.~Rev.~C ');
DefMacro('\prd',   'Phys.~Rev.~D ');
DefMacro('\pre',   'Phys.~Rev.~E ');
DefMacro('\prl',   'Phys.~Rev.~Lett.~');
DefMacro('\rmp',   'Rev.~Mod.~Phys.~');
DefMacro('\pspie', 'Proc.~Soc.~Photo-Opt.~Instrum.~Eng.~');
DefMacro('\sjqe',  'Sov.~J.~Quantum Elecron.~');
DefMacro('\vr',    'Vision Res.~');

#======================================================================

# Some internal macros used in arXiv
DefMacro('\@revmess{}{}', '\typeout{REVTeX #1: #2}');
DefMacroI('\@ptsize',      undef, '0');
DefMacroI('\ds@preprint',  undef, '\global\preprintstytrue \def\@ptsize{2}');
DefMacroI('\ds@twoside',   undef, '\@twosidetrue \@mparswitchtrue');
DefMacroI('\ds@draft',     undef, '\overfullrule 5\p@');
DefMacroI('\ds@amsfonts',  undef, '\@amsfontstrue');
DefMacroI('\ds@amssymb',   undef, '\@amssymbolstrue');
DefMacroI('\ds@titlepage', undef, '\@titlepagefalse');
DefMacroI('\ds@twocolumn', undef, '\@twocolumntrue');
DefMacroI('\ds@tighten',   undef, '\@tightenlinestrue');
DefMacroI('\ds@floats',    undef, '\@floatstrue');
DefMacroI('\ds@eqsecnum',  undef, '\global\secnumberstrue');

DefMacroI('\@journal', undef, 'pra');
DefMacroI('\ds@pra',   undef, '\def\@journal{pra}');
DefMacroI('\ds@prb',   undef, '\def\@journal{prb}');
DefMacroI('\ds@prc',   undef, '\def\@journal{prc}');
DefMacroI('\ds@prd',   undef, '\def\@journal{prd}');
DefMacroI('\ds@pre',   undef, '\def\@journal{pre}');
DefMacroI('\ds@prl',   undef, '\def\@journal{prl}');
DefMacroI('\ds@josaa', undef, '\def\@journal{josaa}');
DefMacroI('\ds@josab', undef, '\def\@journal{josab}');
DefMacroI('\ds@aplop', undef, '\def\@journal{aplop}');

Let('\ds@manuscript', '\ds@preprint');

RawTeX(<<'EOL');
\@namedef{ds@11pt}{\def\@ptsize{1}}
\@namedef{ds@12pt}{\def\@ptsize{2}}
\newif\ifpreprintsty \global\preprintstyfalse
\@namedef{ds@aps}{\def\@society{aps}}
\@namedef{ds@osa}{\def\@society{osa}}

\newif\if@amsfonts  \@amsfontsfalse
\newif\if@amssymbols  \@amssymbolsfalse
\newif\if@titlepage  \@titlepagefalse
\newif\if@tightenlines \@tightenlinesfalse
\newif\if@floats \@floatsfalse
\newif\ifsecnumbers \global\secnumbersfalse
\newif\if@amsfonts  \@amsfontsfalse
\newif\if@amssymbols  \@amssymbolsfalse
\newif\if@titlepage  \@titlepagefalse
\newif\if@tightenlines \@tightenlinesfalse
\newif\if@floats \@floatsfalse
\newif\ifsecnumbers \global\secnumbersfalse
EOL

DefMacroI('\ds@amsfonts',  undef, '\@amsfontstrue');
DefMacroI('\ds@amssymb',   undef, '\@amssymbolstrue');
DefMacroI('\ds@titlepage', undef, '\@titlepagefalse');
DefMacroI('\ds@twocolumn', undef, '\@twocolumntrue');
DefMacroI('\ds@tighten',   undef, '\@tightenlinestrue');
DefMacroI('\ds@floats',    undef, '\@floatstrue');
DefMacroI('\ds@eqsecnum',  undef, '\global\secnumberstrue');

DefMacro('\replace@command{}{}',     '\global\let#1#2 #1');
DefMacro('\replace@environment{}{}', '\glet@environment{#1}{#2}\@nameuse{#1}');
DefMacro('\glet@environment{}{}', '\global\expandafter\let'
    . '\csname#1\expandafter\endcsname\csname#2\endcsname'
    . '\global\expandafter\let'
    . '\csname end#1\expandafter\endcsname\csname end#2\endcsname');
#======================================================================

1;
