1 # This file is part of reLyX
2 # Copyright (c) 1998-9 Amir Karger karger@post.harvard.edu
3 # You are free to use and modify this code under the terms of
4 # the GNU General Public Licence version 2 or later.
7 # This package includes subroutines to translate "clean" LaTeX to LyX.
8 # It translates only "basic" stuff, which means it doesn't do class-specific
9 # things. (It uses the TeX parser Text::TeX)
12 use RelyxTable; # Handle LaTeX tables
13 use RelyxFigure; # Handle LaTeX figures
14 use Verbatim; # Copy stuff verbatim
16 use vars qw($bibstyle_insert_string $bibstyle_file $Begin_Inset_Include);
17 $bibstyle_insert_string = "%%%%%Insert bibliographystyle file here!";
19 $Begin_Inset_Include = "\\begin_inset Include";
21 #################### PACKAGE-WIDE VARIABLES ###########################
22 my $debug_on; # is debugging on?
25 #Next text starts a new paragraph?
26 # $INP = 0 for plain text not starting a new paragraph
27 # $INP = 1 for text starting a new paragraph, so that we write a new
28 # \layout command and renew any font changes for the new paragraph
29 # Starts as 1 cuz if the first text in the document is plain text
30 # (not, e.g., in a \title command) it will start a new paragraph
31 my $IsNewParagraph = 1;
32 my $OldINP; #Save $IsNewParagraph during footnotes
34 # Some layouts may have no actual text in them before the next layout
35 # (e.g. slides). Pending Layout is set when we read a command that puts us
36 # in a new layout. If we get some regular text to print out, set it to false.
37 # But if we get to another layout command, first print out the command to
38 # start the pending layout.
39 my $PendingLayout = 0;
41 # HACK to protect spaces within optional argument to \item
42 my $protect_spaces = 0;
44 # $MBD = 1 if we're in a list, but haven't seen an '\item' command
45 # In that case, we may need to start a nested "Standard" paragraph
47 my $OldMBD; #Save $MBD during footnotes -- this should very rarely be necessary!
49 # Stack to take care of environments like Enumerate, Quote
50 # We need a separate stack for footnotes, which have separate layouts etc.
51 # Therefore we use a reference to an array, not just an array
52 my @LayoutStack = ("Standard"); #default if everything else pops off
53 my $CurrentLayoutStack = \@LayoutStack;
55 # Status of various font commands
56 # Every font characteristic (family, series, etc.) needs a stack, because
57 # there may be nested font commands, like \textsf{blah \texttt{blah} blah}
58 # CurrentFontStatus usually points to the main %FontStatus hash, but
59 # when we're in a footnote, it will point to a temporary hash
61 '\emph' => ["default"],
62 '\family' => ["default"],
63 '\series' => ["default"],
64 '\shape' => ["default"],
65 '\bar' => ["default"],
66 '\size' => ["default"],
67 '\noun' => ["default"],
69 my $CurrentFontStatus = \%FontStatus;
71 # Currently aligning paragraphs right, left, or center?
72 my $CurrentAlignment = "";
73 my $OldAlignment; # Save $AS during footnotes
75 # Global variables for copying tex stuff
76 my $tex_mode_string; # string we accumulate tex mode stuff in
77 my @tex_mode_tokens; # stack of tokens which required calling copy_latex_known
79 # LyX strings to start and end TeX mode
80 my $start_tex_mode = "\n\\latex latex \n";
81 my $end_tex_mode = "\n\\latex default \n";
83 # String to write before each item
84 my $item_preface = "";
86 ############# INFORMATION ABOUT LATEX AND LYX #############################
87 # LyX translations of LaTeX font commands
88 my %FontTransTable = (
90 '\emph' => "\n\\emph on \n",
91 '\underline' => "\n\\bar under \n",
92 '\underbar' => "\n\\bar under \n", # plain tex equivalent of underline?
93 '\textbf' => "\n\\series bold \n",
94 '\textmd' => "\n\\series medium \n",
95 '\textsf' => "\n\\family sans \n",
96 '\texttt' => "\n\\family typewriter \n",
97 '\textrm' => "\n\\family roman \n",
98 '\textsc' => "\n\\shape smallcaps \n",
99 '\textsl' => "\n\\shape slanted \n",
100 '\textit' => "\n\\shape italic \n",
101 '\textup' => "\n\\shape up \n",
102 '\noun' => "\n\\noun on \n", # LyX abstraction of smallcaps
105 '\tiny' => "\n\\size tiny \n",
106 '\scriptsize' => "\n\\size scriptsize \n",
107 '\footnotesize' => "\n\\size footnotesize \n",
108 '\small' => "\n\\size small \n",
109 '\normalsize' => "\n\\size default \n",
110 '\large' => "\n\\size large \n",
111 '\Large' => "\n\\size Large \n",
112 '\LARGE' => "\n\\size LARGE \n",
113 '\huge' => "\n\\size huge \n",
114 '\Huge' => "\n\\size Huge \n",
115 # This doesn't work yet!
116 #'\textnormal' => "\n\\series medium \n\\family roman \n\\shape up \n",
119 # Things LyX implements as "Floats"
120 my %FloatTransTable = (
121 # Footnote, Margin note
122 '\footnote' => "\n\\begin_float footnote \n",
123 '\thanks' => "\n\\begin_float footnote \n", # thanks is same as footnote
124 '\marginpar' => "\n\\begin_float margin \n",
126 # Environments that LyX implements as "floats"
127 my %FloatEnvTransTable = (
128 "table" => "\n\\begin_float tab \n",
129 "table*" => "\n\\begin_float wide-tab \n",
130 "figure" => "\n\\begin_float fig \n",
131 "figure*" => "\n\\begin_float wide-fig \n",
134 # Simple LaTeX tokens which are turned into small pieces of LyX text
135 my %TextTokenTransTable = (
136 # LaTeX escaped characters
146 # \i and \j are used in accents. LyX doesn't recognize them in plain
147 # text. Hopefully, this isn't a problem.
151 # Misc simple LaTeX tokens
152 '~' => "\n\\protected_separator \n",
153 '@' => "@", # TeX.pm considers this a token, but it's not really
154 '\@' => "\\SpecialChar \\@",
155 '\ldots' => "\n\\SpecialChar \\ldots\{\}\n",
156 '\-' => "\\SpecialChar \\-\n",
158 '\LaTeXe' => "LaTeX2e",
161 '\hfill' => "\n\\hfill \n",
162 '\noindent' => "\n\\noindent \n",
163 '\textbackslash' => "\n\\backslash \n",
164 '\textgreater' => ">",
169 # LyX translations of some plain LaTeX text (TeX parser won't recognize it
170 # as a Token, so we need to translate the Text::TeX::Text token.)
171 my %TextTransTable = (
173 "``" => "\n\\begin_inset Quotes eld\n\\end_inset \n\n",
174 "''" => "\n\\begin_inset Quotes erd\n\\end_inset \n\n",
176 # Tokens that don't start with a backslash, so parser won't recognize them
177 # (LyX doesn't support them, so we just print them in TeX mode)
178 '?`' => "$start_tex_mode?`$end_tex_mode",
179 '!`' => "$start_tex_mode!`$end_tex_mode",
182 # Things that LyX translates as "LatexCommand"s
183 # E.g., \ref{foo} ->'\begin_inset LatexCommand \ref{foo}\n\n\end_inset \n'
184 # (Some take arguments, others don't)
185 my @LatexCommands = map {"\\$_"} qw(ref pageref label cite bibliography
186 index printindex tableofcontents
187 listofalgorithms listoftables listoffigures);
188 my @IncludeCommands = map {"\\$_"} qw(input include);
189 # Included postscript files
190 # LyX 1.0 can't do \includegraphics*!
191 my @GraphicsCommands = map {"\\$_"} qw(epsf epsffile epsfbox
192 psfig epsfig includegraphics);
194 # Accents. Most of these take an argument -- the thing to accent
195 # (\l and \L are handled as InsetLatexAccents, so they go here too)
196 my $AccentTokens = "\\\\[`'^#~=.bcdHklLrtuv\"]";
198 # Environments which describe justifying (converted to LyX \align commands)
199 # and the corresponding LyX commands
200 my %AlignEnvironments = (
201 "center" => "\n\\align center \n",
202 "flushright" => "\n\\align right \n",
203 "flushleft" => "\n\\align left \n",
206 # Some environments' begin commands take an extra argument
207 # Print string followed by arg for each item in the list, or ignore the arg ("")
208 my %ExtraArgEnvironments = (
209 "thebibliography" => "",
210 "lyxlist" =>'\labelwidthstring ',
211 "labeling" =>'\labelwidthstring ', # koma script list
214 # Math environments are copied verbatim
215 my $MathEnvironments = "(math|equation|displaymath|eqnarray(\\*)?)";
216 # ListLayouts may have standard paragraphs nested inside them.
217 my $ListLayouts = "Itemize|Enumerate|Description";
219 ##################### PARSER INVOCATION ##################################
221 # This subroutine calls the TeX parser & translator
222 # Before it does that, it does lots of setup work to get ready for parsing.
223 # Arg0 is the file to read (clean) LaTeX from
224 # Arg1 is the file to write LyX to
225 # Arg2 is the file to read layouts from (e.g., in LYX_DIR/layouts/foo.layout)
227 my ($InFileName, $OutFileName) = (shift,shift);
229 # Before anything else, set the package-wide variables based on the
231 # opt_d is set to 1 if '-d' option given, else (probably) undefined
232 $debug_on = (defined($main::opt_d) && $main::opt_d);
234 # Hash of tokens passed to the TeX parser
235 # Many values are $Text::TeX::Tokens{'\operatorname'}, which has
236 # Type=>report_args and count=>1
237 # Note that we don't have to bother putting in tokens which will be simply
238 # translated (e.g., from %TextTokenTransTable).
240 '{' => $Text::TeX::Tokens{'{'},
241 '}' => $Text::TeX::Tokens{'}'},
242 '\begin' => $Text::TeX::Tokens{'\begin'},
243 '\end' => $Text::TeX::Tokens{'\end'},
245 # Lots of other commands will be made by ReadCommands:Merge
246 # by reading the LaTeX syntax file
248 # Font sizing commands (local)
249 '\tiny' => {Type => 'local'},
250 '\small' => {Type => 'local'},
251 '\scriptsize' => {Type => 'local'},
252 '\footnotesize' => {Type => 'local'},
253 '\small' => {Type => 'local'},
254 '\normalsize' => {Type => 'local'},
255 '\large' => {Type => 'local'},
256 '\Large' => {Type => 'local'},
257 '\LARGE' => {Type => 'local'},
258 '\huge' => {Type => 'local'},
259 '\Huge' => {Type => 'local'},
261 # Tokens to ignore (which make a new paragraph)
262 # Just pretend they actually ARE new paragraph markers!
263 '\maketitle' => {'class' => 'Text::TeX::Paragraph'},
266 # Now add to MyTokens all of the commands that were read from the
267 # commands file by package ReadCommands
268 &ReadCommands::Merge(\%MyTokens);
270 # Here's the actual subroutine. The above is all preparation
272 my $zzz = $debug_on ? " ($InFileName --> $OutFileName)\n" : "... ";
273 print STDERR "Translating$zzz";
274 open (OUTFILE,">$OutFileName");
276 # Open the file to turn into LyX.
277 my $infile = new Text::TeX::OpenFile $InFileName,
278 'defaultact' => \&basic_lyx,
279 'tokens' => \%MyTokens;
281 # Process what's left of the file (everything from \begin{document})
284 # Last line of the LyX file
285 print OUTFILE "\n\\the_end\n";
287 #warn "Done with basic translation\n";
289 } # end subroutine call_parser
291 ########################## MAIN TRANSLATOR SUBROUTINE #####################
293 # This subroutine is called by Text::TeX::process each time subroutine
294 # eat returns a value.
295 # Argument 0 is the return value from subroutine eat
296 # Argument 1 is the Text::TeX::OpenFile (namely, $TeXfile)
298 my $fileobject = shift;
300 # This handles most but maybe not all comments
301 # THere shouldn't be any if we've run CleanTeX.pl
302 print "Comment: ",$eaten->comment if defined $eaten->comment && $debug_on;
304 my $type = ref($eaten);
305 print "$type " if $debug_on;
307 # This loop is basically just a switch. However, making it a for
308 # (1) makes $_ = $type (convenient)
309 # (2) allows us to use things like next and last
310 TYPESW: for ($type) {
313 s/^Text::TeX:://o or die "unknown token?!";
317 # The parser puts whitespace before certain kinds of tokens along
318 # with that token. If that happens, save a space
319 my $pre_space = ""; # whitespace before a token
320 if (/BegArgsToken|^Token|::Group$/) {
321 $dummy = $eaten->exact_print;
322 # Only set prespace if we match something
323 # We wouldn't want it to be more than one space, since that's
324 # illegal in LyX. Also, replace \t or \n with ' ' since they are
325 # ignored in LyX. Hopefully, this won't lead to anything worse
326 # than some lines with >80 chars
327 # Finally, don't put a space at the beginning of a new paragraph
328 if (($dummy =~ /^\s+/) && !$IsNewParagraph) {
333 # Handle blank lines.
334 if (m/^Paragraph$/o) {
335 # $INP <>0 means We will need a new layout command
338 # $MBD means start a begin_deeper within list environments
339 # unless there's an \item command
345 # If, e.g., there's just a comment in this token, don't do anything
346 # This actually shouldn't happen if CleanTeX has already removed them
347 last TYPESW if !defined $eaten->print;
349 # Handle LaTeX tokens
352 my $name = $eaten->token_name; # name of the token, e.g., "\large"
353 print "'$name' " if $debug_on;
355 # Tokens which turn into a bit of LyX text
356 if (exists $TextTokenTransTable{$name}) {
357 &CheckForNewParagraph; #Start new paragraph if necessary
359 my $to_print = $TextTokenTransTable{$name};
361 # \@ has to be specially handled, because it depends on
362 # the character AFTER the \@
364 my $next = $fileobject->eatGroup(1);
366 $ch = $next->print or warn "\@ confused me!\n";
368 # Note: \@ CAN'T have pre_space before it
369 print OUTFILE "$to_print$ch\n";
370 print "followed by $ch" if $debug_on;
372 warn "LyX (or LaTeX) can't handle '$ch' after $name\n";
376 } else { # it's not \@
377 # Print the translated text (include preceding whitespace)
378 print OUTFILE "$pre_space$to_print";
379 } # end special handling for \@
381 # Handle tokens that LyX translates as a "LatexCommand" inset
382 } elsif (grep {$_ eq $name} @LatexCommands) {
383 &CheckForNewParagraph; #Start new paragraph if necessary
384 print OUTFILE "$pre_space\n\\begin_inset LatexCommand ",
386 "\n\n\\end_inset \n\n";
388 # Math -- copy verbatim until you're done
389 } elsif ($name eq '\(' || $name eq '\[') {
390 print "\nCopying math beginning with '$name'\n" if $debug_on;
391 # copy everything until end text
392 $dummy = &Verbatim::copy_verbatim($fileobject, $eaten);
393 $dummy = &fixmath($dummy); # convert '\sp' to '^', etc.
395 &CheckForNewParagraph; # math could be first thing in a par
396 print OUTFILE "$pre_space\n\\begin_inset Formula $name ";
397 print $dummy if $debug_on;
398 print OUTFILE $dummy;
400 } elsif ($name eq '\)' || $name eq '\]') {
402 print OUTFILE "$name\n\\end_inset \n\n";
403 print "\nDone copying math ending with '$name'" if $debug_on;
405 # Items in list environments
406 } elsif ($name eq '\item') {
408 # What if we had a nested "Standard" paragraph?
409 # Then write \end_deeper to finish the standard layout
410 # before we write the new \layout ListEnv command
411 if ($$CurrentLayoutStack[-1] eq "Standard") {
412 pop (@$CurrentLayoutStack); # take "Standard" off the stack
413 print OUTFILE "\n\\end_deeper ";
414 print "\nCurrent Layout Stack: @$CurrentLayoutStack"
418 # Upcoming text (the item) will be a new paragraph,
419 # requiring a new layout command based on whichever
420 # kind of list environment we're in
423 # But since we had an \item command, DON'T nest a
424 # deeper "Standard" paragraph in the list
427 # Check for an optional argument to \item
428 # If so, within the [] we need to protect spaces
429 # TODO: In fact, for description, if there's no [] or
430 # there's an empty [], then we need to write a ~, since LyX
431 # will otherwise make the next word the label
432 # If it's NOT a description & has a [] then we're stuck!
433 # They need to fix the bullets w/in lyx!
434 if (($dummy = $fileobject->lookAheadToken) &&
435 ($dummy =~ /\s*\[/)) {
436 $fileobject->eatFixedString('\['); # eat the [
440 # Special lists (e.g. List layout) have to print something
441 # before each item. In that case, CFNP and print it
443 &CheckForNewParagraph;
444 print OUTFILE $item_preface;
447 # Font sizing commands
448 # (Other font commands are TT::BegArgsTokens because they take
449 # arguments. Font sizing commands are 'local' TT::Tokens)
450 } elsif (exists $FontTransTable{$name}) {
451 my $command = $FontTransTable{$name}; #e.g., '\size large'
453 if (! $IsNewParagraph) {
454 print OUTFILE "$pre_space$command";
455 } #otherwise, wait until we've printed the new paragraph command
457 # Store the current font change
458 ($dummy = $command) =~ s/\s*(\S+)\s+(\w+)\s*/$1/;
459 die "Font command error" if !exists $$CurrentFontStatus{$dummy};
460 push (@{$CurrentFontStatus->{$dummy}}, $2);
461 print "\nCurrent $dummy Stack: @{$CurrentFontStatus->{$dummy}}"
465 } elsif ($name eq '&') {
466 if ($thistable = &RelyxTable::in_table) {
467 print OUTFILE "\n\\newline \n";
469 } else {warn "& is illegal outside a table!"}
471 } elsif ($name eq '\\\\' || $name eq '\\newline') {
472 &CheckForNewParagraph; # could be at beginning of par?
473 print OUTFILE "\n\\newline \n";
475 # If we're in a table, \\ means add a row to the table
476 # Note: if we're on the last row of the table, this extra
477 # row will get deleted later. This hack is necessary, because
478 # we don't know while reading when the last row is!
479 if ($thistable = &RelyxTable::in_table) {
483 } elsif ($name eq '\hline') {
484 if ($thistable = &RelyxTable::in_table) {
485 # hcline does hline if no arg is given
487 } else {warn "\\hline is illegal outside a table!"}
491 } elsif ($name =~ /^\\epsf[xy]size$/) {
492 # We need to eat '=' followed by EITHER more text OR
493 # one (or more?!) macros describing a TeX size
494 my $arg = $fileobject->eatMultiToken;
495 my $length = $arg->print;
496 $length =~ s/^\s*=\s*// or warn "weird '$name' command!";
498 # If there's no "cm" or other letters in $length, the next token
499 # ought to be something like \textwidth. Then it will be empty
500 # or just have numbers in it.
501 # This is bugprone. Hopefully not too many people use epsf!
502 if ($length =~ /^[\d.]*\s*$/) {
503 my $next = $fileobject->eatMultiToken;
504 $length .= $next->print;
506 $length =~ s/\s*$//; # may have \n at end
508 # If we can't parse the command, print it in tex mode
509 &RelyxFigure::parse_epsfsize($name, $length) or
510 &print_tex_mode("$name=$length");
514 } elsif ($name =~ /\\verb.*?/) {
515 my $dummy = &Verbatim::copy_verb($fileobject, $eaten);
516 print "\nCopying $name in TeX mode: " if $debug_on;
517 &print_tex_mode ($dummy);
519 # Otherwise it's an unknown token, which must be copied
520 # in TeX mode, along with its arguments, if any
522 if (defined($eaten->relyx_args($fileobject))) {
523 ©_latex_known($eaten, $fileobject);
524 } else { # it's not in MyTokens
525 ©_latex_unknown($eaten, $fileobject);
532 # Handle tokens that take arguments, like \section{},\section*{}
533 if (/^BegArgsToken$/) {
534 my $name = $eaten->token_name;
535 print "$name" if $debug_on;
537 # Handle things that LyX translates as a "LatexCommand" inset
538 if (grep {$_ eq $name} @LatexCommands) {
539 &CheckForNewParagraph; #Start new paragraph if necessary
541 print OUTFILE "$pre_space\n\\begin_inset LatexCommand ";
543 # \bibliography gets handled as a LatexCommand inset, but
544 # it's a special case, cuz LyX syntax expects "\BibTeX"
545 # instead of "\bibliography" (I have no idea why), and because
546 # we have to print extra stuff
547 # Because we might not have encountered the
548 # \bibliographystyle command yet, we write
549 # "insert bibstyle here", and replace that string
550 # with the actual bibliographystyle argument in
551 # LastLyX (i.e., the next pass through the file)
552 if ($name eq "\\bibliography") {
553 print OUTFILE "\\BibTeX[", $bibstyle_insert_string, "]";
555 print OUTFILE "$name";
558 # \cite takes an optional argument, e.g.
559 my $args = $eaten->relyx_args ($fileobject);
560 while ($args =~ s/^o//) {
561 my $tok = $fileobject->eatOptionalArgument;
562 my $dummy = $tok->exact_print;
563 print OUTFILE $dummy;
567 last TYPESW; # skip to the end of the switch
570 if (grep {$_ eq $name} @IncludeCommands) {
571 &CheckForNewParagraph; #Start new paragraph if necessary
572 print OUTFILE "$pre_space\n$Begin_Inset_Include $name\{";
573 last TYPESW; # skip to the end of the switch
576 # This is to handle cases where _ is used, say, in a filename.
577 # When _ is used in math mode, it'll be copied by the math mode
578 # copying subs. Here we handle cases where it's used in non-math.
579 # Examples are filenames for & citation labels.
580 # (It's illegal to use it in regular LaTeX text.)
582 print OUTFILE $eaten->exact_print;
586 # Sectioning and Title environments (using a LyX \layout command)
587 if (exists $ReadCommands::ToLayout->{$name}) {
588 &ConvertToLayout($name);
589 last TYPESW; #done translating
591 # Font characteristics
592 } elsif (exists $FontTransTable{$name}) {
594 my $command = $FontTransTable{$name};
595 ($dummy, $dum2) = ($command =~ /(\S+)\s+(\w+)/);
597 # HACK so that "\emph{hi \emph{bye}}" yields unemph'ed "bye"
598 if ( ($dummy eq "\\emph") &&
599 ($CurrentFontStatus->{$dummy}->[-1] eq "on")) {
600 $dum2 = "default"; # "on" instead of default?
601 $command =~ s/on/default/;
604 # If we're about to start a new paragraph, save writing
605 # this command until *after* we write '\layout Standard'
606 if (! $IsNewParagraph) {
607 print OUTFILE "$pre_space$command";
610 # Store the current font change
611 die "Font command error" if !exists $$CurrentFontStatus{$dummy};
612 push (@{$CurrentFontStatus->{$dummy}}, $dum2);
615 # Handle footnotes and margin notes
616 # Make a new font table & layout stack which will be local to the
617 # footnote or marginpar
618 } elsif (exists $FloatTransTable{$name}) {
619 my $command = $FloatTransTable{$name};
622 print OUTFILE "$pre_space$command";
624 # Make $CurrentFontStatus point to a new (anonymous) font table
625 $CurrentFontStatus = {
626 '\emph' => ["default"],
627 '\family' => ["default"],
628 '\series' => ["default"],
629 '\shape' => ["default"],
630 '\bar' => ["default"],
631 '\size' => ["default"],
632 '\noun' => ["default"],
635 # And make $CurrentLayoutStack point to a new (anon.) stack
636 $CurrentLayoutStack = ["Standard"];
638 # Store whether we're at the end of a paragraph or not
639 # for when we get to end of footnote AND
640 # Note that the footnote text will be starting a new paragraph
641 # Also store the current alignment (justification)
642 $OldINP = $IsNewParagraph; $OldMBD = $MayBeDeeper;
643 $OldAlignment = $CurrentAlignment;
645 $MayBeDeeper = 0; #can't be deeper at beginning of footnote
646 $CurrentAlignment = "";
649 } elsif ($name =~ m/^$AccentTokens$/) {
650 &CheckForNewParagraph; # may be at the beginning of a par
652 print OUTFILE "$pre_space\n",'\i ',$name,'{'
654 # Included Postscript Figures
655 # Currently, all postscript including commands take one
656 # required argument and 0 to 2 optional args, so we can
657 # clump them together in one else.
658 } elsif (grep {$_ eq $name} @GraphicsCommands) {
659 &CheckForNewParagraph; # may be at the beginning of a par
660 my $arg1 = $fileobject->eatOptionalArgument;
661 # arg2 is a token of an empty string for most commands
662 my $arg2 = $fileobject->eatOptionalArgument;
663 my $arg3 = $fileobject->eatRequiredArgument;
664 my $save = $arg1->exact_print . $arg2->exact_print .
667 # Parse and put figure into LyX file
668 # Print it verbatim if we didn't parse correctly
669 my $thisfig = new RelyxFigure::Figure;
670 if ($thisfig->parse_pscommand($name, $arg1, $arg2, $arg3)) {
671 print OUTFILE $thisfig->print_info;
673 &print_tex_mode($eaten->exact_print . $save);
678 } elsif ($name eq "\\multicolumn") {
679 if ($thistable = &RelyxTable::in_table) {
680 # the (simple text) first arg.
681 $dummy = $fileobject->eatRequiredArgument->contents->print;
682 my $group = $fileobject->eatRequiredArgument;
683 $thistable->multicolumn($dummy, $group);
684 } else {warn "\\multicolumn is illegal outside a table!"}
686 } elsif ($name eq '\cline') {
687 if ($thistable = &RelyxTable::in_table) {
688 # the (simple text) first arg.
689 $dummy = $fileobject->eatRequiredArgument->contents->print;
690 # sub hcline does cline if an arg is given
691 $thistable->hcline($dummy);
692 } else {warn "\\cline is illegal outside a table!"}
696 } elsif ($name eq '\bibliographystyle') {
697 $tok = $fileobject->eatRequiredArgument;
699 # There may be >1 token in the {}, e.g. "{a_b}" -> 3 tokens
700 my @toks = $tok->contents;
701 foreach $tok (@toks) {
702 # kludge: CleanTeX adds {} after _
703 $tok = $tok->contents if ref($tok) eq "Text::TeX::Group";
704 $bibstyle_file .= $tok->print;
706 print "\nBibliography style file is $bibstyle_file"if $debug_on;
708 # LyX \bibitem actually looks just like LaTeX bibitem, except
709 # it's in a Bibliography par & there must be a space after the
710 # bibitem command. Note we need to explicitly print the braces...
711 } elsif ($name eq "\\bibitem") {
712 $IsNewParagraph=1; # \bibitem always starts new par. in LyX
713 &CheckForNewParagraph;
715 $tok = $fileobject->eatOptionalArgument;
716 print OUTFILE "$name ", $tok->exact_print, "{";
720 # ensuremath -- copy verbatim until you're done
722 # Note that we'll only get here if the command is NOT in math mode
723 } elsif ($name eq '\ensuremath') {
724 print "\nCopying math beginning with '$name'\n" if $debug_on;
725 my $tok = $fileobject->eatGroup; # eat math expression
726 my $dummy = $tok->exact_print;
727 $dummy =~ s/\{(.*)\}/$1/;
728 $dummy = &fixmath($dummy); # convert '\sp' to '^', etc.
730 &CheckForNewParagraph; # math could be first thing in a par
731 print OUTFILE "$pre_space\n\\begin_inset Formula \\( ";
732 print $dummy if $debug_on;
733 print OUTFILE $dummy;
736 print OUTFILE "\\)\n\\end_inset \n\n";
737 print "\nDone copying math" if $debug_on;
739 # Token in the ReadCommands command list that basic_lyx doesn't
742 ©_latex_known($eaten,$fileobject);
749 # ArgTokens appear when we've used eatRequiredArgument
751 # If we're copying a recognized but untranslatable token in tex mode
752 my $tok = $tex_mode_tokens[-1] || 0;
753 if ($eaten->base_token == $tok) {
754 ©_latex_known($eaten,$fileobject);
760 if (/^EndArgsToken$/) {
761 # If we're copying a recognized but untranslatable token in tex mode
762 my $tok = $tex_mode_tokens[-1] || 0;
763 if ($eaten->base_token eq $tok) {
764 ©_latex_known($eaten,$fileobject);
768 my $name = $eaten->token_name;
769 print "$name" if $debug_on;
771 # Handle things that LyX translates as a "LatexCommand" inset
772 # or "Include" insets
773 if (grep {$_ eq $name} @LatexCommands, @IncludeCommands) {
774 print OUTFILE "\}\n\n\\end_inset \n\n";
776 } elsif (exists $ReadCommands::ToLayout->{$name}) {
779 # Font characteristics
780 # Pop the current FontStatus stack for a given characteristic
781 # and give the new command (e.g., \emph default)
782 } elsif (exists $FontTransTable{$name}) {
783 my $command = $FontTransTable{$name};
784 ($dummy) = ($command =~ /(\S+)\s+\w+/);
785 pop @{$CurrentFontStatus->{$dummy}};
786 $command = "\n$dummy $CurrentFontStatus->{$dummy}->[-1] \n";
787 print OUTFILE "$command";
789 # Footnotes and marginpars
790 } elsif (exists $FloatTransTable{$name}) {
791 print OUTFILE "\n\\end_float \n\n";
793 # Reset the layout stack and font status table pointers to
794 # point to the global stack/table again, instead of the
795 # footnote-specific stack/table
796 $CurrentFontStatus = \%FontStatus;
797 $CurrentLayoutStack = \@LayoutStack;
799 # We need to reissue any font commands (but not layouts)
800 foreach $dummy (keys %$CurrentFontStatus) {
801 if ($CurrentFontStatus->{$dummy}->[-1] ne "default") {
802 print OUTFILE $FontTransTable{$dummy};
806 # Same paragraph status as we had before the footnote started
807 $IsNewParagraph = $OldINP; $MayBeDeeper = $OldMBD;
808 $CurrentAlignment = $OldAlignment;
810 } elsif ($name =~ m/^$AccentTokens$/) {
813 } elsif ($name eq "\\bibitem") {
819 } # end if EndArgsToken
821 # Handle END of scope of local commands like \large
823 my $name = $eaten->token_name; #cmd we're ending, e.g.,\large
824 print $name if $debug_on;
826 if (exists $FontTransTable{$name}) {
827 my $command = $FontTransTable{$name};
828 ($dummy = $command) =~ s/\s*(\S*)\s+(\w+)\s*/$1/; #e.g., '\size'
829 die "Font command error" if !exists $$CurrentFontStatus{$dummy};
830 # TT::OF->check_presynthetic returns local commands FIFO!
831 # So pop font stack, but warn if we pop the wrong thing
832 warn " font confusion?" if
833 pop @{$CurrentFontStatus->{$dummy}} ne $2;
834 print "\nCurrent $dummy Stack: @{$CurrentFontStatus->{$dummy}}"
836 my $newfont = $CurrentFontStatus->{$dummy}->[-1];
837 $command = "\n$dummy $newfont\n";
838 print OUTFILE "$command";
841 warn "Unknown EndLocal token!\n";
847 # We don't print { or }, but we make sure that the spacing is correct
849 if (/^Begin::Group$/) {
850 print OUTFILE "$pre_space";
855 if (/^End::Group$/) {
856 print OUTFILE "$pre_space";
861 if (/^Begin::Group::Args$/) {
862 print $eaten->print," " if $debug_on; # the string "\begin{foo}"
863 my $env = $eaten->environment;
865 # Any environment found in the layouts files
866 if (exists $ReadCommands::ToLayout->{$env}) {
867 &ConvertToLayout($env);
869 # Some environments have an extra argument. In that case,
870 # print the \layout command (cuz these environments always
871 # start new pars). Then either print the extra arg or
872 # ignore it (depending on the environment).
873 if (exists $ExtraArgEnvironments{$env}) {
874 # Should be just one token in the arg.
875 my $arg = $fileobject->eatBalanced->contents->print;
877 if ($ExtraArgEnvironments{$env}) { #print it
878 print "\nArgument $arg to $env environment"
880 $item_preface = $ExtraArgEnvironments{$env} . $arg."\n";
883 print "\nIgnoring argument '$arg' to $env environment"
886 } # end if for reading extra args to \begin command
889 } elsif ($env =~ /^$MathEnvironments$/o) {
890 &CheckForNewParagraph; # may be beginning of paragraph
891 my $begin_text = $eaten->print;
892 print "\nCopying math beginning with '$begin_text'\n"
894 print OUTFILE "\n\\begin_inset Formula $begin_text ";
895 $dummy = &Verbatim::copy_verbatim($fileobject, $eaten);
896 $dummy = &fixmath($dummy); # convert '\sp' to '^', etc.
897 print $dummy if $debug_on;
898 print OUTFILE $dummy;
900 # Alignment environments
901 } elsif (exists $AlignEnvironments{$env}) {
902 # Set it to the command which creates this alignment
903 $CurrentAlignment = $AlignEnvironments{$env};
904 ($dummy) = ($CurrentAlignment =~ /\S+\s+(\w+)/);
905 print "\nNow $dummy-aligning text " if $debug_on;
907 # alignment environments automatically start a new paragraph
910 # Environments lyx translates to floats
911 } elsif (exists $FloatEnvTransTable{$env}) {
912 $tok = $fileobject->eatOptionalArgument;
913 if ($tok && defined ($dummy = $tok->print) && $dummy) {
914 print "\nIgnoring float placement '$dummy'" if $debug_on;
916 my $command = $FloatEnvTransTable{$env};
919 print OUTFILE "$command";
922 } elsif ($env =~ /^tabular$/) { # don't allow tabular* or ctabular
923 # Table must start a new paragraph
924 $IsNewParagraph = 1; $MayBeDeeper = 1;
925 # We want to print table stuff *after* a \layout Standard
926 &CheckForNewParagraph;
928 # Since table info needs to come *before* the table content,
929 # put a line in the output file saying that the *next*
930 # reLyX pass needs to put the table info there
931 print OUTFILE "\n$RelyxTable::TableBeginString\n";
933 # Read and ignore an optional argument [t] or [b]
934 $tok = $fileobject->eatOptionalArgument;
935 if ($tok && defined ($dummy = $tok->print) && $dummy) {
936 print "\nIgnoring positioning arg '$dummy'" if $debug_on;
939 # Read the argument into a TT::Group
940 # (that group may contain groups, e.g. for {clp{10cm}}
941 $tok = $fileobject->eatGroup;
942 new RelyxTable::Table $tok;
945 } elsif ($env eq "document") {
947 #print "\nStarting to translate actual document" if $debug_on;
949 # Special environments to copy as regular text (-r option).
950 # Do this by copying the \begin & \end command in TeX mode
951 # (\Q\E around $env allows *'s in environment names!)
952 } elsif (grep /^\Q$env\E$/, @ReadCommands::regular_env) {
953 print "\nCopying $env environment as regular text\n"
955 $dummy = $eaten->print; # \begin{env}, ignore initial whitespace
956 &print_tex_mode($dummy);
958 # otherwise, it's an unknown environment
959 # In that case, copy everything up to the \end{env}
960 # Save stuff in global tex_mode_string so we can print it
961 # when we read & handle the \end{env}
964 print "\nUnknown environment $env" if $debug_on;
965 $tex_mode_string = "";
967 # For reLyXskip env, don't print the \begin & \end commands!
968 $tex_mode_string .= $eaten->exact_print
969 unless $env eq "reLyXskip";
970 $tex_mode_string .=&Verbatim::copy_verbatim($fileobject,$eaten);
977 if (/^End::Group::Args$/) {
978 print $eaten->print," " if $debug_on; # the string "\end{foo}"
979 my $env = $eaten->environment;
981 # End of list or quote/verse environment
982 # OR special environment given with -t option
983 if (exists $ReadCommands::ToLayout->{$env}) {
985 $item_preface = ""; # reset when at end of List env.
987 # End of math environments
988 } elsif ($env =~ /^$MathEnvironments$/o) {
989 print OUTFILE "\\end{$env}\n\\end_inset \n\n";
990 print "\nDone copying math environment '$env'" if $debug_on;
992 } elsif (exists $AlignEnvironments{$env}) {
993 # Back to block alignment
994 $CurrentAlignment = "";
995 print "\nBack to block alignment" if $debug_on;
997 # assume that \end should end a paragraph
998 # This isn't correct LaTeX, but LyX can't align part of a par
1001 # Environments lyx translates to floats
1002 } elsif (exists $FloatEnvTransTable{$env}) {
1003 print OUTFILE "\n\\end_float \n\n";
1006 } elsif ($env =~ /tabular$/) { # don't allow tabular*
1007 if ($thistable = &RelyxTable::in_table) {
1008 $thistable->done_reading;
1009 print OUTFILE "\n$RelyxTable::TableEndString\n";
1010 } else {warn "found \\end{tabular} when not in table!"}
1012 # Anything after a table will be a new paragraph
1013 $IsNewParagraph = 1; $MayBeDeeper = 1;
1015 } elsif ($env eq "document") {
1016 print "\nDone with document!" if $debug_on;
1018 # "regular" environment given with -r option
1019 } elsif (grep /^\Q$env\E$/, @ReadCommands::regular_env) {
1020 $dummy = $eaten->print; # \end{env}, ignore initial whitespace
1021 &print_tex_mode($dummy);
1023 # Next stuff will be new env.
1024 $IsNewParagraph = 1;
1026 # End of unknown environments. We're already in TeX mode
1028 # Add \end{env} (including initial whitespace) to string
1029 # For reLyXskip environment, don't print \begin & \end commands!
1030 $tex_mode_string .= $eaten->exact_print
1031 unless $env eq "reLyXskip";
1033 &print_tex_mode($tex_mode_string);
1034 print "Done copying unknown environment '$env'" if $debug_on;
1041 # Note for text handling: we have to do lots of stuff to handle
1042 # spaces in (as close as possible to) the same way that LaTeX does
1043 # LaTeX considers all whitespace to be the same, so basically, we
1044 # convert each clump of whitespace to one space. Unfortunately, there
1045 # are special cases, like whitespace at the beginning/end of a par,
1046 # which we have to get rid of to avoid extra spaces in the LyX display.
1047 # \n at the end of a paragraph must be considered like a space,
1048 # because the next line might begin with a token like \LyX. But
1049 # if the next line starts with \begin, say, then an extra space will be
1050 # generated in the LyX file. Oh well. It doesn't affect the dvi file.
1052 my $outstr = $eaten->print; # the actual text
1054 # don't bother printing whitespace
1055 # Note: this avoids the problem of extra whitespace generating
1056 # extra Text::TeX::Paragraphs, which would generate extra
1058 last TYPESW if $outstr =~ /^\s+$/;
1060 # whitespace at beginning of a paragraph is meaningless
1061 # e.g. \begin{foo}\n hello \end{foo} shouldn't print the \n
1062 # (Note: check IsNewParagraph BEFORE calling &CFNP, which zeros it)
1063 my $replace = $IsNewParagraph ? "" : " ";
1064 $outstr =~ s/^\s+/$replace/;
1066 # Only write '\layout Standard' once per paragraph
1067 &CheckForNewParagraph;
1069 # \n\n signals end of paragraph, so get rid of it (and any space
1071 $outstr =~ s/\s*\n\n$//;
1073 # Print the LaTeX text to STDOUT
1074 print "'$outstr'" if $debug_on;
1076 # LyX *ignores* \n and \t, whereas LaTeX considers them just
1078 # Also, many spaces are equivalent to one space in LaTeX
1079 # (But LyX misleadingly displays them on screen, so get rid of them)
1080 $outstr =~ s/\s+/ /g;
1082 # protect spaces in an optional argument if necessary
1083 # Put a SPACE after the argument for List, Description layouts
1084 if ($protect_spaces) {
1085 $dummy = $TextTokenTransTable{'~'};
1087 # This will not handle brackets in braces!
1088 if ($outstr =~ /\]/) { # protect spaces only *until* the bracket
1091 # Note that any \t's have been changed to space already
1092 $tempstr =~ s/ /$dummy/g;
1094 # Print 1 space after the argument (which finished with ])
1095 # Don't print 2 (i.e. remove leading space from $tempstr2)
1096 # don't print the bracket
1097 $tempstr2 =~ s/^ //;
1098 $outstr = "$tempstr $tempstr2";
1099 $protect_spaces = 0; # Done with optional argument
1100 } else { # protect all spaces, since we're inside brackets
1101 $outstr =~ s/ /$dummy/g;
1103 } # end special stuff for protected spaces
1105 # Translate any LaTeX text that requires special LyX handling
1106 foreach $dummy (keys %TextTransTable) {
1107 $outstr =~ s/\Q$dummy\E/$TextTransTable{$dummy}/g;
1110 # "pretty-print" the string. It's not perfect, since there may
1111 # be text in the OUTFILE before $outstr, but it will keep from
1112 # having REALLY long lines.
1113 # Try to use approximately the same word-wrapping as LyX does:
1114 # - before space after a period, except at end of string
1115 # - before first space after column seventy-one
1116 # - after 80'th column
1118 $outstr =~ s/\. (?!$)/.\n / or
1119 $outstr =~ s/(.{71,79}?) /$1\n / or
1120 $outstr =~ s/(.{80})(.)/$1\n$2/ or
1121 last; # exit loop if string is < 79 characters
1124 # Actually print the text
1125 print OUTFILE "$outstr";
1127 } # end TT::Text handling
1129 # The default action - this should never happen!
1130 print("I don't know ",$eaten->print) if $debug_on;
1134 print "\n" if $debug_on;
1136 } #end sub basic_lyx
1138 ######################### TEX MODE SUBROUTINES #########################
1140 # This subroutine copies and prints a latex token and its arguments if any.
1141 # This sub is only needed if the command was not found in the syntax file
1142 # Use exact_print to preserve, e.g., whitespace after macros
1143 sub copy_latex_unknown {
1145 my $fileobject = shift;
1146 my $outstr = $eaten->exact_print;
1147 my ($dummy, $tok, $count);
1149 # Copy the actual word. Copy while you've still got
1150 # arguments. Assume all args must be in the same paragraph
1151 # (There could be new paragraphs *within* args)
1152 # We can't use copy_verbatim (unless we make it smarter) because
1153 # it would choke on nested braces
1154 print "\nUnknown token: '",$eaten->print,"': Copying in TeX mode\n"
1157 while (($dum2 = $fileobject->lookAheadToken) &&
1158 ($dum2 =~ /^[[{]$/)) {
1159 if ($dum2 eq '[') { #copy optional argument - assume it's simple
1160 $tok = $fileobject->eatOptionalArgument;
1161 $outstr .= $tok->exact_print; # also print brackets & whitespace
1164 EAT: { #copied from eatBalanced, but allow paragraphs
1165 die unless defined ($tok = $fileobject->eatMultiToken);
1166 $outstr.="\n",redo EAT if ref($tok) eq "Text::TeX::Paragraph";
1167 $dummy = $tok->exact_print;
1169 # Sometimes, token will be '\n{', e.g.
1170 $count++ if $dummy =~ /^\s*\{$/; # add a layer of nesting
1171 $count-- if $dummy =~ /^\s*\}$/; # end one layer of nesting
1172 redo EAT if $count; #don't dump out until all done nesting
1174 } # end if $dummy = [{
1177 # Add {} after macro if it's followed by '}'. Otherwise, {\foo}bar
1178 # will yield \foobar when LyX creates LaTeX files
1179 $outstr.="{}" if $outstr=~/\\[a-zA-Z]+$/ && $dum2 eq '}';
1181 # Print it out in TeX mode
1182 &print_tex_mode($outstr);
1184 print "\nDone copying unknown token" if $debug_on;
1185 } # end sub copy_latex_unknown
1187 # Copy an untranslatable latex command whose syntax we know, along with its
1189 # The command itself, optional arguments, and untranslatable
1190 # arguments get copied in TeX mode. However, arguments which contain regular
1191 # LaTeX will get translated by reLyX. Do that by printing what you have so
1192 # far in TeX mode, leaving this subroutine, continuing with regular reLyX
1193 # translating, and then returning here when you reach the ArgToken or
1194 # EndArgsToken at the end of the translatable argument.
1195 # We need to keep a stack of the tokens that brought us here, because
1196 # you might have nested commands (e.g., \mbox{hello \fbox{there} how are you}
1197 sub copy_latex_known {
1198 my ($eaten, $fileobject) = (shift,shift);
1199 my $type = ref($eaten);
1200 $type =~ s/^Text::TeX::// or die "unknown token?!";
1202 # token itself for TT::Token, TT::BegArgsToken,
1203 # Corresponding BegArgsToken for ArgToken,EndArgsToken
1204 my $temp_start = $eaten->base_token;
1206 # Initialize tex mode copying
1207 if ($type eq "BegArgsToken" or $type eq "Token") {
1208 print "\nCopying untranslatable token '",$eaten->print,
1209 "' in TeX mode" if $debug_on;
1210 push @tex_mode_tokens, $temp_start;
1212 # initialize the string of stuff we're copying
1213 $tex_mode_string = $eaten->exact_print;
1214 } # Start tex copying?
1217 # This token's next arguments -- returns a string matching /o*[rR]?/
1218 my $curr_args = $eaten->next_args($fileobject);
1220 if ($type eq "EndArgsToken" or $type eq "ArgToken") {
1221 # Print ending '}' for the group we just finished reading
1222 $tex_mode_string .= '}';
1225 # If there could be optional arguments next, copy them
1226 while ($curr_args =~ s/^o// && $fileobject->lookAheadToken eq '[') {
1227 my $opt = $fileobject->eatOptionalArgument;
1228 $tex_mode_string .= $opt->exact_print;
1230 $curr_args =~ s/^o*//; # Some OptArgs may not have appeared
1232 if ($type eq "BegArgsToken" or $type eq "ArgToken") {
1233 # Print beginning '{' for the group we're about to read
1234 $tex_mode_string .= '{';
1237 # Now copy the next required argument, if any
1238 # Copy it verbatim (r), or translate it as regular LaTeX (R)?
1239 if ($curr_args =~ s/^r//) {
1240 my $group = $fileobject->eatRequiredArgument;
1241 my $temp = $group->exact_print;
1242 # Remove braces. They're put in explicitly
1243 $temp =~ s/\{(.*)\}/$1/; # .* is greedy
1244 $tex_mode_string .= $temp;
1246 } elsif ($curr_args =~ s/^R//) {
1247 print "\n" if $debug_on;
1248 &print_tex_mode($tex_mode_string);
1249 $tex_mode_string = "";
1250 print "\nTranslating this argument for ",$temp_start->print,
1251 " as regular LaTeX" if $debug_on;
1253 } else { # anything but '' is weird
1254 warn "weird arg $curr_args to ",$temp_start->print,"\n" if $curr_args;
1257 # Finished tex mode copying
1258 if ($type eq "Token" or $type eq "EndArgsToken") {
1260 # Add {} to plain tokens followed by { or }. Otherwise {\foo}bar
1261 # and \foo{bar} yield \foobar in the LaTeX files created by LyX
1263 if ($type eq "Token" and
1264 $dummy=$fileobject->lookAheadToken and
1267 $tex_mode_string .= '{}';
1270 # Print out the string
1271 print "\n" if $debug_on;
1272 &print_tex_mode($tex_mode_string);
1273 $tex_mode_string = "";
1275 # We're done with this token
1276 pop(@tex_mode_tokens);
1278 my $i = $type eq "Token" ? "" : " and its arguments";
1279 my $j = $temp_start->print;
1280 print "\nDone copying untranslatable token '$j'$i in TeX mode"
1282 } # end tex copying?
1283 } # end sub copy_latex_known
1285 # Print a string in LyX "TeX mode"
1286 # The goal of this subroutine is to create a block of LyX which will be
1287 # translated exactly back to the original when LyX creates its temporary LaTeX
1288 # file prior to creating a dvi file.
1289 # Don't print \n\n at the end of the string... instead just set the new
1290 # paragraph flag. Also, don't print whitespace at the beginning of the string.
1291 # Print nothing if it's the beginning of a paragraph, or space otherwise.
1292 # These two things avoid extra C-Enter's in the LyX file
1293 sub print_tex_mode {
1296 print "'$outstr'" if $debug_on;
1298 # Handle extra \n's (& spaces) at beginning & end of string
1299 my $str_ends_par = ($outstr =~ s/\n{2,}$//);
1300 if ($IsNewParagraph) {
1301 $outstr =~ s/^\s+//; # .e.g, $outstr follows '\begin{quote}'
1303 # Any whitespace is equivalent to one space in LaTeX
1304 $outstr =~ s/^\s+/ /; # e.g. $outstr follows "\LaTeX{}" or "Hi{}"
1307 # Check whether string came right at the beginning of a new paragraph
1308 # This *might* not be necessary. Probably can't hurt.
1309 &CheckForNewParagraph;
1312 print OUTFILE "$start_tex_mode";
1314 # Do TeX mode translation;
1315 $outstr =~ s/\\/\n\\backslash /g;
1316 # don't translate \n in '\n\backslash' that we just made!
1317 $outstr =~ s/\n(?!\\backslash)/\n\\newline \n/g;
1319 # Print the actual token + arguments if any
1320 print OUTFILE $outstr;
1322 # Get OUT of LaTeX mode (and end nesting if nec.)
1323 print OUTFILE "$end_tex_mode";
1324 $IsNewParagraph = $str_ends_par;
1327 } # end sub print_tex_mode
1329 ############################ LAYOUT SUBROUTINES ###########################
1331 sub CheckForNewParagraph {
1332 # This subroutine makes sure we only write \layout command once per paragraph
1333 # It's mostly necessary cuz 'Standard' layout is the default in LaTeX;
1334 # there is no command which officially starts a standard environment
1335 # If we're in a table, new layouts aren't allowed, so just return
1336 # If $IsNewParagraph is 0, it does nothing
1337 # If $INP==1, It starts a new paragraph
1338 # If $CurrentAlignment is set, it prints the alignment command for this par.
1339 # If $MayBeDeeper==1 and we're currently within a list environment,
1340 # it starts a "deeper" Standard paragraph
1342 my $layout = $$CurrentLayoutStack[-1];
1344 return if &RelyxTable::in_table;
1346 if ($IsNewParagraph) {
1347 # Handle standard text within a list environment specially
1349 if ($layout =~ /^$ListLayouts$/o) {
1350 push (@$CurrentLayoutStack, "Standard");
1351 print "\nCurrent Layout Stack: @$CurrentLayoutStack\n"
1353 print OUTFILE "\n\\begin_deeper ";
1354 $layout = "Standard";
1356 $MayBeDeeper = 0; # Don't test again until new paragraph
1359 # Print layout command itself
1360 print OUTFILE "\n\\layout $layout\n\n";
1361 print OUTFILE $CurrentAlignment if $CurrentAlignment;
1363 # Now that we've written the command, it's no longer a new paragraph
1364 $IsNewParagraph = 0;
1366 # And we're no longer waiting to see if this paragraph is empty
1369 # When you write a new paragraph, reprint any font commands
1370 foreach $dummy (keys %$CurrentFontStatus) {
1371 my $currf = $CurrentFontStatus->{$dummy}->[-1];
1372 if ($currf ne "default") {
1373 print OUTFILE "\n$dummy $currf \n";
1377 } # end sub CheckForNewParagraph
1379 sub ConvertToLayout {
1380 # This subroutine begins a new layout, pushing onto the layout stack, nesting
1381 # if necessary. It doesn't actually write the \layout command -- that's
1382 # done by CheckForNewParagraph.
1383 # The subroutine assumes that it's being passed an environment name or macro
1384 # which is known and which creates a known layout
1385 # It uses the ToLayout hash (created by the ReadCommands module) which
1386 # gives the LyX layout for a given LaTeX command or environment
1387 # Arg0 is the environment or macro
1390 my $layoutref = $ReadCommands::ToLayout->{$name};
1391 my $layout = $layoutref->{'layout'};
1392 my $keepempty = $layoutref->{'keepempty'};
1393 my $dummy = ($name =~ /^\\/ ? "macro" : "environment");
1394 print "\nChanging $dummy $name to layout $layout" if $debug_on;
1396 # Nest if the layout stack has more than just "Standard" in it
1397 if ($#{$CurrentLayoutStack} > 0) {
1398 # Die here for sections & things that can't be nested!
1399 print " Nesting!" if $debug_on;
1400 print OUTFILE "\n\\begin_deeper ";
1403 # If we still haven't printed the *previous* \layout command because that
1404 # environment is empty, print it now! (This happens if an environment
1405 # is nested inside a keepempty, like slide.)
1406 &CheckForNewParagraph if $PendingLayout;
1408 # Put the new layout onto the layout stack
1409 push @$CurrentLayoutStack, $layout;
1410 print "\nCurrent Layout Stack: @$CurrentLayoutStack" if $debug_on;
1412 # Upcoming text will be new paragraph, needing a new layout cmd
1413 $IsNewParagraph = 1;
1415 # Test for nested "Standard" paragraph in upcoming text?
1416 # Some environments can nest. Sections & Title commands can't
1417 $MayBeDeeper = $layoutref->{"nestable"};
1419 # We haven't yet read any printable stuff in the new paragraph
1420 # If this is a layout that's allowed to be empty, prepare for an
1422 $PendingLayout = $keepempty;
1424 } # end sub ConvertToLayout
1427 # This subroutine ends a layout, popping the layout stack, etc.
1428 # The subroutine assumes that it's being passed an environment name or macro
1429 # which is known and which creates a known layout
1430 # It uses the ToLayout hash (created by the ReadCommands module) which
1431 # gives the LyX layout for a given LaTeX command or environment
1432 # Arg0 is the environment or macro
1435 my $layoutref = $ReadCommands::ToLayout->{$name};
1436 my $layout = $layoutref->{'layout'};
1437 my $dummy = ($name =~ /^\\/ ? "macro" : "environment");
1438 print "\nEnding $dummy $name (layout $layout)" if $debug_on;
1440 # If we still haven't printed the *previous* \layout command because that
1441 # environment is empty, print it now! Before we pop the stack!
1442 # This happens for a totally empty, non-nesting environment,
1443 # like hollywood.sty's fadein
1444 &CheckForNewParagraph if $PendingLayout;
1446 my $mylayout = pop (@$CurrentLayoutStack);
1448 # If a standard paragraph was the last thing in a list, then
1449 # we need to end_deeper and then pop the actual list layout
1450 # This should only happen if the Standard layout was nested
1451 # in a nestable layout. We don't check.
1452 if ($mylayout eq "Standard") {
1453 print OUTFILE "\n\\end_deeper ";
1454 print " End Standard Nesting!" if $debug_on;
1455 $mylayout = pop (@$CurrentLayoutStack);
1458 # The layout we popped off the stack had better match the
1459 # environment (or macro) we're ending!
1460 if ($mylayout ne $layout) { die "Problem with Layout Stack!\n"};
1461 print "\nCurrent Layout Stack: @$CurrentLayoutStack" if $debug_on;
1463 # If we're finishing a nested layout, we need to end_deeper
1464 # This should only happen if the layout was nested
1465 # in a nestable layout. We don't check.
1466 # Note that if we're nested in a list environment and the
1467 # NEXT paragraph is Standard, then we'll have an extra
1468 # \end_deeper \begin_deeper in the LyX file. It's sloppy
1469 # but it works, and LyX will get rid of it when it
1471 if ($#{$CurrentLayoutStack} > 0) {
1472 print " End Nesting!" if $debug_on;
1473 print OUTFILE "\n\\end_deeper ";
1476 # Upcoming text will be new paragraph, needing a new layout cmd
1477 $IsNewParagraph = 1;
1479 # Test for nested "Standard" paragraph in upcoming text?
1480 # Some environments can nest. Sections & Title commands can't
1481 $MayBeDeeper = $layoutref->{"nestable"};
1482 } # end sub EndLayout
1484 ####################### MISCELLANEOUS SUBROUTINES ###########################
1486 # Translate math commands LyX doesn't support into commands it does support
1491 (.*?) # non-token matter ($1)
1492 (\\ # token ($2) is a backslash followed by ...
1493 ( ([^A-Za-z] \*?) | # non-letter (and *) ($4) OR
1494 ([A-Za-z]+ \*?) ) # letters (and *) ($5)
1495 )//xs) # /x to allow whitespace/comments, /s to copy \n's
1499 if (exists $ReadCommands::math_trans{$tok}) {
1500 $tok = $ReadCommands::math_trans{$tok};
1501 # add ' ' in case we had, e.g., \|a, which would become \Verta
1502 # Only need to do it in those special cases
1504 defined $4 && $tok =~ /[A-Za-z]$/ && $input =~ /^[A-Za-z]/;
1508 $output .= $input; # copy what's left in $input
1513 1; # return true to calling subroutine