| 1 | # /=====================================================================\ # | ||
| 2 | # | LaTeXML::Package | # | ||
| 3 | # | Exports of Defining forms for Package writers | # | ||
| 4 | # |=====================================================================| # | ||
| 5 | # | Part of LaTeXML: | # | ||
| 6 | # | Public domain software, produced as part of work done by the | # | ||
| 7 | # | United States Government & not subject to copyright in the US. | # | ||
| 8 | # |---------------------------------------------------------------------| # | ||
| 9 | # | Bruce Miller <bruce.miller@nist.gov> #_# | # | ||
| 10 | # | http://dlmf.nist.gov/LaTeXML/ (o o) | # | ||
| 11 | # \=========================================================ooo==U==ooo=/ # | ||
| 12 | |||
| 13 | package LaTeXML::Package; | ||
| 14 | 2 | ▶ | use strict; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 15 | 2 | ▶ | use warnings; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 16 | 2 | ▶ | use Exporter; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 17 | 2 | ▶ | use LaTeXML::Global; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 18 | 2 | ▶ | use LaTeXML::Common::Object; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 19 | 2 | ▶ | use LaTeXML::Common::Error; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 20 | 2 | ▶ | use LaTeXML::Core::Token; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 21 | 2 | ▶ | use LaTeXML::Core::Tokens; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 22 | 2 | ▶ | use LaTeXML::Core::Box; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 23 | 2 | ▶ | use LaTeXML::Core::List; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 24 | 2 | ▶ | use LaTeXML::Core::Mouth::Binding; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 25 | 2 | ▶ | use LaTeXML::Core::Definition; |
|
Subroutine
BEGIN: called CC=1 SCAR=2.6
| |||
| 26 | use LaTeXML::Core::Parameters; | ||
| 27 | use LaTeXML::Common::Number; | ||
| 28 | use LaTeXML::Common::Float; | ||
| 29 | use LaTeXML::Common::Dimension; | ||
| 30 | use LaTeXML::Common::Glue; | ||
| 31 | use LaTeXML::Core::MuDimension; | ||
| 32 | use LaTeXML::Core::MuGlue; | ||
| 33 | # Extra objects typically used in Bindings | ||
| 34 | use LaTeXML::Core::Alignment; | ||
| 35 | use LaTeXML::Core::Array; | ||
| 36 | use LaTeXML::Core::KeyVal; | ||
| 37 | use LaTeXML::Core::KeyVals; | ||
| 38 | use LaTeXML::Core::Pair; | ||
| 39 | use LaTeXML::Core::PairList; | ||
| 40 | use LaTeXML::Common::Color; | ||
| 41 | use LaTeXML::Common::Color::rgb; | ||
| 42 | # Utitlities | ||
| 43 | use LaTeXML::Util::Pathname; | ||
| 44 | use LaTeXML::Util::WWW; | ||
| 45 | use LaTeXML::Common::XML; | ||
| 46 | use LaTeXML::Core::Rewrite; | ||
| 47 | use LaTeXML::Util::Radix; | ||
| 48 | use File::Which; | ||
| 49 | use Unicode::Normalize; | ||
| 50 | use Text::Balanced; | ||
| 51 | use Text::Unidecode; | ||
| 52 | use base qw(Exporter); | ||
| 53 | our @EXPORT = (qw(&DefAutoload &DefExpandable | ||
| 54 | &DefMacro &DefMacroI | ||
| 55 | &DefConditional &DefConditionalI &IfCondition &SetCondition | ||
| 56 | &DefPrimitive &DefPrimitiveI | ||
| 57 | &DefRegister &DefRegisterI &LookupRegister &AssignRegister &LookupDimension | ||
| 58 | &DefConstructor &DefConstructorI | ||
| 59 | &dualize_arglist &createXMRefs | ||
| 60 | &DefMath &DefMathI &DefEnvironment &DefEnvironmentI | ||
| 61 | &convertLaTeXArgs), | ||
| 62 | |||
| 63 | # Class, Package and File loading. | ||
| 64 | qw(&Input &InputContent &InputDefinitions &RequirePackage &LoadClass &LoadPool &FindFile | ||
| 65 | &DeclareOption &PassOptions &ProcessOptions &ExecuteOptions | ||
| 66 | &AddToMacro &AtBeginDocument &AtEndDocument), | ||
| 67 | |||
| 68 | # Counter support | ||
| 69 | qw(&NewCounter &CounterValue &SetCounter &AddToCounter &StepCounter &RefStepCounter &RefStepID &ResetCounter | ||
| 70 | &GenerateID &AfterAssignment), | ||
| 71 | |||
| 72 | # Document Model | ||
| 73 | qw(&Tag &DocType &RelaxNGSchema &RegisterNamespace &RegisterDocumentNamespace), | ||
| 74 | |||
| 75 | # Document Rewriting | ||
| 76 | qw(&DefRewrite &DefMathRewrite | ||
| 77 | &DefLigature &DefMathLigature), | ||
| 78 | |||
| 79 | # Mid-level support for writing definitions. | ||
| 80 | qw(&Expand &Invocation &Digest &DigestText &DigestIf &DigestLiteral | ||
| 81 | &RawTeX &Let &StartSemiverbatim &EndSemiverbatim | ||
| 82 | &Tokenize &TokenizeInternal), | ||
| 83 | |||
| 84 | # Font encoding | ||
| 85 | qw(&DeclareFontMap &FontDecode &FontDecodeString &LoadFontMap), | ||
| 86 | |||
| 87 | # Color | ||
| 88 | qw(&DefColor &DefColorModel &LookupColor), | ||
| 89 | |||
| 90 | # Support for structured/argument readers | ||
| 91 | qw(&ReadParameters &DefParameterType &DefColumnType), | ||
| 92 | |||
| 93 | # Access to State | ||
| 94 | qw(&LookupValue &AssignValue | ||
| 95 | &PushValue &PopValue &UnshiftValue &ShiftValue | ||
| 96 | &LookupMapping &AssignMapping &LookupMappingKeys | ||
| 97 | &LookupCatcode &AssignCatcode | ||
| 98 | &LookupMeaning &LookupDefinition &InstallDefinition &XEquals &IsDefined | ||
| 99 | &LookupMathcode &AssignMathcode | ||
| 100 | &LookupSFcode &AssignSFcode | ||
| 101 | &LookupLCcode &AssignLCcode | ||
| 102 | &LookupUCcode &AssignUCcode | ||
| 103 | &LookupDelcode &AssignDelcode | ||
| 104 | ), | ||
| 105 | |||
| 106 | # Random low-level token or string operations. | ||
| 107 | qw(&CleanID &CleanLabel &CleanIndexKey &CleanClassName &CleanBibKey &NormalizeBibKey &CleanURL | ||
| 108 | &ComposeURL | ||
| 109 | &UTF | ||
| 110 | &roman &Roman), | ||
| 111 | # Math & font state. | ||
| 112 | qw(&MergeFont), | ||
| 113 | |||
| 114 | qw(&CheckOptions), | ||
| 115 | # Resources | ||
| 116 | qw(&RequireResource &ProcessPendingResources), | ||
| 117 | |||
| 118 | @LaTeXML::Global::EXPORT, | ||
| 119 | # And export those things exported by these Core & Common packages. | ||
| 120 | @LaTeXML::Common::Object::EXPORT, | ||
| 121 | @LaTeXML::Common::Error::EXPORT, | ||
| 122 | @LaTeXML::Core::Token::EXPORT, | ||
| 123 | @LaTeXML::Core::Tokens::EXPORT, | ||
| 124 | @LaTeXML::Core::Box::EXPORT, | ||
| 125 | @LaTeXML::Core::List::EXPORT, | ||
| 126 | @LaTeXML::Common::Number::EXPORT, | ||
| 127 | @LaTeXML::Common::Float::EXPORT, | ||
| 128 | @LaTeXML::Common::Dimension::EXPORT, | ||
| 129 | @LaTeXML::Common::Glue::EXPORT, | ||
| 130 | @LaTeXML::Core::KeyVal::EXPORT, | ||
| 131 | @LaTeXML::Core::KeyVals::EXPORT, | ||
| 132 | @LaTeXML::Core::MuDimension::EXPORT, | ||
| 133 | @LaTeXML::Core::MuGlue::EXPORT, | ||
| 134 | @LaTeXML::Core::Pair::EXPORT, | ||
| 135 | @LaTeXML::Core::PairList::EXPORT, | ||
| 136 | @LaTeXML::Common::Color::EXPORT, | ||
| 137 | @LaTeXML::Core::Alignment::EXPORT, | ||
| 138 | @LaTeXML::Common::XML::EXPORT, | ||
| 139 | @LaTeXML::Util::Radix::EXPORT, | ||
| 140 | ); | ||
| 141 | |||
| 142 | #********************************************************************** | ||
| 143 | # Initially, I thought LaTeXML Packages should try to be like perl modules: | ||
| 144 | # once loaded, you didn't need to re-load them, only `initialize' them to | ||
| 145 | # install their definitions into the current stomach. I tried to achieve | ||
| 146 | # that through various package tricks. | ||
| 147 | # But ultimately, most of a package _is_ installing defns in the stomach, | ||
| 148 | # and it's probably better to allow a more TeX-like evaluation of definitions | ||
| 149 | # in order, so \let and such work as expected. | ||
| 150 | # So, it got simpler! | ||
| 151 | # Still, it would be nice if there were `compiled' forms of .ltxml files! | ||
| 152 | #********************************************************************** | ||
| 153 | |||
| 154 | sub UTF { | ||
| 155 | my ($code) = @_; | ||
| 156 | return pack('U', $code); } | ||
| 157 | |||
| 158 | sub coerceCS { | ||
| 159 | my ($cs) = @_; | ||
| 160 | $cs = T_CS($cs) unless ref $cs; | ||
| 161 | $cs = T_CS(ToString($cs)) unless ref $cs eq 'LaTeXML::Core::Token'; | ||
| 162 | return $cs; } | ||
| 163 | |||
| 164 | sub parsePrototype { | ||
| 165 | my ($proto) = @_; | ||
| 166 | my $oproto = $proto; | ||
| 167 | if (ref $proto eq 'LaTeXML::Core::Token') { | ||
| 168 | return ($proto, undef); } | ||
| 169 | my $cs; | ||
| 170 | if ($proto =~ s/^\\csname\s+(.*)\\endcsname//) { | ||
| 171 | $cs = T_CS('\\' . $1); } | ||
| 172 | elsif ($proto =~ s/^(\\[a-zA-Z@]+)//) { # Match a cs | ||
| 173 | $cs = T_CS($1); } | ||
| 174 | elsif ($proto =~ s/^(\\.)//) { # Match a single char cs, env name,... | ||
| 175 | $cs = T_CS($1); } | ||
| 176 | elsif ($proto =~ s/^(.)//) { # Match an active char | ||
| 177 | ($cs) = TokenizeInternal($1)->unlist; } | ||
| 178 | else { | ||
| 179 | Fatal('misdefined', $proto, $STATE->getStomach, | ||
| 180 | "Definition prototype doesn't have proper control sequence: \"$proto\""); } | ||
| 181 | $proto =~ s/^\s*//; | ||
| 182 | #### return ($cs, parseParameters($proto, $cs)); } | ||
| 183 | return ($cs, $proto); } | ||
| 184 | |||
| 185 | # If a ReadFoo function exists (accessible from LaTeXML::Package::Pool), | ||
| 186 | # then the parameter spec: | ||
| 187 | # Foo : will invoke it and use the result for the corresponding argument. | ||
| 188 | # it will complain if ReadFoo returns undef. | ||
| 189 | # SkipFoo : will invoke SkipFoo, if it is defined, else ReadFoo, | ||
| 190 | # but in either case, will ignore the result | ||
| 191 | # OptionalFoo : will invoke ReadOptionalFoo if defined, else ReadFoo | ||
| 192 | # but will not complain if the reader returns undef. | ||
| 193 | # In all cases, there is the provision to supply an additional parameter to the reader: | ||
| 194 | # "Foo:stuff" effectively invokes ReadFoo(Tokenize('stuff')) | ||
| 195 | # similarly for the other variants. What the 'stuff" means depends on the type. | ||
| 196 | sub parseParameters { | ||
| 197 | my ($proto, $for) = @_; | ||
| 198 | my $p = $proto; | ||
| 199 | my @params = (); | ||
| 200 | while ($p) { | ||
| 201 | # Handle possibly nested cases, such as {Number} | ||
| 202 | if ($p =~ s/^(\{([^\}]*)\})\s*//) { | ||
| 203 | my ($spec, $inner_spec) = ($1, $2); | ||
| 204 | my $inner = ($inner_spec ? parseParameters($inner_spec, $for) : undef); | ||
| 205 | # If single inner spec is optional, make whole thing optional | ||
| 206 | my $opt = $inner && (scalar(@$inner) == 1) && $$inner[0]{optional}; | ||
| 207 | push(@params, LaTeXML::Core::Parameter->new('Plain', $spec, extra => [$inner], | ||
| 208 | optional => $opt)); } | ||
| 209 | elsif ($p =~ s/^(\[([^\]]*)\])\s*//) { # Ditto for Optional | ||
| 210 | my ($spec, $inner_spec) = ($1, $2); | ||
| 211 | if ($inner_spec =~ /^Default:(.*)$/) { | ||
| 212 | push(@params, LaTeXML::Core::Parameter->new('Optional', $spec, | ||
| 213 | extra => [TokenizeInternal($1), undef])); } | ||
| 214 | elsif ($inner_spec) { | ||
| 215 | push(@params, LaTeXML::Core::Parameter->new('Optional', $spec, | ||
| 216 | extra => [undef, parseParameters($inner_spec, $for)])); } | ||
| 217 | else { | ||
| 218 | push(@params, LaTeXML::Core::Parameter->new('Optional', $spec)); } } | ||
| 219 | elsif ($p =~ s/^((\w*)(:([^\s\{\[]*))?)\s*//) { | ||
| 220 | my ($spec, $type, $extra) = ($1, $2, $4); | ||
| 221 | my @extra = map { TokenizeInternal($_) } split('\|', $extra || ''); | ||
| 222 | push(@params, LaTeXML::Core::Parameter->new($type, $spec, extra => [@extra])); } | ||
| 223 | else { | ||
| 224 | Fatal('misdefined', $for, undef, "Unrecognized parameter specification at \"$proto\""); } } | ||
| 225 | return (@params ? LaTeXML::Core::Parameters->new(@params) : undef); } | ||
| 226 | |||
| 227 | # Convert a LaTeX-style argument spec to our Package form. | ||
| 228 | # Ie. given $nargs and $optional, being the two optional arguments to | ||
| 229 | # something like \newcommand, convert it to the form we use | ||
| 230 | sub convertLaTeXArgs { | ||
| 231 | my ($nargs, $optional) = @_; | ||
| 232 | $nargs = $nargs->toString if ref $nargs; | ||
| 233 | $nargs = 0 unless $nargs; | ||
| 234 | my @params = (); | ||
| 235 | if ($optional) { | ||
| 236 | push(@params, LaTeXML::Core::Parameter->new('Optional', | ||
| 237 | "[Default:" . UnTeX($optional) . "]", | ||
| 238 | extra => [$optional, undef])); | ||
| 239 | $nargs--; } | ||
| 240 | push(@params, map { LaTeXML::Core::Parameter->new('Plain', '{}') } 1 .. $nargs); | ||
| 241 | return (@params ? LaTeXML::Core::Parameters->new(@params) : undef); } | ||
| 242 | |||
| 243 | #====================================================================== | ||
| 244 | # Convenience functions for writing definitions. | ||
| 245 | #====================================================================== | ||
| 246 | |||
| 247 | sub LookupValue { | ||
| 248 | my ($name) = @_; | ||
| 249 | return $STATE->lookupValue($name); } | ||
| 250 | |||
| 251 | sub AssignValue { | ||
| 252 | my ($name, $value, $scope) = @_; | ||
| 253 | $STATE->assignValue($name, $value, $scope); return; } | ||
| 254 | |||
| 255 | sub PushValue { | ||
| 256 | my ($name, @values) = @_; | ||
| 257 | $STATE->pushValue($name, @values); | ||
| 258 | return; } | ||
| 259 | |||
| 260 | sub PopValue { | ||
| 261 | my ($name) = @_; | ||
| 262 | return $STATE->popValue($name); } | ||
| 263 | |||
| 264 | sub UnshiftValue { | ||
| 265 | my ($name, @values) = @_; | ||
| 266 | $STATE->unshiftValue($name, @values); | ||
| 267 | return; } | ||
| 268 | |||
| 269 | sub ShiftValue { | ||
| 270 | my ($name) = @_; | ||
| 271 | return $STATE->shiftValue($name); } | ||
| 272 | |||
| 273 | sub LookupMapping { | ||
| 274 | my ($map, $key) = @_; | ||
| 275 | return $STATE->lookupMapping($map, $key); } | ||
| 276 | |||
| 277 | sub AssignMapping { | ||
| 278 | my ($map, $key, $value) = @_; | ||
| 279 | return $STATE->assignMapping($map, $key, $value); } | ||
| 280 | |||
| 281 | sub LookupMappingKeys { | ||
| 282 | my ($map) = @_; | ||
| 283 | return $STATE->lookupMappingKeys($map); } | ||
| 284 | |||
| 285 | sub LookupCatcode { | ||
| 286 | my ($char) = @_; | ||
| 287 | return $STATE->lookupCatcode($char); } | ||
| 288 | |||
| 289 | sub AssignCatcode { | ||
| 290 | my ($char, $catcode, $scope) = @_; | ||
| 291 | $STATE->assignCatcode($char, $catcode, $scope); | ||
| 292 | return; } | ||
| 293 | |||
| 294 | sub LookupMeaning { | ||
| 295 | my ($name) = @_; | ||
| 296 | return $STATE->lookupMeaning($name); } | ||
| 297 | |||
| 298 | sub LookupDefinition { | ||
| 299 | my ($name) = @_; | ||
| 300 | return $STATE->lookupDefinition($name); } | ||
| 301 | |||
| 302 | sub InstallDefinition { | ||
| 303 | my ($name, $definition, $scope) = @_; | ||
| 304 | $STATE->installDefinition($name, $definition, $scope); | ||
| 305 | return } | ||
| 306 | |||
| 307 | sub XEquals { | ||
| 308 | my ($token1, $token2) = @_; | ||
| 309 | my $def1 = LookupMeaning($token1); # token, definition object or undef | ||
| 310 | my $def2 = LookupMeaning($token2); # ditto | ||
| 311 | if (defined $def1 != defined $def2) { # False, if only one has 'meaning' | ||
| 312 | return; } | ||
| 313 | elsif (!defined $def1 && !defined $def2) { # true if both undefined | ||
| 314 | return 1; } | ||
| 315 | elsif ($def1->equals($def2)) { # If both have defns, must be same defn! | ||
| 316 | return 1; } | ||
| 317 | return; } | ||
| 318 | |||
| 319 | # Is defined in the LaTeX-y sense of also not being let to \relax. | ||
| 320 | sub IsDefined { | ||
| 321 | my ($name) = @_; | ||
| 322 | my $cs = (ref $name ? $name : T_CS($name)); | ||
| 323 | my $meaning = $STATE->lookupMeaning($cs); | ||
| 324 | return $meaning | ||
| 325 | && ($meaning->isa('LaTeXML::Core::Token') || ($meaning->getCSName ne '\relax')) | ||
| 326 | && $meaning; } | ||
| 327 | |||
| 328 | sub LookupMathcode { | ||
| 329 | my ($char) = @_; | ||
| 330 | return $STATE->lookupMathcode($char); } | ||
| 331 | |||
| 332 | sub AssignMathcode { | ||
| 333 | my ($char, $mathcode, $scope) = @_; | ||
| 334 | $STATE->assignMathcode($char, $mathcode, $scope); | ||
| 335 | return; } | ||
| 336 | |||
| 337 | sub LookupSFcode { | ||
| 338 | my ($char) = @_; | ||
| 339 | return $STATE->lookupSFcode($char); } | ||
| 340 | |||
| 341 | sub AssignSFcode { | ||
| 342 | my ($char, $sfcode, $scope) = @_; | ||
| 343 | $STATE->assignSFcode($char, $sfcode, $scope); | ||
| 344 | return; } | ||
| 345 | |||
| 346 | sub LookupLCcode { | ||
| 347 | my ($char) = @_; | ||
| 348 | return $STATE->lookupLCcode($char); } | ||
| 349 | |||
| 350 | sub AssignLCcode { | ||
| 351 | my ($char, $lccode, $scope) = @_; | ||
| 352 | $STATE->assignLCcode($char, $lccode, $scope); | ||
| 353 | return; } | ||
| 354 | |||
| 355 | sub LookupUCcode { | ||
| 356 | my ($char) = @_; | ||
| 357 | return $STATE->lookupUCcode($char); } | ||
| 358 | |||
| 359 | sub AssignUCcode { | ||
| 360 | my ($char, $uccode, $scope) = @_; | ||
| 361 | $STATE->assignUCcode($char, $uccode, $scope); | ||
| 362 | return; } | ||
| 363 | |||
| 364 | sub LookupDelcode { | ||
| 365 | my ($char) = @_; | ||
| 366 | return $STATE->lookupDelcode($char); } | ||
| 367 | |||
| 368 | sub AssignDelcode { | ||
| 369 | my ($char, $delcode, $scope) = @_; | ||
| 370 | $STATE->assignDelcode($char, $delcode, $scope); | ||
| 371 | return; } | ||
| 372 | |||
| 373 | sub Let { | ||
| 374 | my ($token1, $token2, $scope) = @_; | ||
| 375 | # If strings are given, assume CS tokens (most common case) | ||
| 376 | $token1 = T_CS($token1) unless ref $token1; | ||
| 377 | $token2 = T_CS($token2) unless ref $token2; | ||
| 378 | $STATE->assignMeaning($token1, $STATE->lookupMeaning($token2), $scope); | ||
| 379 | AfterAssignment(); | ||
| 380 | return; } | ||
| 381 | |||
| 382 | sub Digest { | ||
| 383 | my (@stuff) = @_; | ||
| 384 | return $STATE->getStomach->digest(Tokens(map { (ref $_ ? $_ : TokenizeInternal($_)) } @stuff)); } | ||
| 385 | |||
| 386 | sub DigestText { | ||
| 387 | my (@stuff) = @_; | ||
| 388 | my $stomach = $STATE->getStomach; | ||
| 389 | $stomach->beginMode('text'); | ||
| 390 | my $result = $stomach->digest(Tokens(map { (ref $_ ? $_ : TokenizeInternal($_)) } @stuff)); | ||
| 391 | $stomach->endMode('text'); | ||
| 392 | return $result; } | ||
| 393 | |||
| 394 | # probably need to export this, as well? | ||
| 395 | sub DigestLiteral { | ||
| 396 | my (@stuff) = @_; | ||
| 397 | # Perhaps should do StartSemiverbatim, but is it safe to push a frame? (we might cover over valid changes of state!) | ||
| 398 | my $stomach = $STATE->getStomach; | ||
| 399 | $stomach->beginMode('text'); | ||
| 400 | my $font = LookupValue('font'); | ||
| 401 | AssignValue(font => $font->merge(encoding => 'ASCII'), 'local'); # try to stay as ASCII as possible | ||
| 402 | my $value = $STATE->getStomach->digest(Tokens(map { (ref $_ ? $_ : Tokenize($_)) } @stuff)); | ||
| 403 | AssignValue(font => $font); | ||
| 404 | $stomach->endMode('text'); | ||
| 405 | return $value; } | ||
| 406 | |||
| 407 | sub DigestIf { | ||
| 408 | my ($token) = @_; | ||
| 409 | $token = T_CS($token) unless ref $token; | ||
| 410 | if (my $defn = $STATE->lookupDefinition($token)) { | ||
| 411 | return $STATE->getStomach->digest($token); } | ||
| 412 | else { | ||
| 413 | return; } } | ||
| 414 | |||
| 415 | sub ReadParameters { | ||
| 416 | my ($gullet, $spec) = @_; | ||
| 417 | my $for = T_OTHER("Anonymous"); | ||
| 418 | my $parm = parseParameters($spec, $for); | ||
| 419 | return ($parm ? $parm->readArguments($gullet, $for) : ()); } | ||
| 420 | |||
| 421 | # Merge the current font with the style specifications | ||
| 422 | sub MergeFont { | ||
| 423 | my (@kv) = @_; | ||
| 424 | AssignValue(font => LookupValue('font')->merge(@kv), 'local'); | ||
| 425 | return; } | ||
| 426 | |||
| 427 | # Dumb place for this, but where else... | ||
| 428 | # The TeX way! (bah!! hint: try a large number) | ||
| 429 | my @rmletters = ('i', 'v', 'x', 'l', 'c', 'd', 'm'); # [CONSTANT] | ||
| 430 | |||
| 431 | sub roman_aux { | ||
| 432 | my ($n) = @_; | ||
| 433 | my $div = 1000; | ||
| 434 | my $s = ($n > $div ? ('m' x int($n / $div)) : ''); | ||
| 435 | my $p = 4; | ||
| 436 | while ($n %= $div) { | ||
| 437 | $div /= 10; | ||
| 438 | my $d = int($n / $div); | ||
| 439 | if ($d % 5 == 4) { $s .= $rmletters[$p]; $d++; } | ||
| 440 | if ($d > 4) { $s .= $rmletters[$p + int($d / 5)]; $d %= 5; } | ||
| 441 | if ($d) { $s .= $rmletters[$p] x $d; } | ||
| 442 | $p -= 2; } | ||
| 443 | return $s; } | ||
| 444 | |||
| 445 | # Convert the number to lower case roman numerals, returning a list of LaTeXML::Core::Token | ||
| 446 | sub roman { | ||
| 447 | my (@stuff) = @_; | ||
| 448 | return ExplodeText(roman_aux(@stuff)); } | ||
| 449 | # Convert the number to upper case roman numerals, returning a list of LaTeXML::Core::Token | ||
| 450 | sub Roman { | ||
| 451 | my (@stuff) = @_; | ||
| 452 | return ExplodeText(uc(roman_aux(@stuff))); } | ||
| 453 | |||
| 454 | #====================================================================== | ||
| 455 | # Cleaners | ||
| 456 | #====================================================================== | ||
| 457 | |||
| 458 | sub CleanID { | ||
| 459 | my ($key) = @_; | ||
| 460 | $key = ToString($key); | ||
| 461 | $key =~ s/^\s+//s; $key =~ s/\s+$//s; # Trim leading/trailing, in any case | ||
| 462 | $key =~ s/\s//sg; | ||
| 463 | # Remove common idiom: | ||
| 464 | $key =~ s/\$\{\}\^\{(.*?)\}\$/$1/g; | ||
| 465 | # transform some forbidden chars | ||
| 466 | $key =~ s/:/../g; # No colons! | ||
| 467 | $key =~ s/@/-at-/g; | ||
| 468 | $key =~ s/\*/-star-/g; | ||
| 469 | $key =~ s/\$/-dollar-/g; | ||
| 470 | $key =~ s/,/-comma-/g; | ||
| 471 | $key =~ s/%/-pct-/g; | ||
| 472 | $key =~ s/&/-amp-/g; | ||
| 473 | $key = unidecode($key); | ||
| 474 | $key =~ s/[^\w\_\-.]//g; # remove everything else. | ||
| 475 | |||
| 476 | if ($key =~ /^[^a-zA-Z\_]/) { | ||
| 477 | # in case we are missing a prefix and have a leading ., default to X | ||
| 478 | $key = "X$key"; | ||
| 479 | } | ||
| 480 | return $key; } | ||
| 481 | |||
| 482 | sub CleanLabel { | ||
| 483 | my ($label, $prefix) = @_; | ||
| 484 | my $key = ToString($label); | ||
| 485 | $key =~ s/^\s+//s; $key =~ s/\s+$//s; # Trim leading/trailing, in any case | ||
| 486 | $key =~ s/\s+/_/sg; | ||
| 487 | return ($prefix || "LABEL") . ":" . $key; } | ||
| 488 | |||
| 489 | sub CleanIndexKey { | ||
| 490 | my ($key) = @_; | ||
| 491 | $key = ToString($key); | ||
| 492 | $key =~ s/^\s+//s; $key =~ s/\s+$//s; # Trim leading/trailing, in any case | ||
| 493 | # We don't want accented chars (do we?) but we need to decompose the accents! | ||
| 494 | ## No, leave in the unicode at this point (strip them later) | ||
| 495 | ## $key = NFD($key); | ||
| 496 | ## $key =~ s/[^a-zA-Z0-9]//g; | ||
| 497 | $key = NFC($key); # just to be safe(?) | ||
| 498 | ## Shouldn't be case insensitive? | ||
| 499 | ## $key =~ tr|A-Z|a-z|; | ||
| 500 | $key =~ s/[\.\,\;]+$//; # Remove trailing punctuation | ||
| 501 | return $key; } | ||
| 502 | |||
| 503 | sub CleanClassName { | ||
| 504 | my ($key) = @_; | ||
| 505 | $key = ToString($key); | ||
| 506 | $key =~ s/^\s+//s; $key =~ s/\s+$//s; # Trim leading/trailing, in any case | ||
| 507 | # We don't want accented chars (do we?) but we need to decompose the accents! | ||
| 508 | $key = NFD($key); | ||
| 509 | $key =~ s/[^a-zA-Z0-9]//g; | ||
| 510 | $key = NFC($key); # just to be safe(?) | ||
| 511 | return $key; } | ||
| 512 | |||
| 513 | sub CleanBibKey { | ||
| 514 | my ($key) = @_; | ||
| 515 | $key = ToString($key); # Originally lc() here, but let's preserve case till Postproc. | ||
| 516 | $key =~ s/^\s+//s; $key =~ s/\s+$//s; # Trim leading/trailing, in any case | ||
| 517 | $key =~ s/\s//sg; | ||
| 518 | return $key; } | ||
| 519 | |||
| 520 | # Return the bibkey in a form to ACTUALLY lookup. | ||
| 521 | # Usually use CleanBibKey to preserve key in the original form (case) | ||
| 522 | sub NormalizeBibKey { | ||
| 523 | my ($key) = @_; | ||
| 524 | return ($key ? lc(CleanBibKey($key)) : undef); } | ||
| 525 | |||
| 526 | sub CleanURL { | ||
| 527 | my ($url) = @_; | ||
| 528 | $url = ToString($url); | ||
| 529 | $url =~ s/^\s+//s; $url =~ s/\s+$//s; # Trim leading/trailing, in any case | ||
| 530 | $url =~ s/\\~\{\}/~/g; | ||
| 531 | return $url; } | ||
| 532 | |||
| 533 | sub ComposeURL { | ||
| 534 | my ($base, $url, $fragid) = @_; | ||
| 535 | $base = ToString($base); $base =~ s/\/$// if $base; # remove trailing / | ||
| 536 | $url = ToString($url); | ||
| 537 | $fragid = ToString($fragid); | ||
| 538 | return CleanURL(join('', | ||
| 539 | ($base ? | ||
| 540 | ($url =~ /^\w+:/ ? '' # already has protocol, so is absolute url | ||
| 541 | : $base . ($url =~ /^\// ? '' : '/')) # else start w/base, possibly / | ||
| 542 | : ''), | ||
| 543 | $url, | ||
| 544 | ($fragid ? '#' . CleanID($fragid) : ''))); } | ||
| 545 | |||
| 546 | #====================================================================== | ||
| 547 | # Defining new Control-sequence Parameter types. | ||
| 548 | #====================================================================== | ||
| 549 | |||
| 550 | my $parameter_options = { # [CONSTANT] | ||
| 551 | nargs => 1, reversion => 1, optional => 1, novalue => 1, | ||
| 552 | beforeDigest => 1, afterDigest => 1, | ||
| 553 | semiverbatim => 1, undigested => 1 }; | ||
| 554 | |||
| 555 | sub DefParameterType { | ||
| 556 | my ($type, $reader, %options) = @_; | ||
| 557 | CheckOptions("DefParameterType $type", $parameter_options, %options); | ||
| 558 | AssignMapping('PARAMETER_TYPES', $type, { reader => $reader, %options }); | ||
| 559 | return; } | ||
| 560 | |||
| 561 | sub DefColumnType { | ||
| 562 | my ($proto, $expansion) = @_; | ||
| 563 | if ($proto =~ s/^(.)//) { | ||
| 564 | my $char = $1; | ||
| 565 | $proto =~ s/^\s*//; | ||
| 566 | # Defer | ||
| 567 | # $proto = parseParameters($proto, $char); | ||
| 568 | # $expansion = TokenizeInternal($expansion) unless ref $expansion; | ||
| 569 | DefMacroI(T_CS('\NC@rewrite@' . $char), $proto, $expansion); } | ||
| 570 | else { | ||
| 571 | Warn('expected', 'character', undef, "Expected Column specifier"); } | ||
| 572 | return; } | ||
| 573 | |||
| 574 | #====================================================================== | ||
| 575 | # Counters | ||
| 576 | #====================================================================== | ||
| 577 | # This is modelled on LaTeX's counter mechanisms, but since it also | ||
| 578 | # provides support for ID's, even where there is no visible reference number, | ||
| 579 | # it is defined in genera. | ||
| 580 | # These id's should be both unique, and parallel the visible reference numbers | ||
| 581 | # (as much as possible). Also, for consistency, we add id's to unnumbered | ||
| 582 | # document elements (eg from \section*); this requires an additional counter | ||
| 583 | # (eg. UNsection) and mechanisms to track it. | ||
| 584 | |||
| 585 | # Defines a new counter named $ctr. | ||
| 586 | # If $within is defined, $ctr will be reset whenever $within is incremented. | ||
| 587 | # Keywords: | ||
| 588 | # idprefix : specifies a prefix to be used in formatting ID's for document structure elements | ||
| 589 | # counted by this counter. Ie. subsection 3 in section 2 might get: id="S2.SS3" | ||
| 590 | # idwithin : specifies that the ID is composed from $idwithin's ID,, even though | ||
| 591 | # the counter isn't numbered within it. (mainly to avoid duplicated ids) | ||
| 592 | # nested : a list of counters that correspond to scopes which are "inside" this one. | ||
| 593 | # Whenever any definitions scoped to this counter are deactivated, | ||
| 594 | # the inner counter's scopes are also deactivated. | ||
| 595 | # NOTE: I'm not sure this is even a sensible implementation, | ||
| 596 | # or why inner should be different than the counters reset by incrementing this counter. | ||
| 597 | |||
| 598 | sub NewCounter { | ||
| 599 | my ($ctr, $within, %options) = @_; | ||
| 600 | my $unctr = "UN$ctr"; # UNctr is counter for generating ID's for UN-numbered items. | ||
| 601 | DefRegisterI(T_CS("\\c\@$ctr"), undef, Number(0)); | ||
| 602 | AssignValue("\\c\@$ctr" => Number(0), 'global'); | ||
| 603 | AfterAssignment(); | ||
| 604 | AssignValue("\\cl\@$ctr" => Tokens(), 'global') unless LookupValue("\\cl\@$ctr"); | ||
| 605 | DefRegisterI(T_CS("\\c\@$unctr"), undef, Number(0)); | ||
| 606 | AssignValue("\\c\@$unctr" => Number(0), 'global'); | ||
| 607 | AssignValue("\\cl\@$unctr" => Tokens(), 'global') unless LookupValue("\\cl\@$unctr"); | ||
| 608 | my $x; | ||
| 609 | AssignValue("\\cl\@$within" => | ||
| 610 | Tokens(T_CS($ctr), T_CS($unctr), (($x = LookupValue("\\cl\@$within")) ? $x->unlist : ())), | ||
| 611 | 'global') if $within; | ||
| 612 | AssignValue("\\cl\@UN$within" => | ||
| 613 | Tokens(T_CS($unctr), (($x = LookupValue("\\cl\@UN$within")) ? $x->unlist : ())), | ||
| 614 | 'global') if $within; | ||
| 615 | AssignValue('nested_counters_' . $ctr => $options{nested}, 'global') if $options{nested}; | ||
| 616 | # default is equivalent to \arabic{ctr}, but w/o using the LaTeX macro! | ||
| 617 | DefMacroI(T_CS("\\the$ctr"), undef, sub { | ||
| 618 | ExplodeText(CounterValue($ctr)->valueOf); }, | ||
| 619 | scope => 'global'); | ||
| 620 | if (!LookupDefinition(T_CS("\\p\@$ctr"))) { | ||
| 621 | DefMacroI(T_CS("\\p\@$ctr"), undef, Tokens(), scope => 'global'); } | ||
| 622 | my $prefix = $options{idprefix}; | ||
| 623 | AssignValue('@ID@prefix@' . $ctr => $prefix, 'global') if $prefix; | ||
| 624 | $prefix = LookupValue('@ID@prefix@' . $ctr) || $ctr unless $prefix; | ||
| 625 | $prefix = CleanID($prefix); | ||
| 626 | if (defined $prefix) { | ||
| 627 | if (my $idwithin = $options{idwithin} || $within) { | ||
| 628 | DefMacroI(T_CS("\\the$ctr\@ID"), undef, | ||
| 629 | "\\expandafter\\ifx\\csname the$idwithin\@ID\\endcsname\\\@empty" | ||
| 630 | . "\\else\\csname the$idwithin\@ID\\endcsname.\\fi" | ||
| 631 | . " $prefix\\csname \@$ctr\@ID\\endcsname", | ||
| 632 | scope => 'global'); } | ||
| 633 | else { | ||
| 634 | DefMacroI(T_CS("\\the$ctr\@ID"), undef, "$prefix\\csname \@$ctr\@ID\\endcsname", | ||
| 635 | scope => 'global'); } | ||
| 636 | DefMacroI(T_CS("\\\@$ctr\@ID"), undef, "0", scope => 'global'); } | ||
| 637 | return; } | ||
| 638 | |||
| 639 | sub CounterValue { | ||
| 640 | my ($ctr) = @_; | ||
| 641 | $ctr = ToString($ctr) if ref $ctr; | ||
| 642 | my $value = LookupValue('\c@' . $ctr); | ||
| 643 | if (!$value) { | ||
| 644 | Warn('undefined', $ctr, $STATE->getStomach, | ||
| 645 | "Counter '$ctr' was not defined; assuming 0"); | ||
| 646 | $value = Number(0); } | ||
| 647 | return $value; } | ||
| 648 | |||
| 649 | sub AfterAssignment { | ||
| 650 | if (my $after = $STATE->lookupValue('afterAssignment')) { | ||
| 651 | $STATE->assignValue(afterAssignment => undef, 'global'); | ||
| 652 | $STATE->getStomach->getGullet->unread($after); } # primitive returns boxes, so these need to be digested! | ||
| 653 | return; } | ||
| 654 | |||
| 655 | sub SetCounter { | ||
| 656 | my ($ctr, $value) = @_; | ||
| 657 | $ctr = ToString($ctr) if ref $ctr; | ||
| 658 | AssignValue('\c@' . $ctr => $value, 'global'); | ||
| 659 | AfterAssignment(); | ||
| 660 | DefMacroI(T_CS("\\\@$ctr\@ID"), undef, Tokens(Explode($value->valueOf)), scope => 'global'); | ||
| 661 | return; } | ||
| 662 | |||
| 663 | sub AddToCounter { | ||
| 664 | my ($ctr, $value) = @_; | ||
| 665 | $ctr = ToString($ctr) if ref $ctr; | ||
| 666 | my $v = CounterValue($ctr)->add($value); | ||
| 667 | AssignValue('\c@' . $ctr => $v, 'global'); | ||
| 668 | AfterAssignment(); | ||
| 669 | DefMacroI(T_CS("\\\@$ctr\@ID"), undef, Tokens(Explode($v->valueOf)), scope => 'global'); | ||
| 670 | return; } | ||
| 671 | |||
| 672 | sub StepCounter { | ||
| 673 | my ($ctr, $noreset) = @_; | ||
| 674 | my $value = CounterValue($ctr); | ||
| 675 | AssignValue("\\c\@$ctr" => $value->add(Number(1)), 'global'); | ||
| 676 | AfterAssignment(); | ||
| 677 | DefMacroI(T_CS("\\\@$ctr\@ID"), undef, Tokens(Explode(LookupValue('\c@' . $ctr)->valueOf)), | ||
| 678 | scope => 'global'); | ||
| 679 | # and reset any within counters! | ||
| 680 | if (!$noreset) { | ||
| 681 | if (my $nested = LookupValue("\\cl\@$ctr")) { | ||
| 682 | foreach my $c ($nested->unlist) { | ||
| 683 | ResetCounter(ToString($c)); } } } | ||
| 684 | DigestIf(T_CS("\\the$ctr")); | ||
| 685 | return; } | ||
| 686 | |||
| 687 | # HOW can we retract this? | ||
| 688 | sub RefStepCounter { | ||
| 689 | my ($type, $noreset) = @_; | ||
| 690 | my $ctr = LookupMapping('counter_for_type', $type) || $type; | ||
| 691 | StepCounter($ctr, $noreset); | ||
| 692 | my $iddef = $STATE->lookupDefinition(T_CS("\\the$ctr\@ID")); | ||
| 693 | my $has_id = $iddef && ((!defined $iddef->getParameters) || ($iddef->getParameters->getNumArgs == 0)); | ||
| 694 | |||
| 695 | DefMacroI(T_CS('\@currentlabel'), undef, T_CS("\\the$ctr"), scope => 'global'); | ||
| 696 | DefMacroI(T_CS('\@currentID'), undef, T_CS("\\the$ctr\@ID"), scope => 'global') if $has_id; | ||
| 697 | |||
| 698 | my $id = $has_id && CleanID(ToString(DigestLiteral(T_CS("\\the$ctr\@ID")))); | ||
| 699 | |||
| 700 | my $refnum = DigestText(T_CS("\\the$ctr")); | ||
| 701 | my $tags = Digest(Invocation(T_CS('\lx@make@tags'), $type)); | ||
| 702 | # Any scopes activated for previous value of this counter (& any nested counters) must be removed. | ||
| 703 | # This may also include scopes activated for \label | ||
| 704 | deactivateCounterScope($ctr); | ||
| 705 | # And install the scope (if any) for this reference number. | ||
| 706 | AssignValue(current_counter => $ctr, 'local'); | ||
| 707 | my $scope = $ctr . ':' . ToString($refnum); | ||
| 708 | AssignValue('scopes_for_counter:' . $ctr => [$scope], 'local'); | ||
| 709 | $STATE->activateScope($scope); | ||
| 710 | return ( | ||
| 711 | ($tags ? (tags => $tags) : ()), | ||
| 712 | ($has_id ? (id => $id) : ())); } | ||
| 713 | |||
| 714 | sub deactivateCounterScope { | ||
| 715 | my ($ctr) = @_; | ||
| 716 | # print STDERR "Unusing scopes for $ctr\n"; | ||
| 717 | if (my $scopes = LookupValue('scopes_for_counter:' . $ctr)) { | ||
| 718 | map { $STATE->deactivateScope($_) } @$scopes; } | ||
| 719 | foreach my $inner_ctr (@{ LookupValue('nested_counters_' . $ctr) || [] }) { | ||
| 720 | deactivateCounterScope($inner_ctr); } | ||
| 721 | return; } | ||
| 722 | |||
| 723 | # For UN-numbered units | ||
| 724 | sub RefStepID { | ||
| 725 | my ($type) = @_; | ||
| 726 | my $ctr = LookupMapping('counter_for_type', $type) || $type; | ||
| 727 | my $unctr = "UN$ctr"; | ||
| 728 | StepCounter($unctr); | ||
| 729 | DefMacroI(T_CS("\\\@$ctr\@ID"), undef, | ||
| 730 | Tokens(T_OTHER('x'), Explode(LookupValue('\c@' . $unctr)->valueOf)), | ||
| 731 | scope => 'global'); | ||
| 732 | DefMacroI(T_CS('\@currentID'), undef, T_CS("\\the$ctr\@ID")); | ||
| 733 | my $id = CleanID(ToString(DigestLiteral(T_CS("\\the$ctr\@ID")))); | ||
| 734 | return (id => $id); } | ||
| 735 | |||
| 736 | sub ResetCounter { | ||
| 737 | my ($ctr) = @_; | ||
| 738 | AssignValue('\c@' . $ctr => Number(0), 'global'); | ||
| 739 | DefMacroI(T_CS("\\\@$ctr\@ID"), undef, Tokens(Explode(LookupValue('\c@' . $ctr)->valueOf)), | ||
| 740 | scope => 'global'); | ||
| 741 | # and reset any within counters! | ||
| 742 | if (my $nested = LookupValue("\\cl\@$ctr")) { | ||
| 743 | foreach my $c ($nested->unlist) { | ||
| 744 | ResetCounter(ToString($c)); } } | ||
| 745 | return; } | ||
| 746 | |||
| 747 | #********************************************************************** | ||
| 748 | # This function computes an xml:id for a node, if it hasn't already got one. | ||
| 749 | # It is suitable for use in Tag afterOpen as | ||
| 750 | # Tag('ltx:para',afterOpen=>sub { GenerateID(@_,'p'); }); | ||
| 751 | # It generates an id of the form <parentid>.<prefix><number> | ||
| 752 | # The parent node (the one with ID=<parentid>) also maintains a counter | ||
| 753 | # stored in an attribute _ID_counter_<prefix> recording the last used | ||
| 754 | # <number> for <prefix> amongst its descendents. | ||
| 755 | sub GenerateID { | ||
| 756 | my ($document, $node, $whatsit, $prefix) = @_; | ||
| 757 | # If node doesn't already have an id, and can | ||
| 758 | if (!$node->hasAttribute('xml:id') && $document->canHaveAttribute($node, 'xml:id') | ||
| 759 | # but isn't a _Capture_ node (which ultimately should disappear) | ||
| 760 | && ($document->getNodeQName($node) ne 'ltx:_Capture_')) { | ||
| 761 | my $ancestor = $document->findnode('ancestor::*[@xml:id][1]', $node) | ||
| 762 | || $document->getDocument->documentElement; | ||
| 763 | ## Old versions don't like $ancestor->getAttribute('xml:id'); | ||
| 764 | my $ancestor_id = $ancestor && $ancestor->getAttributeNS($LaTeXML::Common::XML::XML_NS, 'id'); | ||
| 765 | # If we've got no $ancestor_id, then we've got no $ancestor (no document yet!), | ||
| 766 | # or $ancestor IS the root element (but without an id); | ||
| 767 | # If we also have no $prefix, we'll end up with an illegal id (just digits)!!! | ||
| 768 | # We'll use "id" for an id prefix; this will work whether or not we have an $ancestor. | ||
| 769 | $prefix = 'id' unless $prefix || $ancestor_id; | ||
| 770 | |||
| 771 | my $ctrkey = '_ID_counter_' . (defined $prefix ? $prefix . '_' : ''); | ||
| 772 | my $ctr = ($ancestor && $ancestor->getAttribute($ctrkey)) || 0; | ||
| 773 | |||
| 774 | my $id = ($ancestor_id ? $ancestor_id . "." : '') . (defined $prefix ? $prefix : '') . (++$ctr); | ||
| 775 | $ancestor->setAttribute($ctrkey => $ctr) if $ancestor; | ||
| 776 | $document->setAttribute($node, 'xml:id' => $id); } | ||
| 777 | return; } | ||
| 778 | |||
| 779 | #====================================================================== | ||
| 780 | # | ||
| 781 | #====================================================================== | ||
| 782 | |||
| 783 | # Return $tokens with all tokens expanded | ||
| 784 | sub Expand { | ||
| 785 | my (@tokens) = @_; | ||
| 786 | return () unless @tokens; | ||
| 787 | return $STATE->getStomach->getGullet->readingFromMouth(LaTeXML::Core::Mouth->new(), sub { | ||
| 788 | my ($gullet) = @_; | ||
| 789 | $gullet->unread(@tokens); | ||
| 790 | my @expanded = (); | ||
| 791 | while (defined(my $t = $gullet->readXToken(0))) { | ||
| 792 | push(@expanded, $t); } | ||
| 793 | return Tokens(@expanded); }); } | ||
| 794 | |||
| 795 | sub Invocation { | ||
| 796 | my ($token, @args) = @_; | ||
| 797 | $token = (ref $token ? $token : T_CS($token)); | ||
| 798 | # Note: $token may have been \let to another defn! | ||
| 799 | if (my $defn = $STATE->lookupDefinition($token)) { | ||
| 800 | my $params = $defn->getParameters; | ||
| 801 | return Tokens($token, ($params ? $params->revertArguments(@args) : ())); } | ||
| 802 | else { | ||
| 803 | Error('undefined', $token, undef, | ||
| 804 | "Can't invoke " . Stringify($token) . "; it is undefined"); | ||
| 805 | DefConstructorI($token, convertLaTeXArgs(scalar(@args), 0), | ||
| 806 | sub { LaTeXML::Core::Stomach::makeError($_[0], 'undefined', $token); }); | ||
| 807 | return Tokens($token, map { (T_BEGIN, $_->unlist, T_END) } @args); } } | ||
| 808 | |||
| 809 | sub RawTeX { | ||
| 810 | my ($text) = @_; | ||
| 811 | # It could be as simple as this, except if catcodes get changed, it's too late!!! | ||
| 812 | # Digest(TokenizeInternal($text)); | ||
| 813 | my $stomach = $STATE->getStomach; | ||
| 814 | my $savedcc = $STATE->lookupCatcode('@'); | ||
| 815 | $STATE->assignCatcode('@' => CC_LETTER); | ||
| 816 | |||
| 817 | $stomach->getGullet->readingFromMouth(LaTeXML::Core::Mouth->new($text, fordefinitions => 1), sub { | ||
| 818 | my ($gullet) = @_; | ||
| 819 | my $token; | ||
| 820 | while ($token = $gullet->readXToken(0)) { | ||
| 821 | next if $token->equals(T_SPACE); | ||
| 822 | $stomach->invokeToken($token); } }); | ||
| 823 | |||
| 824 | $STATE->assignCatcode('@' => $savedcc); | ||
| 825 | return; } | ||
| 826 | |||
| 827 | sub StartSemiverbatim { | ||
| 828 | my (@chars) = @_; | ||
| 829 | $STATE->beginSemiverbatim(@chars); | ||
| 830 | return; } | ||
| 831 | |||
| 832 | sub EndSemiverbatim { | ||
| 833 | $STATE->endSemiverbatim; | ||
| 834 | return; } | ||
| 835 | |||
| 836 | # WARNING: These two utilities bind $STATE to simple State objects with known fixed catcodes. | ||
| 837 | # The State normally contains ALL the bindings, etc and links to other important objects. | ||
| 838 | # We CAN do that here, since we are ONLY tokenizing from a new Mouth, bypassing stomach & gullet. | ||
| 839 | # However, be careful with any changes. | ||
| 840 | our $STD_CATTABLE; | ||
| 841 | our $STY_CATTABLE; | ||
| 842 | |||
| 843 | # Tokenize($string); Tokenizes the string using the standard cattable, returning a LaTeXML::Core::Tokens | ||
| 844 | sub Tokenize { | ||
| 845 | my ($string) = @_; | ||
| 846 | $STD_CATTABLE = LaTeXML::Core::State->new(catcodes => 'standard') unless $STD_CATTABLE; | ||
| 847 | local $STATE = $STD_CATTABLE; | ||
| 848 | return LaTeXML::Core::Mouth->new($string)->readTokens; } | ||
| 849 | |||
| 850 | # TokenizeInternal($string); Tokenizes the string using the internal cattable, returning a LaTeXML::Core::Tokens | ||
| 851 | sub TokenizeInternal { | ||
| 852 | my ($string) = @_; | ||
| 853 | $STY_CATTABLE = LaTeXML::Core::State->new(catcodes => 'style') unless $STY_CATTABLE; | ||
| 854 | local $STATE = $STY_CATTABLE; | ||
| 855 | return LaTeXML::Core::Mouth->new($string)->readTokens; } | ||
| 856 | |||
| 857 | #====================================================================== | ||
| 858 | # Non-exported support for defining forms. | ||
| 859 | #====================================================================== | ||
| 860 | sub CheckOptions { | ||
| 861 | my ($operation, $allowed, %options) = @_; | ||
| 862 | my @badops = grep { !$$allowed{$_} } keys %options; | ||
| 863 | Error('misdefined', $operation, $STATE->getStomach, | ||
| 864 | "$operation does not accept options:" . join(', ', @badops)) if @badops; | ||
| 865 | return; } | ||
| 866 | |||
| 867 | sub requireMath { | ||
| 868 | my ($cs) = @_; | ||
| 869 | $cs = ToString($cs); | ||
| 870 | Warn('unexpected', $cs, $STATE->getStomach, | ||
| 871 | "$cs should only appear in math mode") unless LookupValue('IN_MATH'); | ||
| 872 | return; } | ||
| 873 | |||
| 874 | sub forbidMath { | ||
| 875 | my ($cs) = @_; | ||
| 876 | $cs = ToString($cs); | ||
| 877 | Warn('unexpected', $cs, $STATE->getStomach, | ||
| 878 | "$cs should not appear in math mode") if LookupValue('IN_MATH'); | ||
| 879 | return; } | ||
| 880 | |||
| 881 | #********************************************************************** | ||
| 882 | # Definitions | ||
| 883 | #********************************************************************** | ||
| 884 | sub DefAutoload { | ||
| 885 | my ($cs, $defnfile) = @_; | ||
| 886 | my $csname = (ref $cs ? ToString($cs) : $cs); | ||
| 887 | $csname = '\\' . $csname unless $cs =~ /^\\/; | ||
| 888 | $cs = T_CS($csname) unless ref $cs; | ||
| 889 | if ($defnfile =~ /^(.*?)\.(pool|sty|cls)\.ltxml$/) { | ||
| 890 | my ($name, $type) = ($1, $2); | ||
| 891 | if (!LookupValue($name . '.' . $type . '_loaded')) { # if already loaded, DONT redefine! | ||
| 892 | DefMacroI($cs, undef, sub { | ||
| 893 | $STATE->assign_internal('meaning', $csname => undef, 'global'); # UNDEFINE (no recurse) | ||
| 894 | if ($type eq 'pool') { LoadPool($name); } # Load appropriate definitions | ||
| 895 | elsif ($type eq 'cls') { LoadClass($name); } | ||
| 896 | else { RequirePackage($name); } | ||
| 897 | ($cs); }); } } # Then return the original cs, so that it's be re-tried. | ||
| 898 | else { | ||
| 899 | Warning('unexpected', $defnfile, undef, "Don't know how to autoload $csname from $defnfile"); } | ||
| 900 | return; } | ||
| 901 | |||
| 902 | #====================================================================== | ||
| 903 | # Defining Expandable Control Sequences. | ||
| 904 | #====================================================================== | ||
| 905 | # Define an expandable control sequence. It will be expanded in the Gullet. | ||
| 906 | # The $replacement should be a LaTeXML::Core::Tokens (the arguments will be | ||
| 907 | # substituted for any #1,...), or a sub which returns a list of tokens (or just return;). | ||
| 908 | # Those tokens, if any, will be reinserted into the input. | ||
| 909 | # There are no options to these definitions. | ||
| 910 | my $expandable_options = { # [CONSTANT] | ||
| 911 | scope => 1, locked => 1 }; | ||
| 912 | |||
| 913 | sub DefExpandable { | ||
| 914 | my ($proto, $expansion, %options) = @_; | ||
| 915 | Warn('deprecated', 'DefExpandable', $STATE->getStomach, | ||
| 916 | "DefExpandable ($proto) is deprecated; use DefMacro"); | ||
| 917 | DefMacro($proto, $expansion, %options); | ||
| 918 | return; } | ||
| 919 | |||
| 920 | # Define a Macro: Essentially an alias for DefExpandable | ||
| 921 | # For convenience, the $expansion can be a string which will be tokenized. | ||
| 922 | my $macro_options = { # [CONSTANT] | ||
| 923 | scope => 1, locked => 1, mathactive => 1, | ||
| 924 | protected => 1, outer => 1, long => 1 }; | ||
| 925 | |||
| 926 | sub DefMacro { | ||
| 927 | my ($proto, $expansion, %options) = @_; | ||
| 928 | CheckOptions("DefMacro ($proto)", $macro_options, %options); | ||
| 929 | DefMacroI(parsePrototype($proto), $expansion, %options); | ||
| 930 | return; } | ||
| 931 | |||
| 932 | sub DefMacroI { | ||
| 933 | my ($cs, $paramlist, $expansion, %options) = @_; | ||
| 934 | if (!defined $expansion) { $expansion = Tokens(); } | ||
| 935 | # Optimization: Defer till macro actually used | ||
| 936 | # elsif (!ref $expansion) { $expansion = TokenizeInternal($expansion); } | ||
| 937 | if ((length($cs) == 1) && $options{mathactive}) { | ||
| 938 | $STATE->assignMathcode($cs => 0x8000, $options{scope}); } | ||
| 939 | $cs = coerceCS($cs); | ||
| 940 | ### $paramlist = parseParameters($paramlist, $cs) if defined $paramlist && !ref $paramlist; | ||
| 941 | $STATE->installDefinition(LaTeXML::Core::Definition::Expandable->new($cs, $paramlist, $expansion, %options), | ||
| 942 | $options{scope}); | ||
| 943 | AssignValue(ToString($cs) . ":locked" => 1, 'global') if $options{locked}; | ||
| 944 | return; } | ||
| 945 | |||
| 946 | #====================================================================== | ||
| 947 | # Defining Conditional Control Sequences. | ||
| 948 | #====================================================================== | ||
| 949 | # Define a conditional control sequence. Its processing takes place in | ||
| 950 | # the Gullet. The test is applied to the arguments (if any), | ||
| 951 | # which determines which branch is executed. | ||
| 952 | # If the test is undefined, the conditional is a "user defined" one; | ||
| 953 | # Two additional primitives are defined \footrue and \foofalse; | ||
| 954 | # the test is then determined by the most recently called of those. | ||
| 955 | |||
| 956 | # If you supply a skipper instead of a test, it is also applied to the arguments | ||
| 957 | # and should skip to the right place in the following \or, \else, \fi. | ||
| 958 | # This is ONLY used for \ifcase. | ||
| 959 | my $conditional_options = { # [CONSTANT] | ||
| 960 | scope => 1, locked => 1, skipper => 1 }; | ||
| 961 | |||
| 962 | sub DefConditional { | ||
| 963 | my ($proto, $test, %options) = @_; | ||
| 964 | CheckOptions("DefConditional ($proto)", $conditional_options, %options); | ||
| 965 | DefConditionalI(parsePrototype($proto), $test, %options); | ||
| 966 | return; } | ||
| 967 | |||
| 968 | sub DefConditionalI { | ||
| 969 | my ($cs, $paramlist, $test, %options) = @_; | ||
| 970 | $cs = coerceCS($cs); | ||
| 971 | my $csname = ToString($cs); | ||
| 972 | # Special cases... | ||
| 973 | if ($csname eq '\fi') { | ||
| 974 | $STATE->installDefinition(LaTeXML::Core::Definition::Conditional->new( | ||
| 975 | $cs, undef, undef, conditional_type => 'fi', %options), | ||
| 976 | $options{scope}); } | ||
| 977 | elsif ($csname eq '\else') { | ||
| 978 | $STATE->installDefinition(LaTeXML::Core::Definition::Conditional->new( | ||
| 979 | $cs, undef, undef, conditional_type => 'else', %options), | ||
| 980 | $options{scope}); } | ||
| 981 | elsif ($csname eq '\or') { | ||
| 982 | $STATE->installDefinition(LaTeXML::Core::Definition::Conditional->new( | ||
| 983 | $cs, undef, undef, conditional_type => 'or', %options), | ||
| 984 | $options{scope}); } | ||
| 985 | elsif ($csname =~ /^\\(?:if(.*)|unless)$/) { | ||
| 986 | my $name = $1; | ||
| 987 | if ((defined $name) && ($name ne 'case') | ||
| 988 | && (!defined $test)) { # user-defined conditional, like with \newif | ||
| 989 | DefMacroI(T_CS('\\' . $name . 'true'), undef, Tokens(T_CS('\let'), $cs, T_CS('\iftrue'))); | ||
| 990 | DefMacroI(T_CS('\\' . $name . 'false'), undef, Tokens(T_CS('\let'), $cs, T_CS('\iffalse'))); | ||
| 991 | Let($cs, T_CS('\iffalse')); } | ||
| 992 | else { | ||
| 993 | # For \ifcase, the parameter list better be a single Number !! | ||
| 994 | $STATE->installDefinition(LaTeXML::Core::Definition::Conditional->new($cs, $paramlist, $test, | ||
| 995 | conditional_type => 'if', %options), | ||
| 996 | $options{scope}); } | ||
| 997 | } | ||
| 998 | else { | ||
| 999 | Error('misdefined', $cs, $STATE->getStomach, | ||
| 1000 | "The conditional " . Stringify($cs) . " is being defined but doesn't start with \\if"); } | ||
| 1001 | AssignValue(ToString($cs) . ":locked" => 1) if $options{locked}; | ||
| 1002 | return; } | ||
| 1003 | |||
| 1004 | sub IfCondition { | ||
| 1005 | my ($if, @args) = @_; | ||
| 1006 | my $gullet = $STATE->getStomach->getGullet; | ||
| 1007 | $if = coerceCS($if); | ||
| 1008 | my ($defn, $test); | ||
| 1009 | if (($defn = $STATE->lookupDefinition($if)) | ||
| 1010 | && (($$defn{conditional_type} || '') eq 'if') && ($test = $defn->getTest)) { | ||
| 1011 | return &$test($gullet, @args); } | ||
| 1012 | elsif (XEquals($if, T_CS('\iftrue'))) { | ||
| 1013 | return 1; } | ||
| 1014 | elsif (XEquals($if, T_CS('\iffalse'))) { | ||
| 1015 | return 0; } | ||
| 1016 | else { | ||
| 1017 | Error('expected', 'conditional', $gullet, | ||
| 1018 | "Expected a conditional, got '" . ToString($if) . "'"); | ||
| 1019 | return; } } | ||
| 1020 | |||
| 1021 | # Used only for regular \newif type conditions | ||
| 1022 | sub SetCondition { | ||
| 1023 | my ($if, $value, $scope) = @_; | ||
| 1024 | my ($defn, $test); | ||
| 1025 | # We'll accept any conditional \ifxxx, providing it takes no arguments | ||
| 1026 | if (($defn = $STATE->lookupDefinition($if)) && (($$defn{conditional_type} || '') eq 'if') | ||
| 1027 | && !$defn->getParameters) { | ||
| 1028 | Let($if, ($value ? T_CS('\iftrue') : T_CS('\iffalse')), $scope) } | ||
| 1029 | else { | ||
| 1030 | Error('expected', 'conditional', $STATE->getStomach, | ||
| 1031 | "Expected a conditional defined by \\newif, got '" . ToString($if) . "'"); } | ||
| 1032 | return; } | ||
| 1033 | |||
| 1034 | #====================================================================== | ||
| 1035 | # Define a primitive control sequence. | ||
| 1036 | #====================================================================== | ||
| 1037 | # Primitives are executed in the Stomach. | ||
| 1038 | # The $replacement should be a sub which returns nothing, or a list of Box's or Whatsit's. | ||
| 1039 | # The options are: | ||
| 1040 | # isPrefix : 1 for things like \global, \long, etc. | ||
| 1041 | # registerType : for parameters (but needs to be worked into DefParameter, below). | ||
| 1042 | |||
| 1043 | my $primitive_options = { # [CONSTANT] | ||
| 1044 | isPrefix => 1, scope => 1, mode => 1, font => 1, | ||
| 1045 | requireMath => 1, forbidMath => 1, | ||
| 1046 | beforeDigest => 1, afterDigest => 1, | ||
| 1047 | bounded => 1, locked => 1, alias => 1, | ||
| 1048 | outer => 1, long => 1 }; | ||
| 1049 | |||
| 1050 | sub DefPrimitive { | ||
| 1051 | my ($proto, $replacement, %options) = @_; | ||
| 1052 | CheckOptions("DefPrimitive ($proto)", $primitive_options, %options); | ||
| 1053 | DefPrimitiveI(parsePrototype($proto), $replacement, %options); | ||
| 1054 | return; } | ||
| 1055 | |||
| 1056 | sub DefPrimitiveI { | ||
| 1057 | my ($cs, $paramlist, $replacement, %options) = @_; | ||
| 1058 | ##### $replacement = sub { (); } unless defined $replacement; | ||
| 1059 | my $string = $replacement; | ||
| 1060 | $replacement = sub { Box($string, undef, undef, Invocation($options{alias} || $cs, @_[1 .. $#_])); } | ||
| 1061 | unless ref $replacement; | ||
| 1062 | $cs = coerceCS($cs); | ||
| 1063 | ### $paramlist = parseParameters($paramlist, $cs) if defined $paramlist && !ref $paramlist; | ||
| 1064 | my $mode = $options{mode}; | ||
| 1065 | my $bounded = $options{bounded}; | ||
| 1066 | $STATE->installDefinition(LaTeXML::Core::Definition::Primitive | ||
| 1067 | ->new($cs, $paramlist, $replacement, | ||
| 1068 | beforeDigest => flatten(($options{requireMath} ? (sub { requireMath($cs); }) : ()), | ||
| 1069 | ($options{forbidMath} ? (sub { forbidMath($cs); }) : ()), | ||
| 1070 | ($mode ? (sub { $_[0]->beginMode($mode); }) | ||
| 1071 | : ($bounded ? (sub { $_[0]->bgroup; }) : ())), | ||
| 1072 | ($options{font} ? (sub { MergeFont(%{ $options{font} }); }) : ()), | ||
| 1073 | $options{beforeDigest}), | ||
| 1074 | afterDigest => flatten($options{afterDigest}, | ||
| 1075 | ($mode ? (sub { $_[0]->endMode($mode) }) | ||
| 1076 | : ($bounded ? (sub { $_[0]->egroup; }) : ()))), | ||
| 1077 | outer => $options{outer}, | ||
| 1078 | long => $options{long}, | ||
| 1079 | isPrefix => $options{isPrefix}), | ||
| 1080 | $options{scope}); | ||
| 1081 | AssignValue(ToString($cs) . ":locked" => 1) if $options{locked}; | ||
| 1082 | return; } | ||
| 1083 | |||
| 1084 | my $register_options = { # [CONSTANT] | ||
| 1085 | readonly => 1, getter => 1, setter => 1 }; | ||
| 1086 | my %register_types = ( # [CONSTANT] | ||
| 1087 | 'LaTeXML::Common::Number' => 'Number', | ||
| 1088 | 'LaTeXML::Common::Dimension' => 'Dimension', | ||
| 1089 | 'LaTeXML::Common::Glue' => 'Glue', | ||
| 1090 | 'LaTeXML::Core::MuGlue' => 'MuGlue', | ||
| 1091 | 'LaTeXML::Core::Tokens' => 'Tokens', | ||
| 1092 | 'LaTeXML::Core::Token' => 'Token', | ||
| 1093 | ); | ||
| 1094 | |||
| 1095 | sub DefRegister { | ||
| 1096 | my ($proto, $value, %options) = @_; | ||
| 1097 | CheckOptions("DefRegister ($proto)", $register_options, %options); | ||
| 1098 | DefRegisterI(parsePrototype($proto), $value, %options); | ||
| 1099 | return; } | ||
| 1100 | |||
| 1101 | sub DefRegisterI { | ||
| 1102 | my ($cs, $paramlist, $value, %options) = @_; | ||
| 1103 | $cs = coerceCS($cs); | ||
| 1104 | ### $paramlist = parseParameters($paramlist, $cs) if defined $paramlist && !ref $paramlist; | ||
| 1105 | my $type = $register_types{ ref $value }; | ||
| 1106 | my $name = ToString($cs); | ||
| 1107 | my $getter = $options{getter} | ||
| 1108 | || sub { LookupValue(join('', $name, map { ToString($_) } @_)) || $value; }; | ||
| 1109 | my $setter = $options{setter} | ||
| 1110 | || ($options{readonly} | ||
| 1111 | ? sub { my ($v, @args) = @_; | ||
| 1112 | Warn('unexpected', $name, $STATE->getStomach, | ||
| 1113 | "Can't assign readonly register $name to " . ToString($v)); return; } | ||
| 1114 | : sub { my ($v, @args) = @_; | ||
| 1115 | AssignValue(join('', $name, map { ToString($_) } @args) => $v); }); | ||
| 1116 | # Not really right to set the value! | ||
| 1117 | AssignValue(ToString($cs) => $value) if defined $value; | ||
| 1118 | $STATE->installDefinition(LaTeXML::Core::Definition::Register->new($cs, $paramlist, | ||
| 1119 | registerType => $type, | ||
| 1120 | getter => $getter, setter => $setter, | ||
| 1121 | readonly => $options{readonly}), | ||
| 1122 | 'global'); | ||
| 1123 | return; } | ||
| 1124 | |||
| 1125 | sub LookupRegister { | ||
| 1126 | my ($cs, @parameters) = @_; | ||
| 1127 | my $defn; | ||
| 1128 | $cs = T_CS($cs) unless ref $cs; | ||
| 1129 | if (($defn = $STATE->lookupDefinition($cs)) && $defn->isRegister) { | ||
| 1130 | return $defn->valueOf(@parameters); } | ||
| 1131 | else { | ||
| 1132 | Warn('expected', 'register', $STATE->getStomach, | ||
| 1133 | "The control sequence " . ToString($cs) . " is not a register"); } | ||
| 1134 | return; } | ||
| 1135 | |||
| 1136 | sub LookupDimension { | ||
| 1137 | my ($cs) = @_; | ||
| 1138 | $cs = T_CS($cs) unless ref $cs; | ||
| 1139 | if (my $defn = $STATE->lookupDefinition($cs)) { | ||
| 1140 | if ($defn->isRegister) { # Easy (and proper) case. | ||
| 1141 | return $defn->valueOf; } | ||
| 1142 | else { | ||
| 1143 | $STATE->getStomach->getGullet->readingFromMouth(LaTeXML::Core::Mouth->new(), sub { # start with empty mouth | ||
| 1144 | my ($gullet) = @_; | ||
| 1145 | $gullet->unread($cs); # but put back tokens to be read | ||
| 1146 | return $gullet->readDimension; }); } } | ||
| 1147 | else { | ||
| 1148 | Warn('expected', 'register', $STATE->getStomach, | ||
| 1149 | "The control sequence " . ToString($cs) . " is not a register"); } | ||
| 1150 | return Dimension(0); } | ||
| 1151 | |||
| 1152 | sub AssignRegister { | ||
| 1153 | my ($cs, $value, @parameters) = @_; | ||
| 1154 | my $defn; | ||
| 1155 | $cs = T_CS($cs) unless ref $cs; | ||
| 1156 | if (($defn = $STATE->lookupDefinition($cs)) && $defn->isRegister) { | ||
| 1157 | return $defn->setValue($value, @parameters); } | ||
| 1158 | else { | ||
| 1159 | Warn('expected', 'register', $STATE->getStomach, | ||
| 1160 | "The control sequence " . ToString($cs) . " is not a register"); | ||
| 1161 | return; } } | ||
| 1162 | |||
| 1163 | sub flatten { | ||
| 1164 | my (@stuff) = @_; | ||
| 1165 | return [map { (defined $_ ? (ref $_ eq 'ARRAY' ? @$_ : ($_)) : ()) } @stuff]; } | ||
| 1166 | |||
| 1167 | #====================================================================== | ||
| 1168 | # Define a constructor control sequence. | ||
| 1169 | #====================================================================== | ||
| 1170 | # The arguments, if any, will be collected and processed in the Stomach, and | ||
| 1171 | # a Whatsit will be constructed. | ||
| 1172 | # It is the Whatsit that will be processed in the Document: It is responsible | ||
| 1173 | # for constructing XML Nodes. The $replacement should be a sub which inserts nodes, | ||
| 1174 | # or a string specifying a constructor pattern (See somewhere). | ||
| 1175 | # | ||
| 1176 | # Options are: | ||
| 1177 | # bounded : any side effects of before/after daemans are bounded; they are | ||
| 1178 | # automatically enclosed by bgroup/egroup pair. | ||
| 1179 | # mode : causes a switch into the given mode during the Whatsit building in the stomach. | ||
| 1180 | # reversion : a string representing the preferred TeX form of the invocation. | ||
| 1181 | # beforeDigest : code to be executed (in the stomach) before parsing & constructing the Whatsit. | ||
| 1182 | # Can be used for changing modes, beginning groups, etc. | ||
| 1183 | # afterDigest : code to be executed (in the stomach) after parsing & constructing the Whatsit. | ||
| 1184 | # useful for setting Whatsit properties, | ||
| 1185 | # properties : a hashref listing default values of properties to assign to the Whatsit. | ||
| 1186 | # These properties can be used in the constructor. | ||
| 1187 | my $constructor_options = { # [CONSTANT] | ||
| 1188 | mode => 1, requireMath => 1, forbidMath => 1, font => 1, | ||
| 1189 | alias => 1, reversion => 1, sizer => 1, properties => 1, | ||
| 1190 | nargs => 1, | ||
| 1191 | beforeDigest => 1, afterDigest => 1, beforeConstruct => 1, afterConstruct => 1, | ||
| 1192 | captureBody => 1, scope => 1, bounded => 1, locked => 1, | ||
| 1193 | outer => 1, long => 1 }; | ||
| 1194 | |||
| 1195 | sub inferSizer { | ||
| 1196 | my ($sizer, $reversion) = @_; | ||
| 1197 | return (defined $sizer ? $sizer | ||
| 1198 | : ((defined $reversion) && (!ref $reversion) && ($reversion =~ /^(?:#\w+)*$/) | ||
| 1199 | ? $reversion : undef)); } | ||
| 1200 | |||
| 1201 | sub DefConstructor { | ||
| 1202 | my ($proto, $replacement, %options) = @_; | ||
| 1203 | CheckOptions("DefConstructor ($proto)", $constructor_options, %options); | ||
| 1204 | DefConstructorI(parsePrototype($proto), $replacement, %options); | ||
| 1205 | return; } | ||
| 1206 | |||
| 1207 | sub DefConstructorI { | ||
| 1208 | my ($cs, $paramlist, $replacement, %options) = @_; | ||
| 1209 | $cs = coerceCS($cs); | ||
| 1210 | ### $paramlist = parseParameters($paramlist, $cs) if defined $paramlist && !ref $paramlist; | ||
| 1211 | my $mode = $options{mode}; | ||
| 1212 | my $bounded = $options{bounded}; | ||
| 1213 | $STATE->installDefinition(LaTeXML::Core::Definition::Constructor | ||
| 1214 | ->new($cs, $paramlist, $replacement, | ||
| 1215 | beforeDigest => flatten(($options{requireMath} ? (sub { requireMath($cs); }) : ()), | ||
| 1216 | ($options{forbidMath} ? (sub { forbidMath($cs); }) : ()), | ||
| 1217 | ($mode ? (sub { $_[0]->beginMode($mode); }) | ||
| 1218 | : ($bounded ? (sub { $_[0]->bgroup; }) : ())), | ||
| 1219 | ($options{font} ? (sub { MergeFont(%{ $options{font} }); }) : ()), | ||
| 1220 | $options{beforeDigest}), | ||
| 1221 | afterDigest => flatten($options{afterDigest}, | ||
| 1222 | ($mode ? (sub { $_[0]->endMode($mode) }) | ||
| 1223 | : ($bounded ? (sub { $_[0]->egroup; }) : ()))), | ||
| 1224 | beforeConstruct => flatten($options{beforeConstruct}), | ||
| 1225 | afterConstruct => flatten($options{afterConstruct}), | ||
| 1226 | nargs => $options{nargs}, | ||
| 1227 | alias => $options{alias}, | ||
| 1228 | reversion => $options{reversion}, | ||
| 1229 | sizer => inferSizer($options{sizer}, $options{reversion}), | ||
| 1230 | captureBody => $options{captureBody}, | ||
| 1231 | properties => $options{properties} || {}, | ||
| 1232 | outer => $options{outer}, | ||
| 1233 | long => $options{long}), | ||
| 1234 | $options{scope}); | ||
| 1235 | AssignValue(ToString($cs) . ":locked" => 1) if $options{locked}; | ||
| 1236 | return; } | ||
| 1237 | |||
| 1238 | #====================================================================== | ||
| 1239 | # Support for XMDual | ||
| 1240 | |||
| 1241 | # Perhaps it would be better to use a label(-like) indirection here, | ||
| 1242 | # so all ID's can stay in the desired format? | ||
| 1243 | sub getXMArgID { | ||
| 1244 | StepCounter('@XMARG'); | ||
| 1245 | DefMacroI(T_CS('\@@XMARG@ID'), undef, Tokens(Explode(LookupValue('\c@@XMARG')->valueOf)), | ||
| 1246 | scope => 'global'); | ||
| 1247 | return Expand(T_CS('\the@XMARG@ID')); } | ||
| 1248 | |||
| 1249 | # Given a list of Tokens (to be expanded into mathematical objects) | ||
| 1250 | # return two lists: | ||
| 1251 | # (1) The Tokens' wrapped in an XMAarg, with an ID added | ||
| 1252 | # (2) a corresponding list of Tokens creating XMRef's to those IDs | ||
| 1253 | # Ah, but there are complications!!! | ||
| 1254 | # On the one hand, arguments may be hidden, never appearing on the presentation side | ||
| 1255 | # (all will be passed to the content side); This argues for putting the XMArg's on the content side. | ||
| 1256 | # OTOH, they ought to be on the presentation side, so that they can be expanded & digested in | ||
| 1257 | # the proper context they will be presented, and pick up all the styling (font size, displaystyle..) | ||
| 1258 | # I don't know how to work around the latter, so we'll put args on the presentation side, | ||
| 1259 | # UNLESS they are hidden, in which case they'll be on the content side. | ||
| 1260 | # So, how do we know if they're hidden? We'll scan the presentation for #\d, that's how! | ||
| 1261 | sub dualize_arglist { | ||
| 1262 | my ($presentation, @args) = @_; | ||
| 1263 | my %used = (); | ||
| 1264 | $presentation = ToString($presentation); | ||
| 1265 | $presentation =~ s/#(\d)/{ $used{$1}++; }/ge; # Get the args that were actually used! | ||
| 1266 | my (@cargs, @pargs); | ||
| 1267 | my $i = 0; | ||
| 1268 | foreach my $arg (@args) { | ||
| 1269 | $i++; | ||
| 1270 | if (!(defined $arg) || !$arg->unlist) { # undefined or empty args, just pass through | ||
| 1271 | push(@pargs, $arg); | ||
| 1272 | push(@cargs, $arg); } | ||
| 1273 | elsif ($used{$i}) { # used in presentation? | ||
| 1274 | my $id = getXMArgID(); | ||
| 1275 | push(@pargs, Invocation(T_CS('\@XMArg'), $id, $arg)); # put XMArg in presentation | ||
| 1276 | push(@cargs, Invocation(T_CS('\@XMRef'), $id)); } | ||
| 1277 | else { # Hidden arg, put XMArg in content. | ||
| 1278 | my $id = getXMArgID(); | ||
| 1279 | push(@cargs, Invocation(T_CS('\@XMArg'), $id, $arg)); | ||
| 1280 | push(@pargs, Invocation(T_CS('\@XMRef'), $id)); } } | ||
| 1281 | return ([@cargs], [@pargs]); } | ||
| 1282 | |||
| 1283 | # Given a list of XML nodes (either libxml nodes, or array representations) | ||
| 1284 | # return a list of XMRef's referring to those nodes; | ||
| 1285 | # ensure each source node has an ID (if already instanciated as XML) | ||
| 1286 | # or _xmkey if still in array rep. since it will get an ID later, and the connection re-made) | ||
| 1287 | # Note that ltx:XMHint nodes are ephemeral and shouldn't be ref'd! | ||
| 1288 | # likewise, we avoid creating XMRefs to XMRefs | ||
| 1289 | sub createXMRefs { | ||
| 1290 | my ($document, @args) = @_; | ||
| 1291 | my @refs = (); | ||
| 1292 | foreach my $arg (@args) { | ||
| 1293 | my $isarray = (ref $arg eq 'ARRAY'); | ||
| 1294 | my $qname = ($isarray ? $$arg[0] : $document->getNodeQName($arg)); | ||
| 1295 | my $box = ($isarray ? $$arg[1]{_box} : $document->getNodeBox($arg)); | ||
| 1296 | # XMHint's are ephemeral, they may disappear; so just clone it w/o id | ||
| 1297 | if ($qname eq 'ltx:XMHint') { | ||
| 1298 | my %attr = ($isarray ? %{ $$arg[1] } : (map { $_->nodeName => $_->getValue } $arg->attributes)); | ||
| 1299 | delete $attr{'xml:id'}; | ||
| 1300 | push(@refs, [$qname, {%attr}]); } | ||
| 1301 | # Likewise, clone an XMRef (w/o any attributes or id ?) rather than create an XMRef to an XMRef. | ||
| 1302 | elsif ($qname eq 'ltx:XMRef') { | ||
| 1303 | my $key = ($isarray ? $$arg[1]{_xmkey} : $arg->getAttribute('_xmkey')); | ||
| 1304 | my $id = ($isarray ? $$arg[1]{idref} : $arg->getAttribute('idref')); | ||
| 1305 | push(@refs, [$qname, { _xmkey => $key, idref => $id, _box => $box }]); } | ||
| 1306 | else { | ||
| 1307 | if (my $id = ($isarray ? $$arg[1]{'xml:id'} : $arg->getAttribute('xml:id'))) { | ||
| 1308 | # $arg already has id, so refer to it. | ||
| 1309 | push(@refs, ['ltx:XMRef', { 'idref' => $id, _box => $box }]); } | ||
| 1310 | elsif ($isarray) { | ||
| 1311 | # $arg is not yet instanciated, so hasn't had chance to get auto-id; use _xmkey | ||
| 1312 | my $key = ToString(getXMArgID()); | ||
| 1313 | $$arg[1]{'_xmkey'} = $key; | ||
| 1314 | push(@refs, ['ltx:XMRef', { '_xmkey' => $key, _box => $box }]); } | ||
| 1315 | else { | ||
| 1316 | # If arg is already XML, it's too late to get automatic ID's | ||
| 1317 | GenerateID($document, $arg, undef, ''); | ||
| 1318 | push(@refs, ['ltx:XMRef', { 'idref' => $arg->getAttribute('xml:id'), _box => $box }]); } } } | ||
| 1319 | return @refs; } | ||
| 1320 | |||
| 1321 | # DefMath Define a Mathematical symbol or function. | ||
| 1322 | # There are two sets of cases: | ||
| 1323 | # (1) If the presentation appears to be TeX code, we create an XMDual, | ||
| 1324 | # since the presentation may end up with structure, etc. | ||
| 1325 | # (2) But if the presentation is a simple string, or unicode, | ||
| 1326 | # it is just the content of the symbol; even if the function takes arguments. | ||
| 1327 | # ALSO | ||
| 1328 | # arrange that the operator token gets cs="$cs" | ||
| 1329 | # ALSO | ||
| 1330 | # Possibly some trick with SUMOP/INTOP affecting limits ? | ||
| 1331 | # Well, not exactly, but.... | ||
| 1332 | # HMM.... Still fishy. | ||
| 1333 | # When to make a dual ? | ||
| 1334 | # If the $presentation seems to be TeX (ie. it involves #1... but not ONLY!) | ||
| 1335 | my $math_options = { # [CONSTANT] | ||
| 1336 | name => 1, meaning => 1, omcd => 1, reversion => 1, sizer => 1, alias => 1, | ||
| 1337 | role => 1, operator_role => 1, reorder => 1, dual => 1, | ||
| 1338 | mathstyle => 1, font => 1, | ||
| 1339 | scriptpos => 1, operator_scriptpos => 1, | ||
| 1340 | stretchy => 1, operator_stretchy => 1, | ||
| 1341 | beforeDigest => 1, afterDigest => 1, scope => 1, nogroup => 1, locked => 1, | ||
| 1342 | hide_content_reversion => 1 }; | ||
| 1343 | my $simpletoken_options = { # [CONSTANT] | ||
| 1344 | name => 1, meaning => 1, omcd => 1, role => 1, mathstyle => 1, | ||
| 1345 | font => 1, scriptpos => 1, scope => 1, locked => 1 }; | ||
| 1346 | |||
| 1347 | sub DefMath { | ||
| 1348 | my ($proto, $presentation, %options) = @_; | ||
| 1349 | CheckOptions("DefMath ($proto)", $math_options, %options); | ||
| 1350 | DefMathI(parsePrototype($proto), $presentation, %options); | ||
| 1351 | return; } | ||
| 1352 | |||
| 1353 | sub DefMathI { | ||
| 1354 | my ($cs, $paramlist, $presentation, %options) = @_; | ||
| 1355 | $cs = coerceCS($cs); | ||
| 1356 | # Can't defer parsing parameters since we need to know number of args! | ||
| 1357 | $paramlist = parseParameters($paramlist, $cs) if defined $paramlist && !ref $paramlist; | ||
| 1358 | my $nargs = ($paramlist ? scalar($paramlist->getParameters) : 0); | ||
| 1359 | my $csname = $cs->getString; | ||
| 1360 | my $meaning = $options{meaning}; | ||
| 1361 | my $name = $options{alias} || $csname; | ||
| 1362 | # Avoid undefs specifically, we'll be doing string comparisons | ||
| 1363 | $presentation = '' unless defined $presentation; | ||
| 1364 | $meaning = '' unless defined $meaning; | ||
| 1365 | $name =~ s/^\\//; | ||
| 1366 | $name = $options{name} if defined $options{name}; | ||
| 1367 | $name = undef if (defined $name) | ||
| 1368 | && (($name eq $presentation) || ($name eq '') | ||
| 1369 | || ($meaning eq $name)); | ||
| 1370 | $options{name} = $name; | ||
| 1371 | $options{role} = 'UNKNOWN' | ||
| 1372 | if ($nargs == 0) && !defined $options{role}; | ||
| 1373 | $options{operator_role} = 'UNKNOWN' | ||
| 1374 | if ($nargs > 0) && !defined $options{operator_role}; | ||
| 1375 | # Store some data for introspection | ||
| 1376 | defmath_introspective($cs, $paramlist, $presentation, %options); | ||
| 1377 | |||
| 1378 | # If single character, handle with a rewrite rule | ||
| 1379 | if (length($csname) == 1) { | ||
| 1380 | defmath_rewrite($cs, %options); } | ||
| 1381 | |||
| 1382 | # If the presentation is complex, and involves arguments, | ||
| 1383 | # we will create an XMDual to separate content & presentation. | ||
| 1384 | elsif ((ref $presentation eq 'CODE') | ||
| 1385 | || ((ref $presentation) && grep { $_->equals(T_PARAM) } $presentation->unlist) | ||
| 1386 | || (!(ref $presentation) && ($presentation =~ /\#\d|\\./)) | ||
| 1387 | || ((ref $presentation) && (grep { $_->isExecutable } $presentation->unlist))) { | ||
| 1388 | defmath_dual($cs, $paramlist, $presentation, %options); } | ||
| 1389 | |||
| 1390 | # EXPERIMENT: Introduce an intermediate case for simple symbols | ||
| 1391 | # Define a primitive that will create a Box with the appropriate set of XMTok attributes. | ||
| 1392 | elsif (($nargs == 0) && !grep { !$$simpletoken_options{$_} } keys %options) { | ||
| 1393 | defmath_prim($cs, $paramlist, $presentation, %options); } | ||
| 1394 | |||
| 1395 | else { | ||
| 1396 | defmath_cons($cs, $paramlist, $presentation, %options); } | ||
| 1397 | AssignValue($csname . ":locked" => 1) if $options{locked}; | ||
| 1398 | return; } | ||
| 1399 | |||
| 1400 | sub defmath_introspective { | ||
| 1401 | my ($cs, $paramlist, $presentation, %options) = @_; | ||
| 1402 | # Store some data for introspection [should be optional?] | ||
| 1403 | my $nargs = ($paramlist ? scalar($paramlist->getParameters) : 0); | ||
| 1404 | AssignValue(join("##", "math_definition", $cs->getString, $nargs, | ||
| 1405 | $options{role} || $options{operator_role} || '', $options{name} || '', | ||
| 1406 | (defined $options{meaning} ? $options{meaning} : ''), | ||
| 1407 | $STATE->getStomach->getGullet->getMouth->getSource, | ||
| 1408 | (ref $presentation ? '' : $presentation)) => 1, global => 1); | ||
| 1409 | return; } | ||
| 1410 | |||
| 1411 | sub defmath_rewrite { | ||
| 1412 | my ($cs, %options) = @_; | ||
| 1413 | my $csname = $cs->getString; | ||
| 1414 | #### $STATE->assignMathcode($csname=>0x8000, $options{scope}); } | ||
| 1415 | # No, do NOT make mathactive; screws up things like babel french, or... ? | ||
| 1416 | # EXPERIMENT: store XMTok attributes for if this char ends up a Math Token. | ||
| 1417 | # But only some DefMath options make sense! | ||
| 1418 | my $rw_options = { name => 1, meaning => 1, omcd => 1, role => 1, mathstyle => 1, stretchy => 1 }; # (well, mathstyle?) | ||
| 1419 | CheckOptions("DefMath reimplemented as DefRewrite ($csname)", $rw_options, %options); | ||
| 1420 | AssignValue('math_token_attributes_' . $csname => {%options}, 'global'); | ||
| 1421 | return; } | ||
| 1422 | |||
| 1423 | sub defmath_common_constructor_options { | ||
| 1424 | my ($cs, $presentation, %options) = @_; | ||
| 1425 | my $sizer = inferSizer($options{sizer}, $options{reversion}); | ||
| 1426 | return ( | ||
| 1427 | alias => $options{alias} || $cs->getString, | ||
| 1428 | (defined $options{reversion} ? (reversion => $options{reversion}) : ()), | ||
| 1429 | (defined $sizer ? (sizer => $sizer) : ()), | ||
| 1430 | beforeDigest => flatten(sub { requireMath($cs->getString); }, | ||
| 1431 | ($options{nogroup} ? () : (sub { $_[0]->bgroup; })), | ||
| 1432 | ($options{font} ? (sub { MergeFont(%{ $options{font} }); }) : ()), | ||
| 1433 | $options{beforeDigest}), | ||
| 1434 | afterDigest => flatten($options{afterDigest}, | ||
| 1435 | ($options{nogroup} ? () : (sub { $_[0]->egroup; }))), | ||
| 1436 | beforeConstruct => flatten($options{beforeConstruct}), | ||
| 1437 | afterConstruct => flatten($options{afterConstruct}), | ||
| 1438 | properties => { | ||
| 1439 | name => $options{name}, | ||
| 1440 | meaning => $options{meaning}, | ||
| 1441 | omcd => $options{omcd}, | ||
| 1442 | role => $options{role}, | ||
| 1443 | operator_role => $options{operator_role}, | ||
| 1444 | mathstyle => $options{mathstyle}, | ||
| 1445 | scriptpos => $options{scriptpos}, | ||
| 1446 | operator_scriptpos => $options{operator_scriptpos}, | ||
| 1447 | stretchy => $options{stretchy}, | ||
| 1448 | operator_stretchy => $options{operator_stretchy}, | ||
| 1449 | font => ($options{mathstyle} | ||
| 1450 | ? sub { LookupValue('font')->merge(mathstyle => $options{mathstyle})->specialize($presentation); } | ||
| 1451 | : sub { LookupValue('font')->specialize($presentation); }) }, | ||
| 1452 | scope => $options{scope}); } | ||
| 1453 | |||
| 1454 | # If the presentation is complex, and involves arguments, | ||
| 1455 | # we will create an XMDual to separate content & presentation. | ||
| 1456 | # This involves creating 3 control sequences: | ||
| 1457 | # \cs macro that expands into \DUAL{pres}{content} | ||
| 1458 | # \cs@content constructor creates the content branch | ||
| 1459 | # \cs@presentation macro that expands into code in the presentation branch. | ||
| 1460 | # OK, this is getting a bit out-of-hand; I can't, myself, predict whether XMDual gets involved! | ||
| 1461 | # The basic distinction seems to be whether the arguments are explicitly involved | ||
| 1462 | # in the presentation form; | ||
| 1463 | # This excludes (at least?) (OVER|UNDER)ACCENT's | ||
| 1464 | sub defmath_dual { | ||
| 1465 | my ($cs, $paramlist, $presentation, %options) = @_; | ||
| 1466 | my $csname = $cs->getString; | ||
| 1467 | my $cont_cs = T_CS($csname . "\@content"); | ||
| 1468 | my $pres_cs = T_CS($csname . "\@presentation"); | ||
| 1469 | # Make the original CS expand into a DUAL invoking a presentation macro and content constructor | ||
| 1470 | $STATE->installDefinition(LaTeXML::Core::Definition::Expandable->new($cs, $paramlist, sub { | ||
| 1471 | my ($self, @args) = @_; | ||
| 1472 | my ($cargs, $pargs) = dualize_arglist($presentation, @args); | ||
| 1473 | Invocation(T_CS('\DUAL'), | ||
| 1474 | Tokens( | ||
| 1475 | ($options{role} | ||
| 1476 | ? (T_OTHER('role'), T_OTHER('='), T_OTHER($options{role})) : ()), | ||
| 1477 | ($options{role} && $options{hide_content_reversion} ? (T_OTHER(',')) : ()), | ||
| 1478 | ($options{hide_content_reversion} | ||
| 1479 | ? (T_OTHER('hide_content_reversion'), T_OTHER('='), T_OTHER('true')) : ())), | ||
| 1480 | |||
| 1481 | Invocation($cont_cs, @$cargs), | ||
| 1482 | Invocation($pres_cs, @$pargs))->unlist; }), | ||
| 1483 | $options{scope}); | ||
| 1484 | # Make the presentation macro. | ||
| 1485 | $presentation = TokenizeInternal($presentation) unless ref $presentation; | ||
| 1486 | $STATE->installDefinition(LaTeXML::Core::Definition::Expandable->new($pres_cs, $paramlist, $presentation), | ||
| 1487 | $options{scope}); | ||
| 1488 | my $nargs = ($paramlist ? scalar($paramlist->getParameters) : 0); | ||
| 1489 | my $cons_attr = "name='#name' meaning='#meaning' omcd='#omcd' mathstyle='#mathstyle'"; | ||
| 1490 | |||
| 1491 | $STATE->installDefinition(LaTeXML::Core::Definition::Constructor->new($cont_cs, $paramlist, | ||
| 1492 | ($nargs == 0 | ||
| 1493 | ? "<ltx:XMTok $cons_attr role='#role' scriptpos='#scriptpos' stretchy='#stretchy'/>" | ||
| 1494 | : "<ltx:XMApp role='#role' scriptpos='#scriptpos'>" | ||
| 1495 | . "<ltx:XMTok $cons_attr role='#operator_role'" | ||
| 1496 | . " scriptpos='#operator_scriptpos' stretchy='#operator_stretchy'/>" | ||
| 1497 | . join('', map { "#$_" } | ||
| 1498 | ($options{reorder} ? @{ $options{reorder} } : (1 .. $nargs))) | ||
| 1499 | . "</ltx:XMApp>"), | ||
| 1500 | defmath_common_constructor_options($cs, $presentation, %options)), $options{scope}); | ||
| 1501 | return; } | ||
| 1502 | |||
| 1503 | sub defmath_prim { | ||
| 1504 | my ($cs, $paramlist, $presentation, %options) = @_; | ||
| 1505 | my $string = ToString($presentation); | ||
| 1506 | my $reqfont = $options{font} || {}; | ||
| 1507 | delete $options{locked}; | ||
| 1508 | delete $options{font}; | ||
| 1509 | $STATE->installDefinition(LaTeXML::Core::Definition::Primitive->new($cs, undef, sub { | ||
| 1510 | my ($stomach) = @_; | ||
| 1511 | my $locator = $stomach->getGullet->getLocator; | ||
| 1512 | my %properties = %options; | ||
| 1513 | my $font = LookupValue('font')->merge(%$reqfont)->specialize($string); | ||
| 1514 | my $mode = (LookupValue('IN_MATH') ? 'math' : 'text'); | ||
| 1515 | foreach my $key (keys %properties) { | ||
| 1516 | my $value = $properties{$key}; | ||
| 1517 | if (ref $value eq 'CODE') { | ||
| 1518 | $properties{$key} = &$value(); } } | ||
| 1519 | LaTeXML::Core::Box->new($string, $font, $locator, $cs, mode => $mode, %properties); })); | ||
| 1520 | return; } | ||
| 1521 | |||
| 1522 | sub defmath_cons { | ||
| 1523 | my ($cs, $paramlist, $presentation, %options) = @_; | ||
| 1524 | # do we need to do anything about digesting the presentation? | ||
| 1525 | my $qpresentation = $presentation && ToString($presentation); # Quote any constructor specials | ||
| 1526 | $qpresentation =~ s/(\#|\&|\?|\\)/\\$1/g if $presentation; | ||
| 1527 | my $end_tok = (defined $presentation ? '>' . $qpresentation . '</ltx:XMTok>' : "/>"); | ||
| 1528 | my $cons_attr = "name='#name' meaning='#meaning' omcd='#omcd' mathstyle='#mathstyle'"; | ||
| 1529 | my $nargs = ($paramlist ? scalar($paramlist->getParameters) : 0); | ||
| 1530 | $STATE->installDefinition(LaTeXML::Core::Definition::Constructor->new($cs, $paramlist, | ||
| 1531 | ($nargs == 0 | ||
| 1532 | # If trivial presentation, allow it in Text | ||
| 1533 | ? ($presentation !~ /(?:\(|\)|\\)/ | ||
| 1534 | ? "?#isMath(<ltx:XMTok role='#role' scriptpos='#scriptpos' stretchy='#stretchy'" | ||
| 1535 | . " font='#font' $cons_attr$end_tok)" | ||
| 1536 | . "($qpresentation)" | ||
| 1537 | : "<ltx:XMTok role='#role' scriptpos='#scriptpos' stretchy='#stretchy'" | ||
| 1538 | . " font='#font' $cons_attr$end_tok") | ||
| 1539 | : "<ltx:XMApp role='#role' scriptpos='#scriptpos' stretchy='#stretchy'>" | ||
| 1540 | . "<ltx:XMTok $cons_attr font='#font' role='#operator_role'" | ||
| 1541 | . " scriptpos='#operator_scriptpos' stretchy='#operator_stretchy' $end_tok" | ||
| 1542 | . join('', map { "<ltx:XMArg>#$_</ltx:XMArg>" } 1 .. $nargs) | ||
| 1543 | . "</ltx:XMApp>"), | ||
| 1544 | defmath_common_constructor_options($cs, $presentation, | ||
| 1545 | sizer => sub { | ||
| 1546 | # my $font = $_[1]->getFont || LaTeXML::Common::Font->mathDefault; | ||
| 1547 | my $font = LaTeXML::Common::Font->mathDefault; | ||
| 1548 | $font->computeStringSize($presentation); }, | ||
| 1549 | %options)), $options{scope}); | ||
| 1550 | return; } | ||
| 1551 | |||
| 1552 | #====================================================================== | ||
| 1553 | # Define a LaTeX environment | ||
| 1554 | # Note that the body of the environment is treated is the 'body' parameter in the constructor. | ||
| 1555 | my $environment_options = { # [CONSTANT] | ||
| 1556 | mode => 1, requireMath => 1, forbidMath => 1, | ||
| 1557 | properties => 1, nargs => 1, font => 1, | ||
| 1558 | beforeDigest => 1, afterDigest => 1, | ||
| 1559 | afterDigestBegin => 1, beforeDigestEnd => 1, afterDigestBody => 1, | ||
| 1560 | beforeConstruct => 1, afterConstruct => 1, | ||
| 1561 | reversion => 1, sizer => 1, scope => 1, locked => 1 }; | ||
| 1562 | |||
| 1563 | sub DefEnvironment { | ||
| 1564 | my ($proto, $replacement, %options) = @_; | ||
| 1565 | CheckOptions("DefEnvironment ($proto)", $environment_options, %options); | ||
| 1566 | ## $proto =~ s/^\{([^\}]+)\}\s*//; # Pull off the environment name as {name} | ||
| 1567 | ## my $paramlist=parseParameters($proto,"Environment $name"); | ||
| 1568 | ## my $name = $1; | ||
| 1569 | my ($name, $paramlist) = Text::Balanced::extract_bracketed($proto, '{}'); | ||
| 1570 | $name =~ s/[\{\}]//g; | ||
| 1571 | $paramlist =~ s/^\s*//; | ||
| 1572 | ## $paramlist = parseParameters($paramlist, "Environment $name"); | ||
| 1573 | DefEnvironmentI($name, $paramlist, $replacement, %options); | ||
| 1574 | return; } | ||
| 1575 | |||
| 1576 | sub DefEnvironmentI { | ||
| 1577 | my ($name, $paramlist, $replacement, %options) = @_; | ||
| 1578 | my $mode = $options{mode}; | ||
| 1579 | $name = ToString($name) if ref $name; | ||
| 1580 | ## $paramlist = parseParameters($paramlist, $name) if defined $paramlist && !ref $paramlist; | ||
| 1581 | # This is for the common case where the environment is opened by \begin{env} | ||
| 1582 | my $sizer = inferSizer($options{sizer}, $options{reversion}); | ||
| 1583 | $STATE->installDefinition(LaTeXML::Core::Definition::Constructor | ||
| 1584 | ->new(T_CS("\\begin{$name}"), $paramlist, $replacement, | ||
| 1585 | beforeDigest => flatten(($options{requireMath} ? (sub { requireMath($name); }) : ()), | ||
| 1586 | ($options{forbidMath} ? (sub { forbidMath($name); }) : ()), | ||
| 1587 | sub { $_[0]->bgroup; }, | ||
| 1588 | sub { my $b = LookupValue('@environment@' . $name . '@atbegin'); | ||
| 1589 | ($b ? Digest(@$b) : ()); }, | ||
| 1590 | ($mode ? (sub { $_[0]->setMode($mode); }) : ()), | ||
| 1591 | sub { AssignValue(current_environment => $name); | ||
| 1592 | DefMacroI('\@currenvir', undef, $name); }, | ||
| 1593 | ($options{font} ? (sub { MergeFont(%{ $options{font} }); }) : ()), | ||
| 1594 | $options{beforeDigest}), | ||
| 1595 | afterDigest => flatten($options{afterDigestBegin}), | ||
| 1596 | afterDigestBody => flatten($options{afterDigestBody}), | ||
| 1597 | beforeConstruct => flatten(sub { $STATE->pushFrame; }, $options{beforeConstruct}), | ||
| 1598 | # Curiously, it's the \begin whose afterConstruct gets called. | ||
| 1599 | afterConstruct => flatten($options{afterConstruct}, sub { $STATE->popFrame; }), | ||
| 1600 | nargs => $options{nargs}, | ||
| 1601 | captureBody => 1, | ||
| 1602 | properties => $options{properties} || {}, | ||
| 1603 | (defined $options{reversion} ? (reversion => $options{reversion}) : ()), | ||
| 1604 | (defined $sizer ? (sizer => $sizer) : ()), | ||
| 1605 | ), $options{scope}); | ||
| 1606 | $STATE->installDefinition(LaTeXML::Core::Definition::Constructor | ||
| 1607 | ->new(T_CS("\\end{$name}"), "", "", | ||
| 1608 | beforeDigest => flatten($options{beforeDigestEnd}, | ||
| 1609 | sub { my $e = LookupValue('@environment@' . $name . '@atend'); | ||
| 1610 | ($e ? Digest(@$e) : ()); }, | ||
| 1611 | ), | ||
| 1612 | afterDigest => flatten($options{afterDigest}, | ||
| 1613 | sub { my $env = LookupValue('current_environment'); | ||
| 1614 | if (!$env || ($name ne $env)) { | ||
| 1615 | my @lines = (); | ||
| 1616 | my $nf = $STATE->getFrameDepth; | ||
| 1617 | for (my $f = 0 ; $f <= $nf ; $f++) { # Get currently open environments & locators | ||
| 1618 | if (my $e = $STATE->isValueBound('current_environment', $f) | ||
| 1619 | && $STATE->valueInFrame('current_environment', $f)) { | ||
| 1620 | my $locator = ToString($STATE->valueInFrame('groupInitiatorLocator', $f)); | ||
| 1621 | push(@lines, $e . ' ' . $locator); } } | ||
| 1622 | Error('unexpected', "\\end{$name}", $_[0], | ||
| 1623 | "Can't close environment $name;", "Current are:", @lines); } | ||
| 1624 | return; }, | ||
| 1625 | sub { $_[0]->egroup; }, | ||
| 1626 | ), | ||
| 1627 | ), $options{scope}); | ||
| 1628 | # For the uncommon case opened by \csname env\endcsname | ||
| 1629 | $STATE->installDefinition(LaTeXML::Core::Definition::Constructor | ||
| 1630 | ->new(T_CS("\\$name"), $paramlist, $replacement, | ||
| 1631 | beforeDigest => flatten(($options{requireMath} ? (sub { requireMath($name); }) : ()), | ||
| 1632 | ($options{forbidMath} ? (sub { forbidMath($name); }) : ()), | ||
| 1633 | ($mode ? (sub { $_[0]->beginMode($mode); }) : ()), | ||
| 1634 | ($options{font} ? (sub { MergeFont(%{ $options{font} }); }) : ()), | ||
| 1635 | $options{beforeDigest}), | ||
| 1636 | afterDigest => flatten($options{afterDigestBegin}), | ||
| 1637 | afterDigestBody => flatten($options{afterDigestBody}), | ||
| 1638 | beforeConstruct => flatten(sub { $STATE->pushFrame; }, $options{beforeConstruct}), | ||
| 1639 | # Curiously, it's the \begin whose afterConstruct gets called. | ||
| 1640 | afterConstruct => flatten($options{afterConstruct}, sub { $STATE->popFrame; }), | ||
| 1641 | nargs => $options{nargs}, | ||
| 1642 | captureBody => T_CS("\\end$name"), # Required to capture!! | ||
| 1643 | properties => $options{properties} || {}, | ||
| 1644 | (defined $options{reversion} ? (reversion => $options{reversion}) : ()), | ||
| 1645 | (defined $sizer ? (sizer => $sizer) : ()), | ||
| 1646 | ), $options{scope}); | ||
| 1647 | $STATE->installDefinition(LaTeXML::Core::Definition::Constructor | ||
| 1648 | ->new(T_CS("\\end$name"), "", "", | ||
| 1649 | beforeDigest => flatten($options{beforeDigestEnd}), | ||
| 1650 | afterDigest => flatten($options{afterDigest}, | ||
| 1651 | ($mode ? (sub { $_[0]->endMode($mode); }) : ())), | ||
| 1652 | ), $options{scope}); | ||
| 1653 | if ($options{locked}) { | ||
| 1654 | AssignValue("\\begin{$name}:locked" => 1); | ||
| 1655 | AssignValue("\\end{$name}:locked" => 1); | ||
| 1656 | AssignValue("\\$name:locked" => 1); | ||
| 1657 | AssignValue("\\end$name:locked" => 1); } | ||
| 1658 | return; } | ||
| 1659 | |||
| 1660 | #====================================================================== | ||
| 1661 | # Declaring and Adjusting the Document Model. | ||
| 1662 | #====================================================================== | ||
| 1663 | |||
| 1664 | # Specify the properties of a Node tag. | ||
| 1665 | my $tag_options = { # [CONSTANT] | ||
| 1666 | autoOpen => 1, autoClose => 1, afterOpen => 1, afterClose => 1, | ||
| 1667 | 'afterOpen:early' => 1, 'afterClose:early' => 1, | ||
| 1668 | 'afterOpen:late' => 1, 'afterClose:late' => 1 }; | ||
| 1669 | my $tag_prepend_options = { # [CONSTANT] | ||
| 1670 | 'afterOpen:early' => 1, 'afterClose:early' => 1 }; | ||
| 1671 | my $tag_append_options = { # [CONSTANT] | ||
| 1672 | 'afterOpen' => 1, 'afterClose' => 1, | ||
| 1673 | 'afterOpen:late' => 1, 'afterClose:late' => 1 }; | ||
| 1674 | |||
| 1675 | sub Tag { | ||
| 1676 | my ($tag, %properties) = @_; | ||
| 1677 | CheckOptions("Tag ($tag)", $tag_options, %properties); | ||
| 1678 | my $model = $STATE->getModel; | ||
| 1679 | AssignMapping('TAG_PROPERTIES', $tag => {}) unless LookupMapping('TAG_PROPERTIES', $tag); | ||
| 1680 | my $props = LookupMapping('TAG_PROPERTIES', $tag); | ||
| 1681 | foreach my $key (keys %properties) { | ||
| 1682 | my $new = $properties{$key}; | ||
| 1683 | my $old = $$props{$key}; | ||
| 1684 | # These keys accumulate information which should not carry over daemon frames. | ||
| 1685 | if ($$tag_prepend_options{$key}) { | ||
| 1686 | $new = flatten($new, $old); } | ||
| 1687 | elsif ($$tag_append_options{$key}) { | ||
| 1688 | $new = flatten($old, $new); } | ||
| 1689 | $$props{$key} = $new; } | ||
| 1690 | return; } | ||
| 1691 | |||
| 1692 | sub DocType { | ||
| 1693 | my ($rootelement, $pubid, $sysid, %namespaces) = @_; | ||
| 1694 | my $model = $STATE->getModel; | ||
| 1695 | $model->setDocType($rootelement, $pubid, $sysid); | ||
| 1696 | foreach my $prefix (keys %namespaces) { | ||
| 1697 | $model->registerDocumentNamespace($prefix => $namespaces{$prefix}); } | ||
| 1698 | return; } | ||
| 1699 | |||
| 1700 | # What verb here? Set, Choose,... | ||
| 1701 | sub RelaxNGSchema { | ||
| 1702 | my ($schema, %namespaces) = @_; | ||
| 1703 | my $model = $STATE->getModel; | ||
| 1704 | $model->setRelaxNGSchema($schema,); | ||
| 1705 | foreach my $prefix (keys %namespaces) { | ||
| 1706 | $model->registerDocumentNamespace($prefix => $namespaces{$prefix}); } | ||
| 1707 | return; } | ||
| 1708 | |||
| 1709 | sub RegisterNamespace { | ||
| 1710 | my ($prefix, $namespace) = @_; | ||
| 1711 | $STATE->getModel->registerNamespace($prefix => $namespace); | ||
| 1712 | return; } | ||
| 1713 | |||
| 1714 | sub RegisterDocumentNamespace { | ||
| 1715 | my ($prefix, $namespace) = @_; | ||
| 1716 | $STATE->getModel->registerDocumentNamespace($prefix => $namespace); | ||
| 1717 | return; } | ||
| 1718 | |||
| 1719 | #====================================================================== | ||
| 1720 | # Package, Class and File Loading | ||
| 1721 | #====================================================================== | ||
| 1722 | |||
| 1723 | # Does this test even make sense (or can it?) | ||
| 1724 | # Shouldn't this more likely be dependent on the context? | ||
| 1725 | # Ah, but what about \InputFileIfExists type stuff... | ||
| 1726 | # should we assume a raw type can be processed if being read from within a raw type???? | ||
| 1727 | # yeah, that sounds about right... | ||
| 1728 | my %definition_name = ( # [CONSTANT] | ||
| 1729 | sty => 'package', cls => 'class', clo => 'class options', | ||
| 1730 | 'cnf' => 'configuration', 'cfg' => 'configuration', | ||
| 1731 | 'ldf' => 'language definitions', 'def' => 'definitions', 'dfu' => 'definitions'); | ||
| 1732 | |||
| 1733 | sub pathname_is_raw { | ||
| 1734 | my ($pathname) = @_; | ||
| 1735 | return ($pathname =~ /\.(tex|pool|sty|cls|clo|cnf|cfg|ldf|def|dfu)$/); } | ||
| 1736 | |||
| 1737 | my $findfile_options = { # [CONSTANT] | ||
| 1738 | type => 1, notex => 1, noltxml => 1 }; | ||
| 1739 | |||
| 1740 | sub FindFile { | ||
| 1741 | my ($file, %options) = @_; | ||
| 1742 | $file = ToString($file); | ||
| 1743 | if ($options{raw}) { | ||
| 1744 | delete $options{raw}; | ||
| 1745 | Warn('deprecated', 'raw', $STATE->getStomach->getGullet, | ||
| 1746 | "FindFile option raw is deprecated; it is not needed"); } | ||
| 1747 | CheckOptions("FindFile ($file)", $findfile_options, %options); | ||
| 1748 | if (pathname_is_literaldata($file)) { # If literal protocol return immediately (unless notex!) | ||
| 1749 | return ($options{notex} ? undef : $file); } | ||
| 1750 | # If a known special protocol return immediately | ||
| 1751 | elsif (pathname_is_literaldata($file) || pathname_is_url($file)) { | ||
| 1752 | return $file; } | ||
| 1753 | # Otherwise, it's some kind of "real" file, and we might have to search for it | ||
| 1754 | if ($options{type}) { # Specific type requested? Search for it. | ||
| 1755 | # Add the extension, if it isn't already there. | ||
| 1756 | $file = $file . "." . $options{type} unless $file =~ /\.\Q$options{type}\E$/; | ||
| 1757 | return FindFile_aux($file, %options); } | ||
| 1758 | # If no type given, we MAY expect .tex, or maybe NOT!! | ||
| 1759 | elsif ($file =~ /\.tex$/) { # No requested type, then .tex; Of course, it may already have it! | ||
| 1760 | return FindFile_aux($file, %options); } | ||
| 1761 | else { | ||
| 1762 | return FindFile_aux("$file.tex", %options) || FindFile_aux($file, %options); } } | ||
| 1763 | |||
| 1764 | sub FindFile_aux { | ||
| 1765 | my ($file, %options) = @_; | ||
| 1766 | my $path; | ||
| 1767 | # If cached, return simple path (it's a key into the cache) | ||
| 1768 | if (defined LookupValue($file . '_contents')) { | ||
| 1769 | return $file; } | ||
| 1770 | if (pathname_is_absolute($file)) { # And if we've got an absolute path, | ||
| 1771 | if (!$options{noltxml}) { | ||
| 1772 | return $file . '.ltxml' if -f ($file . '.ltxml'); } # No need to search, just check if it exists. | ||
| 1773 | return $file if -f $file; # No need to search, just check if it exists. | ||
| 1774 | return; } # otherwise we're never going to find it. | ||
| 1775 | elsif (pathname_is_nasty($file)) { # If it is a nasty filename, we won't touch it. | ||
| 1776 | return; } # we DO NOT want to pass this to kpathse or such! | ||
| 1777 | |||
| 1778 | # Note that the strategy is complicated by the fact that | ||
| 1779 | # (1) we prefer .ltxml bindings, if present | ||
| 1780 | # (2) those MAY be present in kpsewhich's DB (although our searchpaths take precedence!) | ||
| 1781 | # (3) BUT we want to avoid kpsewhich if we can, since it's slower | ||
| 1782 | # (4) depending on switches we may EXCLUDE .ltxml OR raw tex OR allow both. | ||
| 1783 | my $paths = LookupValue('SEARCHPATHS'); | ||
| 1784 | my $urlbase = LookupValue('URLBASE'); | ||
| 1785 | my $nopaths = LookupValue('REMOTE_REQUEST'); | ||
| 1786 | my $ltxml_paths = $nopaths ? [] : $paths; | ||
| 1787 | # If we're looking for ltxml, look within our paths & installation first (faster than kpse) | ||
| 1788 | if (!$options{noltxml}) { | ||
| 1789 | if ($path = pathname_find("$file.ltxml", paths => $ltxml_paths, installation_subdir => 'Package')) { | ||
| 1790 | return $path; } | ||
| 1791 | elsif ($path = FindFile_fallback($file, $ltxml_paths, %options)) { | ||
| 1792 | return $path; } } | ||
| 1793 | # If we're looking for TeX, look within our paths & installation first (faster than kpse) | ||
| 1794 | if (!$options{notex} | ||
| 1795 | && ($path = pathname_find($file, paths => $paths))) { | ||
| 1796 | return $path; } | ||
| 1797 | # Otherwise, pass on to kpsewhich | ||
| 1798 | # Depending on flags, maybe search for ltxml in texmf or for plain tex in ours! | ||
| 1799 | # The main point, though, is to we make only ONE (more) call. | ||
| 1800 | return if grep { pathname_is_nasty($_) } @$paths; # SECURITY! No nasty paths in cmdline | ||
| 1801 | # Do we need to sanitize these environment variables? | ||
| 1802 | my @candidates = (((!$options{noltxml} && !$nopaths) ? ("$file.ltxml") : ()), | ||
| 1803 | (!$options{notex} ? ($file) : ())); | ||
| 1804 | local $ENV{TEXINPUTS} = join($Config::Config{'path_sep'}, | ||
| 1805 | @$paths, $ENV{TEXINPUTS} || $Config::Config{'path_sep'}); | ||
| 1806 | if (my $result = pathname_kpsewhich(@candidates)) { | ||
| 1807 | return (-f $result ? $result : undef); } | ||
| 1808 | if ($urlbase && ($path = url_find($file, urlbase => $urlbase))) { | ||
| 1809 | return $path; } | ||
| 1810 | return; } | ||
| 1811 | |||
| 1812 | sub FindFile_fallback { | ||
| 1813 | my ($file, $ltxml_paths, %options) = @_; | ||
| 1814 | # Supported: | ||
| 1815 | # Numeric suffixes (version nums, dates) with optional separators | ||
| 1816 | my $fallback_file = $file; | ||
| 1817 | if ($fallback_file =~ s/\.(sty|cls)$//) { | ||
| 1818 | my $ltxtype = $1; | ||
| 1819 | my $discard = ""; | ||
| 1820 | if ($fallback_file =~ s/([-_](?:arxiv|conference|workshop))$//) { | ||
| 1821 | # arxiv-specific suffixes, maybe move those out to an extension package? | ||
| 1822 | $discard = $1; | ||
| 1823 | } | ||
| 1824 | # TODO: If we want a Whitelist hash table -- add it here, before further regexing. | ||
| 1825 | if ($fallback_file =~ s/([-_]?v?[-_\d]+)$//) { | ||
| 1826 | $discard = "$1$discard"; | ||
| 1827 | } | ||
| 1828 | if ($discard) { # we had something to discard, so a new query is needed | ||
| 1829 | my $fallback_query = "$fallback_file.$ltxtype"; | ||
| 1830 | if (my $path = pathname_find("$fallback_query.ltxml", paths => $ltxml_paths, installation_subdir => 'Package')) { | ||
| 1831 | Info('fallback', $file, $STATE->getStomach->getGullet, | ||
| 1832 | "Interpreted $discard as a versioned package/class name, falling back to generic $fallback_query\n"); | ||
| 1833 | return $path; } } } | ||
| 1834 | return; } | ||
| 1835 | |||
| 1836 | sub pathname_is_nasty { | ||
| 1837 | my ($pathname) = @_; | ||
| 1838 | return $pathname =~ /[^\w\-_\+\=\/\\\.~\:\s]/; } | ||
| 1839 | |||
| 1840 | sub maybeReportSearchPaths { | ||
| 1841 | if (LookupValue('SEARCHPATHS_REPORTED')) { | ||
| 1842 | return (); } | ||
| 1843 | else { | ||
| 1844 | AssignValue('SEARCHPATHS_REPORTED' => 1, 'global'); | ||
| 1845 | return ("search paths are " . join(', ', @{ LookupValue('SEARCHPATHS') })); } } | ||
| 1846 | |||
| 1847 | my $inputcontent_options = { # [CONSTANT] | ||
| 1848 | noerror => 1, type => 1 }; | ||
| 1849 | |||
| 1850 | sub InputContent { | ||
| 1851 | my ($request, %options) = @_; | ||
| 1852 | CheckOptions("InputContent ($request)", $inputcontent_options, %options); | ||
| 1853 | if (my $path = FindFile($request, type => $options{type}, noltxml => 1)) { | ||
| 1854 | loadTeXContent($path); } | ||
| 1855 | elsif (!$options{noerror}) { | ||
| 1856 | # Consider it an error if we can't find a file of Content (in contrast to Definitions) | ||
| 1857 | Error('missing_file', $request, $STATE->getStomach->getGullet, | ||
| 1858 | "Can't find TeX file $request", | ||
| 1859 | maybeReportSearchPaths()); } | ||
| 1860 | return; } | ||
| 1861 | |||
| 1862 | # This is essentially the \input equivalent; | ||
| 1863 | # we are most likely expecting to get actual content, | ||
| 1864 | # (possibly with definitions included, as well) | ||
| 1865 | # but might actually be getting pure definitions, | ||
| 1866 | # (like a proper style file) | ||
| 1867 | # in which case we may really want to load a latexml binding. | ||
| 1868 | # Note that generic style files (non-latex) often have a .tex extension. | ||
| 1869 | # But we may have implemented a .sty.ltxml, so we override the .tex. | ||
| 1870 | # Is this actually safe, or should we be explicilty providing .tex.ltxml ? | ||
| 1871 | |||
| 1872 | my $input_options = {}; # [CONSTANT] | ||
| 1873 | |||
| 1874 | sub Input { | ||
| 1875 | my ($request, %options) = @_; | ||
| 1876 | $request = ToString($request); | ||
| 1877 | CheckOptions("Input ($request)", $input_options, %options); | ||
| 1878 | # HEURISTIC! First check if equivalent style file, but only under very specific circumstances | ||
| 1879 | if (pathname_is_literaldata($request)) { | ||
| 1880 | my ($dir, $name, $type) = pathname_split($request); | ||
| 1881 | my $file = $name; $file .= '.' . $type if $type; | ||
| 1882 | my $path; | ||
| 1883 | # Firstly, check if we are going to OVERRIDE the requested raw .tex file | ||
| 1884 | # with a latexml binding to a style file. | ||
| 1885 | if ((!$dir) && (!$type || ($type eq 'tex')) # No SPECIFIC directory, but a raw tex file. | ||
| 1886 | # AND, in preamble; SHOULD be style file, OR also if we can't find the raw file. | ||
| 1887 | && (LookupValue('inPreamble') || !FindFile($file)) | ||
| 1888 | && ($path = FindFile($name, type => 'sty', notex => 1))) { # AND there IS such a style file | ||
| 1889 | Info('ignore', $request, $STATE->getStomach->getGullet, | ||
| 1890 | "Ignoring input of tex $request, using package $name instead"); | ||
| 1891 | RequirePackage($name); # Then override, assuming we'll find $name as a package file! | ||
| 1892 | return; } } | ||
| 1893 | # Next special case: If we were currently reading a "known" style or binding file, | ||
| 1894 | # then this file, even if .tex, must also be definitions rather than content.!!(?) | ||
| 1895 | if (LookupValue('INTERPRETING_DEFINITIONS')) { | ||
| 1896 | InputDefinitions($request); } | ||
| 1897 | elsif (my $path = FindFile($request)) { # Found something plausible.. | ||
| 1898 | my $type = (pathname_is_literaldata($path) ? 'tex' : pathname_type($path)); | ||
| 1899 | |||
| 1900 | # Should we be doing anything about options in the next 2 cases?..... I kinda think not, but? | ||
| 1901 | if ($type eq 'ltxml') { # it's a LaTeXML binding. | ||
| 1902 | loadLTXML($request, $path); } | ||
| 1903 | # Else some sort of "known" definitions type file, but not simply 'tex' | ||
| 1904 | elsif (($type ne 'tex') && (pathname_is_raw($path))) { | ||
| 1905 | loadTeXDefinitions($request, $path); } | ||
| 1906 | else { | ||
| 1907 | loadTeXContent($path); } } | ||
| 1908 | else { # Couldn't find anything? | ||
| 1909 | $STATE->noteStatus(missing => $request); | ||
| 1910 | # We presumably are trying to input Content; an error if we can't find it (contrast to Definitions) | ||
| 1911 | Error('missing_file', $request, $STATE->getStomach->getGullet, | ||
| 1912 | "Can't find TeX file $request", | ||
| 1913 | maybeReportSearchPaths()); } | ||
| 1914 | return; } | ||
| 1915 | |||
| 1916 | # Pass in the "requested path" to the next two, since that's what gets | ||
| 1917 | # recorded as having been loaded (by \@ifpackageloade, eg). | ||
| 1918 | sub loadLTXML { | ||
| 1919 | my ($request, $pathname) = @_; | ||
| 1920 | # Note: $type will typically be ltxml and $name will include the .sty, .cls or whatever. | ||
| 1921 | # Note: we're NOT expecting (allowing?) either literal nor remote data objects here. | ||
| 1922 | if (my $p = pathname_is_literaldata($pathname) || pathname_is_url($pathname)) { | ||
| 1923 | Error('misdefined', 'loadLTXML', $STATE->getStomach->getGullet, | ||
| 1924 | "You can't load LaTeXML binding using protocol $p"); | ||
| 1925 | return; } | ||
| 1926 | my ($dir, $name, $type) = pathname_split($pathname); | ||
| 1927 | # Don't load if the requested path was loaded (with or without the .ltxml) | ||
| 1928 | # We want to check against the original request, but WITH the type | ||
| 1929 | $request .= '.' . $type unless $request =~ /\Q.$type\E$/; # make sure the .ltxml is added here | ||
| 1930 | my $trequest = $request; $trequest =~ s/\.ltxml$//; # and NOT added here! | ||
| 1931 | return if LookupValue($request . '_loaded') || LookupValue($trequest . '_loaded'); | ||
| 1932 | # Note (only!) that the ltxml version of this was loaded; still could load raw tex! | ||
| 1933 | AssignValue($request . '_loaded' => 1, 'global'); | ||
| 1934 | |||
| 1935 | $STATE->getStomach->getGullet->readingFromMouth(LaTeXML::Core::Mouth::Binding->new($pathname), sub { | ||
| 1936 | do $pathname; | ||
| 1937 | Fatal('die', $pathname, $STATE->getStomach->getGullet, | ||
| 1938 | "File $pathname had an error:\n $@") if $@; | ||
| 1939 | # If we've opened anything, we should read it in completely. | ||
| 1940 | # But we'll assume that anything opened has already been processed by loadTeXDefinitions. | ||
| 1941 | }); | ||
| 1942 | return; } | ||
| 1943 | |||
| 1944 | sub loadTeXDefinitions { | ||
| 1945 | my ($request, $pathname) = @_; | ||
| 1946 | if (!pathname_is_literaldata($pathname)) { # We can't analyze literal data's pathnames! | ||
| 1947 | my ($dir, $name, $type) = pathname_split($pathname); | ||
| 1948 | # Don't load if we've already loaded it before. | ||
| 1949 | # Note that we'll still load it if we've already loaded only the ltxml version | ||
| 1950 | # since someone's presumably asking _explicitly_ for the raw TeX version. | ||
| 1951 | # It's probably even the ltxml version is asking for it!! | ||
| 1952 | # Of course, now it will be marked and wont get reloaded! | ||
| 1953 | return if LookupValue($request . '_loaded'); | ||
| 1954 | AssignValue($request . '_loaded' => 1, 'global'); } | ||
| 1955 | |||
| 1956 | my $stomach = $STATE->getStomach; | ||
| 1957 | # Note that we are reading definitions (and recursive input is assumed also definitions) | ||
| 1958 | my $was_interpreting = LookupValue('INTERPRETING_DEFINITIONS'); | ||
| 1959 | # And that if we're interpreting this TeX file of definitions, | ||
| 1960 | # we probably should interpret any TeX files IT loads. | ||
| 1961 | my $was_including_styles = LookupValue('INCLUDE_STYLES'); | ||
| 1962 | AssignValue('INTERPRETING_DEFINITIONS' => 1); | ||
| 1963 | # If we're reading in these definitions, probaly will accept included ones? | ||
| 1964 | # (but not forbid ltxml ?) | ||
| 1965 | AssignValue('INCLUDE_STYLES' => 1); | ||
| 1966 | # When set, this variable allows redefinitions of locked defns. | ||
| 1967 | # It is set in before/after methods to allow local rebinding of commands | ||
| 1968 | # but loading of sources & bindings is typically done in before/after methods of constructors! | ||
| 1969 | # This re-locks defns during reading of TeX packages. | ||
| 1970 | local $LaTeXML::Core::State::UNLOCKED = 0; | ||
| 1971 | $stomach->getGullet->readingFromMouth( | ||
| 1972 | LaTeXML::Core::Mouth->create($pathname, | ||
| 1973 | fordefinitions => 1, notes => 1, | ||
| 1974 | content => LookupValue($pathname . '_contents')), | ||
| 1975 | sub { | ||
| 1976 | my ($gullet) = @_; | ||
| 1977 | my $token; | ||
| 1978 | while ($token = $gullet->readXToken(0)) { | ||
| 1979 | next if $token->equals(T_SPACE); | ||
| 1980 | $stomach->invokeToken($token); } }); | ||
| 1981 | AssignValue('INTERPRETING_DEFINITIONS' => $was_interpreting); | ||
| 1982 | AssignValue('INCLUDE_STYLES' => $was_including_styles); | ||
| 1983 | return; } | ||
| 1984 | |||
| 1985 | sub loadTeXContent { | ||
| 1986 | my ($pathname) = @_; | ||
| 1987 | my $gullet = $STATE->getStomach->getGullet; | ||
| 1988 | # If there is a file-specific declaration file (name.latexml), load it first! | ||
| 1989 | my $file = $pathname; | ||
| 1990 | $file =~ s/\.tex//; | ||
| 1991 | if (my $conf = !pathname_is_literaldata($pathname) | ||
| 1992 | && pathname_find("$file.latexml", paths => LookupValue('SEARCHPATHS'))) { | ||
| 1993 | loadLTXML($conf, $conf); } | ||
| 1994 | $gullet->openMouth(LaTeXML::Core::Mouth->create($pathname, notes => 1, | ||
| 1995 | content => LookupValue($pathname . '_contents')), 0); | ||
| 1996 | return; } | ||
| 1997 | |||
| 1998 | #====================================================================== | ||
| 1999 | # Option Handling for Packages and Classes | ||
| 2000 | |||
| 2001 | # Declare an option for the current package or class | ||
| 2002 | # If $option is undef, it is the default. | ||
| 2003 | # $code can be a sub (as a primitive), or a string to be expanded. | ||
| 2004 | # (effectively a macro) | ||
| 2005 | |||
| 2006 | sub DeclareOption { | ||
| 2007 | my ($option, $code) = @_; | ||
| 2008 | $option = ToString($option) if ref $option; | ||
| 2009 | PushValue('@declaredoptions', $option) if $option; | ||
| 2010 | my $cs = ($option ? '\ds@' . $option : '\default@ds'); | ||
| 2011 | # print STDERR "Declaring option: ".($option ? $option : '<default>')."\n"; | ||
| 2012 | if ((!defined $code) || (ref $code eq 'CODE')) { | ||
| 2013 | DefPrimitiveI($cs, undef, $code); } | ||
| 2014 | else { | ||
| 2015 | DefMacroI($cs, undef, $code); } | ||
| 2016 | return; } | ||
| 2017 | |||
| 2018 | # Pass the sequence of @options to the package $name (if $ext is 'sty'), | ||
| 2019 | # or class $name (if $ext is 'cls'). | ||
| 2020 | sub PassOptions { | ||
| 2021 | my ($name, $ext, @options) = @_; | ||
| 2022 | PushValue('opt@' . $name . '.' . $ext, map { ToString($_) } @options); | ||
| 2023 | # print STDERR "Passing to $name.$ext options: " . join(', ', @options) . "\n"; | ||
| 2024 | return; } | ||
| 2025 | |||
| 2026 | # Process the options passed to the currently loading package or class. | ||
| 2027 | # If inorder=>1, they are processed in the order given (like \ProcessOptions*), | ||
| 2028 | # otherwise, they are processed in the order declared. | ||
| 2029 | # Unless noundefine=>1 (like for \ExecuteOptions), all option definitions | ||
| 2030 | # undefined after execution. | ||
| 2031 | my $processoptions_options = { # [CONSTANT] | ||
| 2032 | inorder => 1 }; | ||
| 2033 | |||
| 2034 | sub ProcessOptions { | ||
| 2035 | my (%options) = @_; | ||
| 2036 | CheckOptions("ProcessOptions", $processoptions_options, %options); | ||
| 2037 | my $name = $STATE->lookupDefinition(T_CS('\@currname')) && ToString(Expand(T_CS('\@currname'))); | ||
| 2038 | my $ext = $STATE->lookupDefinition(T_CS('\@currext')) && ToString(Expand(T_CS('\@currext'))); | ||
| 2039 | my @declaredoptions = @{ LookupValue('@declaredoptions') }; | ||
| 2040 | my @curroptions = @{ (defined($name) && defined($ext) | ||
| 2041 | && LookupValue('opt@' . $name . '.' . $ext)) || [] }; | ||
| 2042 | my @classoptions = @{ LookupValue('class_options') || [] }; | ||
| 2043 | # print STDERR "\nProcessOptions for $name.$ext\n" | ||
| 2044 | # . " declared: " . join(',', @declaredoptions) . "\n" | ||
| 2045 | # . " provided: " . join(',', @curroptions) . "\n" | ||
| 2046 | # . " class: " . join(',', @classoptions) . "\n"; | ||
| 2047 | |||
| 2048 | my $defaultcs = T_CS('\default@ds'); | ||
| 2049 | # Execute options in declared order (unless \ProcessOptions*) | ||
| 2050 | |||
| 2051 | if ($options{inorder}) { # Execute options in the order passed in (eg. \ProcessOptions*) | ||
| 2052 | foreach my $option (@classoptions) { # process global options, but no error | ||
| 2053 | if (executeOption_internal($option)) { } } | ||
| 2054 | |||
| 2055 | foreach my $option (@curroptions) { | ||
| 2056 | if (executeOption_internal($option)) { } | ||
| 2057 | elsif (executeDefaultOption_internal($option)) { } } } | ||
| 2058 | else { # Execute options in declared order (eg. \ProcessOptions) | ||
| 2059 | foreach my $option (@declaredoptions) { | ||
| 2060 | if (grep { $option eq $_ } @curroptions, @classoptions) { | ||
| 2061 | @curroptions = grep { $option ne $_ } @curroptions; # Remove it, since it's been handled. | ||
| 2062 | executeOption_internal($option); } } | ||
| 2063 | # Now handle any remaining options (eg. default options), in the given order. | ||
| 2064 | foreach my $option (@curroptions) { | ||
| 2065 | executeDefaultOption_internal($option); } } | ||
| 2066 | # Now, undefine the handlers? | ||
| 2067 | foreach my $option (@declaredoptions) { | ||
| 2068 | Let('\ds@' . $option, '\relax'); } | ||
| 2069 | return; } | ||
| 2070 | |||
| 2071 | sub executeOption_internal { | ||
| 2072 | my ($option) = @_; | ||
| 2073 | my $cs = T_CS('\ds@' . $option); | ||
| 2074 | if ($STATE->lookupDefinition($cs)) { | ||
| 2075 | # print STDERR "\nPROCESS OPTION $option\n"; | ||
| 2076 | DefMacroI('\CurrentOption', undef, $option); | ||
| 2077 | AssignValue('@unusedoptionlist', | ||
| 2078 | [grep { $_ ne $option } @{ LookupValue('@unusedoptionlist') || [] }]); | ||
| 2079 | Digest($cs); | ||
| 2080 | return 1; } | ||
| 2081 | else { | ||
| 2082 | return; } } | ||
| 2083 | |||
| 2084 | sub executeDefaultOption_internal { | ||
| 2085 | my ($option) = @_; | ||
| 2086 | # print STDERR "\nPROCESS DEFAULT OPTION $option\n"; | ||
| 2087 | # presumably should NOT remove from @unusedoptionlist ? | ||
| 2088 | DefMacroI('\CurrentOption', undef, $option); | ||
| 2089 | Digest(T_CS('\default@ds')); | ||
| 2090 | return 1; } | ||
| 2091 | |||
| 2092 | sub ExecuteOptions { | ||
| 2093 | my (@options) = @_; | ||
| 2094 | my %unhandled = (); | ||
| 2095 | foreach my $option (@options) { | ||
| 2096 | if (executeOption_internal($option)) { } | ||
| 2097 | else { | ||
| 2098 | $unhandled{$option} = 1; } } | ||
| 2099 | foreach my $option (keys %unhandled) { | ||
| 2100 | Info('unexpected', $option, $STATE->getStomach->getGullet, | ||
| 2101 | "Unexpected options passed to ExecuteOptions '$option'"); } | ||
| 2102 | return; } | ||
| 2103 | |||
| 2104 | sub resetOptions { | ||
| 2105 | AssignValue('@declaredoptions', []); | ||
| 2106 | Let('\default@ds', | ||
| 2107 | (ToString(Expand(T_CS('\@currext'))) eq 'cls' | ||
| 2108 | ? '\OptionNotUsed' : '\@unknownoptionerror')); | ||
| 2109 | return; } | ||
| 2110 | |||
| 2111 | sub AddToMacro { | ||
| 2112 | my ($cs, @tokens) = @_; | ||
| 2113 | $cs = T_CS($cs) unless ref $cs; | ||
| 2114 | @tokens = map { (ref $_ ? $_ : TokenizeInternal($_)) } @tokens; | ||
| 2115 | # Needs error checking! | ||
| 2116 | my $defn = $STATE->lookupDefinition($cs); | ||
| 2117 | if (!defined $defn || !$defn->isExpandable) { | ||
| 2118 | Warn('unexpected', $cs, $STATE->getStomach->getGullet, | ||
| 2119 | ToString($cs) . " is not an expandable control sequence", "Ignoring addition"); } | ||
| 2120 | else { | ||
| 2121 | DefMacroI($cs, undef, Tokens($defn->getExpansion->unlist, | ||
| 2122 | map { $_->unlist } map { (ref $_ ? $_ : TokenizeInternal($_)) } @tokens), | ||
| 2123 | scope => 'global'); } | ||
| 2124 | return; } | ||
| 2125 | |||
| 2126 | #====================================================================== | ||
| 2127 | my $inputdefinitions_options = { # [CONSTANT] | ||
| 2128 | options => 1, withoptions => 1, handleoptions => 1, | ||
| 2129 | type => 1, as_class => 1, noltxml => 1, notex => 1, noerror => 1, after => 1 }; | ||
| 2130 | # options=>[options...] | ||
| 2131 | # withoptions=>boolean : pass options from calling class/package | ||
| 2132 | # after=>code or tokens or string as $name.$type-h@@k macro. (executed after the package is loaded) | ||
| 2133 | # Returns the path that was loaded, or undef, if none found. | ||
| 2134 | sub InputDefinitions { | ||
| 2135 | my ($name, %options) = @_; | ||
| 2136 | $name = ToString($name) if ref $name; | ||
| 2137 | $name =~ s/^\s*//; $name =~ s/\s*$//; | ||
| 2138 | CheckOptions("InputDefinitions ($name)", $inputdefinitions_options, %options); | ||
| 2139 | |||
| 2140 | my $prevname = $options{handleoptions} && $STATE->lookupDefinition(T_CS('\@currname')) && ToString(Expand(T_CS('\@currname'))); | ||
| 2141 | my $prevext = $options{handleoptions} && $STATE->lookupDefinition(T_CS('\@currext')) && ToString(Expand(T_CS('\@currext'))); | ||
| 2142 | |||
| 2143 | # This file will be treated somewhat as if it were a class | ||
| 2144 | # IF as_class is true | ||
| 2145 | # OR if it is loaded by such a class, and has withoptions true!!! (yikes) | ||
| 2146 | $options{as_class} = 1 if $options{handleoptions} && $options{withoptions} | ||
| 2147 | && grep { $prevname eq $_ } @{ LookupValue('@masquerading@as@class') || [] }; | ||
| 2148 | |||
| 2149 | $options{raw} = 1 if $options{noltxml}; # so it will be read as raw by Gullet.!L! | ||
| 2150 | my $astype = ($options{as_class} ? 'cls' : $options{type}); | ||
| 2151 | |||
| 2152 | my $filename = $name; | ||
| 2153 | $filename .= '.' . $options{type} if $options{type}; | ||
| 2154 | if ($options{options} && scalar(@{ $options{options} })) { | ||
| 2155 | if (my $prevoptions = LookupValue($filename . '_loaded_with_options')) { | ||
| 2156 | my $curroptions = join(',', @{ $options{options} }); | ||
| 2157 | Info('unexpected', 'options', $STATE->getStomach->getGullet, | ||
| 2158 | "Option clash for file $filename with options '$curroptions'", | ||
| 2159 | "previously loaded with '$prevoptions'") unless $curroptions eq $prevoptions; } } | ||
| 2160 | if (my $file = FindFile($filename, type => $options{type}, | ||
| 2161 | notex => $options{notex}, noltxml => $options{noltxml})) { | ||
| 2162 | if ($options{handleoptions}) { | ||
| 2163 | # For \RequirePackageWithOptions, pass the options from the outer class/style to the inner one. | ||
| 2164 | if (my $passoptions = $options{withoptions} && $prevname | ||
| 2165 | && LookupValue('opt@' . $prevname . "." . $prevext)) { | ||
| 2166 | # Only pass those class options that are declared by the package! | ||
| 2167 | my @declaredoptions = @{ LookupValue('@declaredoptions') }; | ||
| 2168 | my @topass = (); | ||
| 2169 | foreach my $op (@$passoptions) { | ||
| 2170 | push(@topass, $op) if grep { $op eq $_ } @declaredoptions; } | ||
| 2171 | PassOptions($name, $astype, @topass) if @topass; } | ||
| 2172 | DefMacroI('\@currname', undef, Tokens(Explode($name))); | ||
| 2173 | DefMacroI('\@currext', undef, Tokens(Explode($astype))); | ||
| 2174 | # reset options (Note reset & pass were in opposite order in LoadClass ????) | ||
| 2175 | resetOptions(); | ||
| 2176 | PassOptions($name, $astype, @{ $options{options} || [] }); # passed explicit options. | ||
| 2177 | # Note which packages are pretending to be classes. | ||
| 2178 | PushValue('@masquerading@as@class', $name) if $options{as_class}; | ||
| 2179 | DefMacroI(T_CS('\\' . $name . '.' . $astype . '-h@@k'), undef, $options{after} || ''); | ||
| 2180 | DefMacroI(T_CS('\opt@' . $name . '.' . $astype), undef, | ||
| 2181 | Tokens(Explode(join(',', @{ LookupValue('opt@' . $name . "." . $astype) })))); | ||
| 2182 | } | ||
| 2183 | AssignValue($filename . '_loaded_with_options' => join(',', @{ $options{options} }), 'global') | ||
| 2184 | if $options{options}; | ||
| 2185 | |||
| 2186 | my ($fdir, $fname, $ftype) = pathname_split($file); | ||
| 2187 | if ($options{handleoptions}) { | ||
| 2188 | # Add an appropriately faked entry into \@filelist | ||
| 2189 | my ($d, $n, $e) = ($fdir, $fname, $ftype); # If ftype is ltxml, reparse to get sty/cls! | ||
| 2190 | ($d, $n, $e) = pathname_split(pathname_concat($d, $n)) if $e eq 'ltxml'; # Fake it??? | ||
| 2191 | my @p = ($STATE->lookupDefinition(T_CS('\@filelist')) | ||
| 2192 | ? Expand(T_CS('\@filelist'))->unlist : ()); | ||
| 2193 | my @n = Explode($e ? $n . '.' . $e : $n); | ||
| 2194 | DefMacroI('\@filelist', undef, (@p ? Tokens(@p, T_OTHER(','), @n) : Tokens(@n))); } | ||
| 2195 | if ($ftype eq 'ltxml') { | ||
| 2196 | loadLTXML($filename, $file); } # Perl module. | ||
| 2197 | else { | ||
| 2198 | # Special case -- add a default resource if we're loading a raw .cls file as a first choice. | ||
| 2199 | # Raw class interpretations needs _some_ styling as baseline. | ||
| 2200 | if (!$options{noltxml} && ($file =~ /\.cls$/)) { | ||
| 2201 | RelaxNGSchema("LaTeXML"); | ||
| 2202 | RequireResource('ltx-article.css'); } | ||
| 2203 | loadTeXDefinitions($filename, $file); } | ||
| 2204 | if ($options{handleoptions}) { | ||
| 2205 | Digest(T_CS('\\' . $name . '.' . $astype . '-h@@k')); | ||
| 2206 | DefMacroI('\@currname', undef, Tokens(Explode($prevname))) if $prevname; | ||
| 2207 | DefMacroI('\@currext', undef, Tokens(Explode($prevext))) if $prevext; | ||
| 2208 | resetOptions(); } # And reset options afterwards, too. | ||
| 2209 | return $file; } | ||
| 2210 | elsif (!$options{noerror}) { | ||
| 2211 | $STATE->noteStatus(missing => $name . ($options{type} ? '.' . $options{type} : '')); | ||
| 2212 | # We'll only warn about a missing file of definitions: it may be ignorable or never used. | ||
| 2213 | # if there ARE problems, they'll likely produce their own errors! | ||
| 2214 | Warn('missing_file', $name, $STATE->getStomach->getGullet, | ||
| 2215 | "Can't find " | ||
| 2216 | . ($options{notex} ? "binding for " : "") | ||
| 2217 | . (($options{type} && $definition_name{ $options{type} }) || 'definitions') . ' ' | ||
| 2218 | . $name, | ||
| 2219 | "Anticipate undefined macros or environments", | ||
| 2220 | maybeReportSearchPaths()); } | ||
| 2221 | return; } | ||
| 2222 | |||
| 2223 | my $require_options = { # [CONSTANT] | ||
| 2224 | options => 1, withoptions => 1, type => 1, as_class => 1, | ||
| 2225 | noltxml => 1, notex => 1, raw => 1, after => 1 }; | ||
| 2226 | # This (& FindFile) needs to evolve a bit to support reading raw .sty (.def, etc) files from | ||
| 2227 | # the standard texmf directories. Maybe even use kpsewhich itself (INSTEAD of pathname_find ???) | ||
| 2228 | # Another potentially useful option might be that if we are reading a raw file, | ||
| 2229 | # perhaps it should just get digested immediately, since it shouldn't contribute any boxes. | ||
| 2230 | sub RequirePackage { | ||
| 2231 | my ($package, %options) = @_; | ||
| 2232 | $package = ToString($package) if ref $package; | ||
| 2233 | if ($options{raw}) { | ||
| 2234 | delete $options{raw}; $options{notex} = 0; | ||
| 2235 | Warn('deprecated', 'raw', $STATE->getStomach->getGullet, | ||
| 2236 | "RequirePackage option raw is obsolete; it is not needed"); } | ||
| 2237 | CheckOptions("RequirePackage ($package)", $require_options, %options); | ||
| 2238 | # We'll usually disallow raw TeX, unless the option explicitly given, or globally set. | ||
| 2239 | $options{notex} = 1 | ||
| 2240 | if !defined $options{notex} && !LookupValue('INCLUDE_STYLES') && !$options{noltxml}; | ||
| 2241 | my $success = InputDefinitions($package, type => $options{type} || 'sty', handleoptions => 1, | ||
| 2242 | # Pass classes options if we have NONE! | ||
| 2243 | withoptions => !($options{options} && @{ $options{options} }), | ||
| 2244 | %options); | ||
| 2245 | maybeRequireDependencies($package, $options{type} || 'sty') unless $success; | ||
| 2246 | return; } | ||
| 2247 | |||
| 2248 | my $loadclass_options = { # [CONSTANT] | ||
| 2249 | options => 1, withoptions => 1, after => 1, notex => 1 }; | ||
| 2250 | |||
| 2251 | sub LoadClass { | ||
| 2252 | my ($class, %options) = @_; | ||
| 2253 | $options{notex} = 1 | ||
| 2254 | if !defined $options{notex} && !LookupValue('INCLUDE_STYLES') && !$options{noltxml}; | ||
| 2255 | |||
| 2256 | $class = ToString($class) if ref $class; | ||
| 2257 | CheckOptions("LoadClass ($class)", $loadclass_options, %options); | ||
| 2258 | # AssignValue(class_options => [$options{options} ? @{ $options{options} } : ()]); | ||
| 2259 | PushValue(class_options => ($options{options} ? @{ $options{options} } : ())); | ||
| 2260 | if (my $op = $options{options}) { | ||
| 2261 | # ? Expand {\zap@space#2 \@empty}% | ||
| 2262 | DefMacroI('\@classoptionslist', undef, join(',', @$op)); } | ||
| 2263 | # Note that we'll handle errors specifically for this case. | ||
| 2264 | if (my $success = InputDefinitions($class, type => 'cls', notex => $options{notex}, handleoptions => 1, noerror => 1, | ||
| 2265 | %options)) { | ||
| 2266 | return $success; } | ||
| 2267 | else { | ||
| 2268 | $STATE->noteStatus(missing => $class . '.cls'); | ||
| 2269 | # Try guessing at an alternative class that we do have! | ||
| 2270 | # Find all class bindings (pathname_name twice for .cls.ltxml!!!) | ||
| 2271 | my @classes = sort { -(length($a) <=> length($b)) } | ||
| 2272 | map { pathname_name($_) } map { pathname_name($_) } | ||
| 2273 | pathname_findall('*', type => 'cls.ltxml', paths => LookupValue('SEARCHPATHS'), | ||
| 2274 | installation_subdir => 'Package'); | ||
| 2275 | my ($alternate) = grep { $class =~ /^\Q$_\E/ } @classes; | ||
| 2276 | $alternate = 'OmniBus' unless $alternate; | ||
| 2277 | # Only Warn for missing style/class: we'll punt with an alternative; | ||
| 2278 | # there may come other errors from undefined macros, though. | ||
| 2279 | Warn('missing_file', $class, $STATE->getStomach->getGullet, | ||
| 2280 | "Can't find binding for class $class (using $alternate)", | ||
| 2281 | "Anticipate undefined macros or environments", | ||
| 2282 | maybeReportSearchPaths()); | ||
| 2283 | if (my $success = InputDefinitions($alternate, type => 'cls', noerror => 1, handleoptions => 1, %options)) { | ||
| 2284 | maybeRequireDependencies($class, 'cls'); | ||
| 2285 | return $success; } | ||
| 2286 | else { | ||
| 2287 | Fatal('missing_file', $alternate . '.cls.ltxml', $STATE->getStomach->getGullet, | ||
| 2288 | "Can't find binding for class $alternate (installation error)"); | ||
| 2289 | return; } } } | ||
| 2290 | |||
| 2291 | sub LoadPool { | ||
| 2292 | my ($pool) = @_; | ||
| 2293 | $pool = ToString($pool) if ref $pool; | ||
| 2294 | if (my $success = InputDefinitions($pool, type => 'pool', notex => 1, noerror => 1)) { | ||
| 2295 | return $success; } | ||
| 2296 | else { | ||
| 2297 | Fatal('missing_file', "$pool.pool.ltxml", $STATE->getStomach->getGullet, | ||
| 2298 | "Can't find binding for pool $pool (installation error)", | ||
| 2299 | maybeReportSearchPaths()); | ||
| 2300 | return; } } | ||
| 2301 | |||
| 2302 | # Somewhat an act of desperation in contexts like arXiv | ||
| 2303 | # where we may have a bunch of random styles & classes that load other packages | ||
| 2304 | # whose macros are then expected to be present. | ||
| 2305 | # We scan the source for \RequirePackage & \usepackage and load the ones that have bindings. | ||
| 2306 | # This is almost safe: the packages may only be loaded unconditionally, and we don't notice that! | ||
| 2307 | sub maybeRequireDependencies { | ||
| 2308 | my ($file, $type) = @_; | ||
| 2309 | if (my $path = FindFile($file, type => $type, noltxml => 1)) { | ||
| 2310 | local $/ = undef; | ||
| 2311 | my $IN; | ||
| 2312 | if (open($IN, '<', $path)) { | ||
| 2313 | my $code = <$IN>; | ||
| 2314 | close($IN); | ||
| 2315 | my @classes = (); | ||
| 2316 | my @packages = (); | ||
| 2317 | my %dups = (); | ||
| 2318 | my $collect = sub { | ||
| 2319 | my ($packages, $options) = @_; | ||
| 2320 | foreach my $p (split(/\s*,\s*/, $packages)) { | ||
| 2321 | if (!$dups{$p} && !LookupValue($p . '.sty.ltxml_loaded')) { | ||
| 2322 | push(@packages, [$p, $options]); $dups{$p} = 1; } } }; | ||
| 2323 | # Yes, Regexps on TeX code! Ugh!!! Well, this is an act of desperation anyway :> | ||
| 2324 | $code =~ s/%[^\n]*\n//gs; # strip comments | ||
| 2325 | $code =~ s/\\RequirePackage\s*(?:\[([^\]]*)\])?\s*\{([^\}]*)\}/ &$collect($2,$1); /xegs; | ||
| 2326 | # Ugh. \usepackage, too | ||
| 2327 | $code =~ s/\\usepackage\s*(?:\[([^\]]*)\])?\s*\{([^\}]*)\}/ &$collect($2,$1); /xegs; | ||
| 2328 | # Even more ugh; \LoadClass | ||
| 2329 | if ($type eq 'cls') { | ||
| 2330 | $code =~ s/\\LoadClass\s*(?:\[([^\]]*)\])?\s*\{([^\}]*)\}/ push(@classes,[$2,$1]); /xegs; } | ||
| 2331 | |||
| 2332 | Info('dependencies', 'dependencies', undef, | ||
| 2333 | "Loading dependencies for $path: " . join(',', map { $$_[0]; } @classes, @packages)) if scalar(@classes) || scalar(@packages); | ||
| 2334 | foreach my $pair (@classes) { | ||
| 2335 | my ($class, $options) = @$pair; | ||
| 2336 | if (FindFile($class, type => 'cls', notex => 1)) { | ||
| 2337 | LoadClass($class, ($options ? (options => [split(/\s*,\s*/, $options)]) : ())); } } | ||
| 2338 | foreach my $pair (@packages) { | ||
| 2339 | my ($package, $options) = @$pair; | ||
| 2340 | if (FindFile($package, type => 'sty', notex => 1)) { | ||
| 2341 | RequirePackage($package, ($options ? (options => [split(/\s*,\s*/, $options)]) : ())); } } } | ||
| 2342 | else { | ||
| 2343 | Warn('I/O', 'read', undef, "Couldn't open $path to scan dependencies", $!); } } | ||
| 2344 | return; } | ||
| 2345 | |||
| 2346 | sub AtBeginDocument { | ||
| 2347 | my (@operations) = @_; | ||
| 2348 | AssignValue('@at@begin@document', []) unless LookupValue('@at@begin@document'); | ||
| 2349 | foreach my $op (@operations) { | ||
| 2350 | next unless $op; | ||
| 2351 | my $t = ref $op; | ||
| 2352 | if (!$t) { # Presumably String? | ||
| 2353 | $op = TokenizeInternal($op); } | ||
| 2354 | elsif ($t eq 'CODE') { | ||
| 2355 | my $tn = T_CS(ToString($op)); | ||
| 2356 | DefMacroI($tn, undef, $op); | ||
| 2357 | $op = $tn; } | ||
| 2358 | PushValue('@at@begin@document', $op->unlist); } | ||
| 2359 | return; } | ||
| 2360 | |||
| 2361 | sub AtEndDocument { | ||
| 2362 | my (@operations) = @_; | ||
| 2363 | AssignValue('@at@end@document', []) unless LookupValue('@at@end@document'); | ||
| 2364 | foreach my $op (@operations) { | ||
| 2365 | next unless $op; | ||
| 2366 | my $t = ref $op; | ||
| 2367 | if (!$t) { # Presumably String? | ||
| 2368 | $op = TokenizeInternal($op); } | ||
| 2369 | elsif ($t eq 'CODE') { | ||
| 2370 | my $tn = T_CS(ToString($op)); | ||
| 2371 | DefMacroI($tn, undef, $op); | ||
| 2372 | $op = $tn; } | ||
| 2373 | PushValue('@at@end@document', $op->unlist); } | ||
| 2374 | return; } | ||
| 2375 | |||
| 2376 | #====================================================================== | ||
| 2377 | # | ||
| 2378 | my $fontmap_options = { # [CONSTANT] | ||
| 2379 | family => 1 }; | ||
| 2380 | |||
| 2381 | sub DeclareFontMap { | ||
| 2382 | my ($name, $map, %options) = @_; | ||
| 2383 | CheckOptions("DeclareFontMap", $fontmap_options, %options); | ||
| 2384 | my $mapname = ToString($name) | ||
| 2385 | . ($options{family} ? '_' . $options{family} : '') | ||
| 2386 | . '_fontmap'; | ||
| 2387 | AssignValue($mapname => $map, 'global'); | ||
| 2388 | return; } | ||
| 2389 | |||
| 2390 | # Decode a codepoint using the fontmap for a given font and/or fontencoding. | ||
| 2391 | # If $encoding not provided, then lookup according to the current font's | ||
| 2392 | # encoding; the font family may also be used to choose the fontmap (think tt fonts!). | ||
| 2393 | # When $implicit is false, we are "explicitly" asking for a decoding, such as | ||
| 2394 | # with \char, \mathchar, \symbol, DeclareTextSymbol and such cases. | ||
| 2395 | # In such cases, only codepoints specifically within the map are covered; the rest are undef. | ||
| 2396 | # If $implicit is true, we'll decode token content that has made it to the stomach: | ||
| 2397 | # We're going to assume that SOME sort of handling of input encoding is taking place, | ||
| 2398 | # so that if anything above 128 comes in, it must already be Unicode!. | ||
| 2399 | # The lower half plane still needs to go through decoding, though, to deal | ||
| 2400 | # with TeX's rearrangement of ASCII... | ||
| 2401 | sub FontDecode { | ||
| 2402 | my ($code, $encoding, $implicit) = @_; | ||
| 2403 | return if !defined $code || ($code < 0); | ||
| 2404 | my ($map, $font); | ||
| 2405 | if (!$encoding) { | ||
| 2406 | $font = LookupValue('font'); | ||
| 2407 | $encoding = $font->getEncoding || 'OT1'; } | ||
| 2408 | if ($encoding && ($map = LoadFontMap($encoding))) { # OK got some map. | ||
| 2409 | my ($family, $fmap); | ||
| 2410 | if ($font && ($family = $font->getFamily) && ($fmap = LookupValue($encoding . '_' . $family . '_fontmap'))) { | ||
| 2411 | $map = $fmap; } } # Use the family specific map, if any. | ||
| 2412 | if ($implicit) { | ||
| 2413 | if ($map && ($code < 128)) { | ||
| 2414 | return $$map[$code]; } | ||
| 2415 | else { | ||
| 2416 | return pack('U', $code); } } | ||
| 2417 | else { | ||
| 2418 | return ($map ? $$map[$code] : undef); } } | ||
| 2419 | |||
| 2420 | sub FontDecodeString { | ||
| 2421 | my ($string, $encoding, $implicit) = @_; | ||
| 2422 | return if !defined $string; | ||
| 2423 | my ($map, $font); | ||
| 2424 | if (!$encoding) { | ||
| 2425 | $font = LookupValue('font'); | ||
| 2426 | $encoding = $font->getEncoding; } | ||
| 2427 | if ($encoding && ($map = LoadFontMap($encoding))) { # OK got some map. | ||
| 2428 | my ($family, $fmap); | ||
| 2429 | if ($font && ($family = $font->getFamily) && ($fmap = LookupValue($encoding . '_' . $family . '_fontmap'))) { | ||
| 2430 | $map = $fmap; } } # Use the family specific map, if any. | ||
| 2431 | |||
| 2432 | return join('', grep { defined $_ } | ||
| 2433 | map { ($implicit ? (($map && ($_ < 128)) ? $$map[$_] : pack('U', $_)) | ||
| 2434 | : ($map ? $$map[$_] : undef)) } | ||
| 2435 | map { ord($_) } split(//, $string)); } | ||
| 2436 | |||
| 2437 | sub LoadFontMap { | ||
| 2438 | my ($encoding) = @_; | ||
| 2439 | my $map = LookupValue($encoding . '_fontmap'); | ||
| 2440 | if (!$map && !LookupValue($encoding . '_fontmap_failed_to_load')) { | ||
| 2441 | AssignValue($encoding . '_fontmap_failed_to_load' => 1); # Stop recursion? | ||
| 2442 | RequirePackage(lc($encoding), type => 'fontmap'); | ||
| 2443 | if ($map = LookupValue($encoding . '_fontmap')) { # Got map? | ||
| 2444 | AssignValue($encoding . '_fontmap_failed_to_load' => 0); } | ||
| 2445 | else { | ||
| 2446 | AssignValue($encoding . '_fontmap_failed_to_load' => 1, 'global'); } } | ||
| 2447 | return $map; } | ||
| 2448 | |||
| 2449 | #====================================================================== | ||
| 2450 | # Color | ||
| 2451 | sub LookupColor { | ||
| 2452 | my ($name) = @_; | ||
| 2453 | if (my $color = LookupValue('color_' . $name)) { | ||
| 2454 | return $color; } | ||
| 2455 | else { | ||
| 2456 | Error('undefined', $name, $STATE->getStomach, "color '$name' is undefined..."); | ||
| 2457 | return Black; } } | ||
| 2458 | |||
| 2459 | sub DefColor { | ||
| 2460 | my ($name, $color, $scope) = @_; | ||
| 2461 | #print STDERR "DEFINE ".ToString($name)." => ".join(',',@$color)."\n"; | ||
| 2462 | return unless ref $color; | ||
| 2463 | my ($model, @spec) = @$color; | ||
| 2464 | $scope = 'global' if $STATE->lookupDefinition(T_CS('\ifglobalcolors')) && IfCondition(T_CS('\ifglobalcolors')); | ||
| 2465 | AssignValue('color_' . $name => $color, $scope); | ||
| 2466 | # We could store these pieces separately,or in a list for above, | ||
| 2467 | # so that extract could use them more reasonably? | ||
| 2468 | # This is perhaps too xcolor specific? | ||
| 2469 | DefMacroI('\\\\color@' . $name, undef, | ||
| 2470 | '\relax\relax{' . join(' ', $model, @spec) . '}{' . $model . '}{' . join(',', @spec) . '}', | ||
| 2471 | scope => $scope); | ||
| 2472 | return; } | ||
| 2473 | |||
| 2474 | # Need 3 things for Derived Models: | ||
| 2475 | # derivedfrom : the core model that this model is "derived from" | ||
| 2476 | # convertto : code to convert to the (a) core model | ||
| 2477 | # convertfrom : code to convert from the core model | ||
| 2478 | sub DefColorModel { | ||
| 2479 | my ($model, $coremodel, $tocore, $fromcore) = @_; | ||
| 2480 | AssignValue('derived_color_model_' . $model => [$coremodel, $tocore, $fromcore], 'global'); | ||
| 2481 | return; } | ||
| 2482 | |||
| 2483 | #====================================================================== | ||
| 2484 | # Defining Rewrite rules that act on the DOM | ||
| 2485 | # These are applied after the document is completely constructed | ||
| 2486 | my $rewrite_options = { # [CONSTANT] | ||
| 2487 | label => 1, scope => 1, xpath => 1, match => 1, | ||
| 2488 | attributes => 1, replace => 1, regexp => 1, select => 1 }; | ||
| 2489 | |||
| 2490 | sub DefRewrite { | ||
| 2491 | my (@specs) = @_; | ||
| 2492 | CheckOptions("DefRewrite", $rewrite_options, @specs); | ||
| 2493 | PushValue('DOCUMENT_REWRITE_RULES', | ||
| 2494 | LaTeXML::Core::Rewrite->new('text', processRewriteSpecs(0, @specs))); | ||
| 2495 | return; } | ||
| 2496 | |||
| 2497 | sub DefMathRewrite { | ||
| 2498 | my (@specs) = @_; | ||
| 2499 | CheckOptions("DefMathRewrite", $rewrite_options, @specs); | ||
| 2500 | PushValue('DOCUMENT_REWRITE_RULES', | ||
| 2501 | LaTeXML::Core::Rewrite->new('math', processRewriteSpecs(1, @specs))); | ||
| 2502 | return; } | ||
| 2503 | |||
| 2504 | sub processRewriteSpecs { | ||
| 2505 | my ($math, @specs) = @_; | ||
| 2506 | my @procspecs = (); | ||
| 2507 | my $delimiter = ($math ? '$' : ''); | ||
| 2508 | while (@specs) { | ||
| 2509 | my $k = shift(@specs); | ||
| 2510 | my $v = shift(@specs); | ||
| 2511 | # Make sure match & replace are (at least) tokenized | ||
| 2512 | if (($k eq 'match') || ($k eq 'replace')) { | ||
| 2513 | if (ref $v eq 'ARRAY') { | ||
| 2514 | $v = [map { (ref $_ ? $_ : Tokenize($delimiter . $_ . $delimiter)) } @$v]; } | ||
| 2515 | elsif (!ref $v) { | ||
| 2516 | $v = Tokenize($delimiter . $v . $delimiter); } } | ||
| 2517 | push(@procspecs, $k, $v); } | ||
| 2518 | return @procspecs; } | ||
| 2519 | |||
| 2520 | #====================================================================== | ||
| 2521 | # Defining "Ligatures" rules that act on the DOM | ||
| 2522 | # These are actually a sort of rewrite that is applied while the doom | ||
| 2523 | # is being constructed, in particular as each node is closed. | ||
| 2524 | |||
| 2525 | my $ligature_options = { # [CONSTANT] | ||
| 2526 | fontTest => 1 }; | ||
| 2527 | |||
| 2528 | sub DefLigature { | ||
| 2529 | my ($regexp, $replacement, %options) = @_; | ||
| 2530 | CheckOptions("DefLigature", $ligature_options, %options); | ||
| 2531 | UnshiftValue('TEXT_LIGATURES', | ||
| 2532 | { regexp => $regexp, | ||
| 2533 | code => sub { $_[0] =~ s/$regexp/$replacement/g; $_[0]; }, | ||
| 2534 | %options }); | ||
| 2535 | return; } | ||
| 2536 | |||
| 2537 | my $old_math_ligature_options = {}; # [CONSTANT] | ||
| 2538 | my $math_ligature_options = { matcher => 1, role => 1, name => 1, meaning => 1 }; # [CONSTANT] | ||
| 2539 | |||
| 2540 | sub DefMathLigature { | ||
| 2541 | if ((scalar(@_) % 2) == 1) { # Old style! | ||
| 2542 | my ($matcher, %options) = @_; | ||
| 2543 | Info('deprecated', 'ligature', undef, "Old style arguments to DefMathLigature; please update"); | ||
| 2544 | CheckOptions("DefMathLigature", $old_math_ligature_options, %options); | ||
| 2545 | UnshiftValue('MATH_LIGATURES', { old_style => 1, matcher => $matcher }); } # Install it... | ||
| 2546 | else { # new style! | ||
| 2547 | my (%options) = @_; | ||
| 2548 | my $matcher = $options{matcher}; | ||
| 2549 | delete $options{matcher}; | ||
| 2550 | my ($pattern) = grep { !$$math_ligature_options{$_} } keys %options; | ||
| 2551 | my $replacement = $pattern && $options{$pattern}; | ||
| 2552 | delete $options{$pattern} if $replacement; | ||
| 2553 | CheckOptions("DefMathLigature", $math_ligature_options, %options); # Check remaining options | ||
| 2554 | if ($matcher && $pattern) { | ||
| 2555 | Error('misdefined', 'MathLigature', undef, | ||
| 2556 | "DefMathLigature only gets one of matcher or pattern=>replacement keywords"); | ||
| 2557 | return; } | ||
| 2558 | elsif ($pattern) { | ||
| 2559 | my @chars = reverse(split(//, $pattern)); | ||
| 2560 | my $ntomatch = scalar(@chars); | ||
| 2561 | my %attr = %options; | ||
| 2562 | $matcher = sub { | ||
| 2563 | my ($document, $node) = @_; | ||
| 2564 | foreach my $char (@chars) { | ||
| 2565 | return unless | ||
| 2566 | ($node | ||
| 2567 | && ($document->getModel->getNodeQName($node) eq 'ltx:XMTok') | ||
| 2568 | && (($node->textContent || '') eq $char)); | ||
| 2569 | $node = $node->previousSibling; } | ||
| 2570 | return ($ntomatch, $replacement, %attr); }; } | ||
| 2571 | elsif (!$matcher) { | ||
| 2572 | Error('misdefined', 'MathLigature', undef, | ||
| 2573 | "DefMathLigature missing matcher or pattern=>replacement keywords"); | ||
| 2574 | return; } | ||
| 2575 | UnshiftValue('MATH_LIGATURES', { matcher => $matcher }); } # Install it... | ||
| 2576 | return; } | ||
| 2577 | |||
| 2578 | #====================================================================== | ||
| 2579 | # Support for requiring "Resources", ie CSS, Javascript, whatever | ||
| 2580 | |||
| 2581 | my $resource_options = { # [CONSTANT] | ||
| 2582 | type => 1, media => 1, content => 1 }; | ||
| 2583 | my $resource_types = { # [CONSTANT] | ||
| 2584 | css => 'text/css', js => 'text/javascript' }; | ||
| 2585 | |||
| 2586 | sub RequireResource { | ||
| 2587 | my ($resource, %options) = @_; | ||
| 2588 | CheckOptions("RequireResource", $resource_options, %options); | ||
| 2589 | if (!$options{content} && !$resource) { | ||
| 2590 | Warn('expected', 'resource', undef, "Resource must have a resource pathname or content; skipping"); | ||
| 2591 | return; } | ||
| 2592 | if (!$options{type}) { | ||
| 2593 | my $ext = $resource && pathname_type($resource); | ||
| 2594 | $options{type} = $ext && $$resource_types{$ext}; } | ||
| 2595 | if (!$options{type}) { | ||
| 2596 | my $ext = $resource && pathname_type($resource); | ||
| 2597 | my $t = $ext && $$resource_types{$ext}; | ||
| 2598 | Warn('expected', 'type', undef, "Resource must have a mime-type; skipping"); return; } | ||
| 2599 | |||
| 2600 | if ($LaTeXML::DOCUMENT) { # If we've got a document, go ahead & put the resource in. | ||
| 2601 | addResource($LaTeXML::DOCUMENT, $resource, %options); } | ||
| 2602 | else { | ||
| 2603 | AssignValue(PENDING_RESOURCES => [], 'global') unless LookupValue('PENDING_RESOURCES'); | ||
| 2604 | PushValue(PENDING_RESOURCES => [$resource, %options]); } | ||
| 2605 | return; } | ||
| 2606 | |||
| 2607 | # No checking... | ||
| 2608 | sub addResource { | ||
| 2609 | my ($document, $resource, %options) = @_; | ||
| 2610 | my $savenode = $document->floatToElement('ltx:resource'); | ||
| 2611 | $document->insertElement('ltx:resource', $options{content}, | ||
| 2612 | src => $resource, type => $options{type}, media => $options{media}); | ||
| 2613 | $document->setNode($savenode) if $savenode; | ||
| 2614 | return; } | ||
| 2615 | |||
| 2616 | sub ProcessPendingResources { | ||
| 2617 | my ($document) = @_; | ||
| 2618 | if (my $resources = LookupValue('PENDING_RESOURCES')) { | ||
| 2619 | my %seen = (); | ||
| 2620 | my @unique_resources = grep { my $new = !$seen{$_}; $seen{$_} = 1; $new; } @$resources; | ||
| 2621 | for my $resource (@unique_resources) { | ||
| 2622 | addResource($document, @$resource); } | ||
| 2623 | AssignValue(PENDING_RESOURCES => [], 'global'); } | ||
| 2624 | return; } | ||
| 2625 | |||
| 2626 | #********************************************************************** | ||
| 2627 | 1; | ||
| 2628 | |||
| 2629 | __END__ | ||