]> git.lyx.org Git - lyx.git/blob - lib/reLyX/BasicLyX.pm
fix typo that put too many include paths for most people
[lyx.git] / lib / reLyX / BasicLyX.pm
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.
5
6 package BasicLyX;
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)
10 use strict;
11
12 use RelyxTable; # Handle LaTeX tables
13 use RelyxFigure; # Handle LaTeX figures
14 use Verbatim;   # Copy stuff verbatim
15
16 use vars qw($bibstyle_insert_string $bibstyle_file $Begin_Inset_Include);
17 $bibstyle_insert_string = "%%%%%Insert bibliographystyle file here!";
18 $bibstyle_file = "";
19 $Begin_Inset_Include = "\\begin_inset Include";
20
21 #################### PACKAGE-WIDE VARIABLES ###########################
22 my $debug_on; # is debugging on?
23
24 ######
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
33
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;
40
41 # HACK to protect spaces within optional argument to \item
42 my $protect_spaces = 0;
43
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
46 my $MayBeDeeper = 0;
47 my $OldMBD; #Save $MBD during footnotes -- this should very rarely be necessary!
48
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;
54
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
60 my %FontStatus = (
61     '\emph' => ["default"],
62     '\family' => ["default"],
63     '\series' => ["default"],
64     '\shape' => ["default"],
65     '\bar' => ["default"],
66     '\size' => ["default"],
67     '\noun' => ["default"],
68 );
69 my $CurrentFontStatus = \%FontStatus;
70
71 # Currently aligning paragraphs right, left, or center?
72 my $CurrentAlignment = "";
73 my $OldAlignment; # Save $AS during footnotes
74
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
78
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";
82
83 # String to write before each item
84 my $item_preface = "";
85
86 #############  INFORMATION ABOUT LATEX AND LYX   #############################
87 # LyX translations of LaTeX font commands
88 my %FontTransTable = (
89    # Font commands
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
103
104 # Font size commands
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",
117 );
118
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",
125 );
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",
132 );
133
134 # Simple LaTeX tokens which are turned into small pieces of LyX text
135 my %TextTokenTransTable = (
136     # LaTeX escaped characters
137     '\_' => '_',
138     '\%' => '%',
139     '\$' => '$',
140     '\&' => '&',
141     '\{' => '{',
142     '\}' => '}',
143     '\#' => '#',
144     '\~' => '~',
145     '\^' => '^',
146     # \i and \j are used in accents. LyX doesn't recognize them in plain
147     #    text. Hopefully, this isn't a problem.
148     '\i' => '\i',
149     '\j' => '\j',
150
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",
157     '\LaTeX' => "LaTeX",
158     '\LaTeXe' => "LaTeX2e",
159     '\TeX'    => "TeX",
160     '\LyX'    => "LyX",
161     '\lyxarrow' => "\\SpecialChar \\menuseparator\n",
162     '\hfill'  => "\n\\hfill \n",
163     '\noindent'        => "\n\\noindent \n",
164     '\textbackslash'   => "\n\\backslash \n",
165     '\textgreater'     => ">",
166     '\textless'        => "<",
167     '\textbar'         => "|",
168     '\textasciitilde'  => "~",
169 );
170
171 # LyX translations of some plain LaTeX text (TeX parser won't recognize it
172 #     as a Token, so we need to translate the Text::TeX::Text token.)
173 my %TextTransTable = (
174     # Double quotes
175     "``" => "\n\\begin_inset Quotes eld\n\\end_inset \n\n",
176     "''" => "\n\\begin_inset Quotes erd\n\\end_inset \n\n",
177
178     # Tokens that don't start with a backslash, so parser won't recognize them
179     # (LyX doesn't support them, so we just print them in TeX mode)
180     '?`' => "$start_tex_mode?`$end_tex_mode",
181     '!`' => "$start_tex_mode!`$end_tex_mode",
182 );
183
184 # Things that LyX translates as "LatexCommand"s
185 # E.g., \ref{foo} ->'\begin_inset LatexCommand \ref{foo}\n\n\end_inset \n'
186 # (Some take arguments, others don't)
187 my @LatexCommands = map {"\\$_"} qw(ref pageref label cite bibliography
188                                  index printindex tableofcontents
189                                  listofalgorithms listoftables listoffigures);
190 my @IncludeCommands = map {"\\$_"} qw(input include);
191 # Included postscript files
192 # LyX 1.0 can't do \includegraphics*!
193 my @GraphicsCommands = map {"\\$_"} qw(epsf epsffile epsfbox
194                                        psfig epsfig includegraphics);
195
196 # Accents. Most of these take an argument -- the thing to accent
197 # (\l and \L are handled as InsetLatexAccents, so they go here too)
198 my $AccentTokens = "\\\\[`'^#~=.bcdHklLrtuv\"]";
199
200 # Environments which describe justifying (converted to LyX \align commands)
201 #    and the corresponding LyX commands
202 my %AlignEnvironments = (
203     "center" => "\n\\align center \n",
204     "flushright" => "\n\\align right \n",
205     "flushleft" => "\n\\align left \n",
206 );
207
208 # Some environments' begin commands take an extra argument
209 # Print string followed by arg for each item in the list, or ignore the arg ("")
210 my %ExtraArgEnvironments = (
211     "thebibliography" => "",
212     "lyxlist" =>'\labelwidthstring ',
213     "labeling" =>'\labelwidthstring ', # koma script list
214 );
215
216 # Math environments are copied verbatim
217 my $MathEnvironments = "(math|displaymath|xxalignat|(equation|eqnarray|align|alignat|xalignat|multline|gather)(\\*)?)";
218 # ListLayouts may have standard paragraphs nested inside them.
219 my $ListLayouts = "Itemize|Enumerate|Description";
220
221 #####################   PARSER INVOCATION   ##################################
222 sub call_parser {
223 # This subroutine calls the TeX parser & translator
224 # Before it does that, it does lots of setup work to get ready for parsing.
225 # Arg0 is the file to read (clean) LaTeX from
226 # Arg1 is the file to write LyX to
227 # Arg2 is the file to read layouts from (e.g., in LYX_DIR/layouts/foo.layout)
228
229     my ($InFileName, $OutFileName) = (shift,shift);
230
231 # Before anything else, set the package-wide variables based on the
232 #    user-given flags
233     # opt_d is set to 1 if '-d' option given, else (probably) undefined
234     $debug_on = (defined($main::opt_d) && $main::opt_d);
235
236     # Hash of tokens passed to the TeX parser
237     # Many values are $Text::TeX::Tokens{'\operatorname'}, which has
238     #    Type=>report_args and count=>1
239     # Note that we don't have to bother putting in tokens which will be simply
240     #    translated (e.g., from %TextTokenTransTable).
241     my %MyTokens = ( 
242         '{' => $Text::TeX::Tokens{'{'},
243         '}' => $Text::TeX::Tokens{'}'},
244         '\begin' => $Text::TeX::Tokens{'\begin'},
245         '\end' => $Text::TeX::Tokens{'\end'},
246
247         # Lots of other commands will be made by ReadCommands:Merge
248         # by reading the LaTeX syntax file
249
250         # Font sizing commands (local)
251         '\tiny' => {Type => 'local'},
252         '\small' => {Type => 'local'},
253         '\scriptsize' => {Type => 'local'},
254         '\footnotesize' => {Type => 'local'},
255         '\small' => {Type => 'local'},
256         '\normalsize' => {Type => 'local'},
257         '\large' => {Type => 'local'},
258         '\Large' => {Type => 'local'},
259         '\LARGE' => {Type => 'local'},
260         '\huge' => {Type => 'local'},
261         '\Huge' => {Type => 'local'},
262
263         # Tokens to ignore (which make a new paragraph)
264         # Just pretend they actually ARE new paragraph markers!
265         '\maketitle' => {'class' => 'Text::TeX::Paragraph'},
266     );
267     
268     # Now add to MyTokens all of the commands that were read from the
269     #    commands file by package ReadCommands
270     &ReadCommands::Merge(\%MyTokens);
271
272 # Here's the actual subroutine. The above is all preparation
273     # Output LyX file
274     my $zzz = $debug_on ? " ($InFileName --> $OutFileName)\n" : "... ";
275     print STDERR "Translating$zzz";
276     open (OUTFILE,">$OutFileName");
277
278     # Open the file to turn into LyX.
279     my $infile = new Text::TeX::OpenFile $InFileName,
280         'defaultact' => \&basic_lyx,
281         'tokens' => \%MyTokens;
282
283     # Process what's left of the file (everything from \begin{document})
284     $infile->process;
285
286     # Last line of the LyX file
287     print OUTFILE "\n\\the_end\n";
288     close OUTFILE;
289     #warn "Done with basic translation\n";
290     return;
291 } # end subroutine call_parser
292
293 ##########################   MAIN TRANSLATOR SUBROUTINE   #####################
294 sub basic_lyx {
295 # This subroutine is called by Text::TeX::process each time subroutine
296 #     eat returns a value.
297 # Argument 0 is the return value from subroutine eat
298 # Argument 1 is the Text::TeX::OpenFile (namely, $TeXfile)
299     my $eaten = shift;
300     my $fileobject = shift;
301
302     # This handles most but maybe not all comments
303     # THere shouldn't be any if we've run CleanTeX.pl
304     print "Comment: ",$eaten->comment if defined $eaten->comment && $debug_on;
305
306     my $type = ref($eaten);
307     print "$type " if $debug_on;
308
309     # This loop is basically just a switch. However, making it a for
310     #    (1) makes $_ = $type (convenient)
311     #    (2) allows us to use things like next and last
312     TYPESW: for ($type) {
313
314         # some pre-case work
315         s/^Text::TeX:://o or die "unknown token?!";
316         my ($dummy, $tok);
317         my ($thistable);
318
319         # The parser puts whitespace before certain kinds of tokens along
320         # with that token. If that happens, save a space
321         my $pre_space = ""; # whitespace before a token
322         if (/BegArgsToken|^Token|::Group$/) {
323             $dummy = $eaten->exact_print;
324             # Only set prespace if we match something
325             #    We wouldn't want it to be more than one space, since that's
326             # illegal in LyX. Also, replace \t or \n with ' ' since they are
327             # ignored in LyX. Hopefully, this won't lead to anything worse
328             # than some lines with >80 chars
329             #    Finally, don't put a space at the beginning of a new paragraph
330             if (($dummy =~ /^\s+/) && !$IsNewParagraph) {
331                 $pre_space = " ";
332             }
333         }
334
335         # Handle blank lines.
336         if (m/^Paragraph$/o) {
337             # $INP <>0 means We will need a new layout command
338             $IsNewParagraph = 1;
339
340             # $MBD means start a begin_deeper within list environments
341             #    unless there's an \item command
342             $MayBeDeeper = 1;
343
344             last TYPESW;
345         }
346
347         # If, e.g., there's just a comment in this token, don't do anything
348         # This actually shouldn't happen if CleanTeX has already removed them
349         last TYPESW if !defined $eaten->print;
350         
351         # Handle LaTeX tokens
352         if (/^Token$/o) {
353
354             my $name = $eaten->token_name; # name of the token, e.g., "\large"
355             print "'$name' " if $debug_on;
356
357             # Tokens which turn into a bit of LyX text
358             if (exists $TextTokenTransTable{$name}) {
359                 &CheckForNewParagraph; #Start new paragraph if necessary
360
361                 my $to_print = $TextTokenTransTable{$name};
362
363                 # \@ has to be specially handled, because it depends on
364                 # the character AFTER the \@
365                 if ($name eq '\@') {
366                     my $next = $fileobject->eatGroup(1);
367                     my $ch="";
368                     $ch = $next->print or warn "\@ confused me!\n";
369                     if ($ch eq '.') {
370                         # Note: \@ CAN'T have pre_space before it
371                         print OUTFILE "$to_print$ch\n";
372                         print "followed by $ch" if $debug_on;
373                     } else {
374                        warn "LyX (or LaTeX) can't handle '$ch' after $name\n";
375                         print OUTFILE $ch;
376                     }
377
378                 } else { # it's not \@
379                     # Print the translated text (include preceding whitespace)
380                     print OUTFILE "$pre_space$to_print";
381                 } # end special handling for \@
382
383             # Handle tokens that LyX translates as a "LatexCommand" inset
384             } elsif (grep {$_ eq $name} @LatexCommands) {
385                 &CheckForNewParagraph; #Start new paragraph if necessary
386                 print OUTFILE "$pre_space\n\\begin_inset LatexCommand ",
387                                $name,
388                               "\n\n\\end_inset \n\n";
389
390             # Math -- copy verbatim until you're done
391             } elsif ($name eq '\(' || $name eq '\[') {
392                 print "\nCopying math beginning with '$name'\n" if $debug_on;
393                 # copy everything until end text
394                 $dummy = &Verbatim::copy_verbatim($fileobject, $eaten);
395                 $dummy = &fixmath($dummy); # convert '\sp' to '^', etc.
396
397                 &CheckForNewParagraph; # math could be first thing in a par
398                 print OUTFILE "$pre_space\n\\begin_inset Formula $name ";
399                 print $dummy if $debug_on;
400                 print OUTFILE $dummy;
401
402             } elsif ($name eq '\)' || $name eq '\]') {
403                 # end math
404                 print OUTFILE "$name\n\\end_inset \n\n";
405                 print "\nDone copying math ending with '$name'" if $debug_on;
406
407             # Items in list environments
408             } elsif ($name eq '\item') {
409                 
410                 # What if we had a nested "Standard" paragraph?
411                 # Then write \end_deeper to finish the standard layout
412                 #     before we write the new \layout ListEnv command
413                 if ($$CurrentLayoutStack[-1] eq "Standard") {
414                     pop (@$CurrentLayoutStack); # take "Standard" off the stack
415                     print OUTFILE "\n\\end_deeper ";
416                     print "\nCurrent Layout Stack: @$CurrentLayoutStack"
417                           if $debug_on;
418                 } # end deeper if
419
420                 # Upcoming text (the item) will be a new paragraph, 
421                 #    requiring a new layout command based on whichever
422                 #    kind of list environment we're in
423                 $IsNewParagraph = 1;
424
425                 # But since we had an \item command, DON'T nest a
426                 #    deeper "Standard" paragraph in the list
427                 $MayBeDeeper = 0;
428
429                 # Check for an optional argument to \item
430                 # If so, within the [] we need to protect spaces
431                 # TODO: In fact, for description, if there's no [] or
432                 # there's an empty [], then we need to write a ~, since LyX
433                 # will otherwise make the next word the label
434                 # If it's NOT a description & has a [] then we're stuck!
435                 # They need to fix the bullets w/in lyx!
436                 if (($dummy = $fileobject->lookAheadToken) &&
437                     ($dummy =~ /\s*\[/)) {
438                     $fileobject->eatFixedString('\['); # eat the [
439                     $protect_spaces = 1;
440                 }
441
442                 # Special lists (e.g. List layout) have to print something
443                 # before each item. In that case, CFNP and print it
444                 if ($item_preface) {
445                     &CheckForNewParagraph;
446                     print OUTFILE $item_preface;
447                 }
448
449             # Font sizing commands
450             # (Other font commands are TT::BegArgsTokens because they take
451             #     arguments. Font sizing commands are 'local' TT::Tokens)
452             } elsif (exists $FontTransTable{$name}) {
453                 my $command = $FontTransTable{$name}; #e.g., '\size large'
454
455                 if (! $IsNewParagraph) {
456                     print OUTFILE "$pre_space$command";
457                 } #otherwise, wait until we've printed the new paragraph command
458
459                 # Store the current font change
460                 ($dummy = $command) =~ s/\s*(\S+)\s+(\w+)\s*/$1/;
461                 die "Font command error" if !exists $$CurrentFontStatus{$dummy};
462                 push (@{$CurrentFontStatus->{$dummy}}, $2);
463                 print "\nCurrent $dummy Stack: @{$CurrentFontStatus->{$dummy}}"
464                       if $debug_on;
465
466             # Table stuff
467             } elsif ($name eq '&') {
468                 if ($thistable = &RelyxTable::in_table) {
469                     print OUTFILE "\n\\newline \n";
470                     $thistable->nextcol;
471                 } else {warn "& is illegal outside a table!"}
472
473             } elsif ($name eq '\\\\' || $name eq '\\newline') {
474                 &CheckForNewParagraph; # could be at beginning of par?
475                 print OUTFILE "\n\\newline \n";
476
477                 # If we're in a table, \\ means add a row to the table
478                 # Note: if we're on the last row of the table, this extra
479                 # row will get deleted later. This hack is necessary, because
480                 # we don't know while reading when the last row is!
481                 if ($thistable = &RelyxTable::in_table) {
482                     $thistable->addrow;
483                 }
484
485             } elsif ($name eq '\hline') {
486                 if ($thistable = &RelyxTable::in_table) {
487                     # hcline does hline if no arg is given
488                     $thistable->hcline;
489                 } else {warn "\\hline is illegal outside a table!"}
490
491             # Figures
492
493             } elsif ($name =~ /^\\epsf[xy]size$/) {
494                 # We need to eat '=' followed by EITHER more text OR
495                 # one (or more?!) macros describing a TeX size
496                 my $arg = $fileobject->eatMultiToken;
497                 my $length = $arg->print;
498                 $length =~ s/^\s*=\s*// or warn "weird '$name' command!";
499
500                 # If there's no "cm" or other letters in $length, the next token
501                 # ought to be something like \textwidth. Then it will be empty
502                 # or just have numbers in it.
503                 # This is bugprone. Hopefully not too many people use epsf!
504                 if ($length =~ /^[\d.]*\s*$/) {
505                     my $next = $fileobject->eatMultiToken;
506                     $length .= $next->print;
507                 }
508                 $length =~ s/\s*$//; # may have \n at end
509
510                 # If we can't parse the command, print it in tex mode
511                 &RelyxFigure::parse_epsfsize($name, $length) or 
512                     &print_tex_mode("$name=$length");
513
514             # Miscellaneous...
515
516             } elsif ($name =~ /\\verb.*?/) {
517                 my $dummy = &Verbatim::copy_verb($fileobject, $eaten);
518                 print "\nCopying $name in TeX mode: " if $debug_on;
519                 &print_tex_mode ($dummy);
520
521             # Otherwise it's an unknown token, which must be copied
522             #     in TeX mode, along with its arguments, if any
523             } else {
524                 if (defined($eaten->relyx_args($fileobject))) {
525                    &copy_latex_known($eaten, $fileobject);
526                 } else { # it's not in MyTokens
527                     &copy_latex_unknown($eaten, $fileobject);
528                 }
529             }
530
531             last TYPESW;
532         }
533         
534         # Handle tokens that take arguments, like \section{},\section*{}
535         if (/^BegArgsToken$/) {
536             my $name = $eaten->token_name;
537             print "$name" if $debug_on;
538
539             # Handle things that LyX translates as a "LatexCommand" inset
540             if (grep {$_ eq $name} @LatexCommands) {
541                 &CheckForNewParagraph; #Start new paragraph if necessary
542
543                 print OUTFILE "$pre_space\n\\begin_inset LatexCommand ";
544
545                 #    \bibliography gets handled as a LatexCommand inset, but
546                 # it's a special case, cuz LyX syntax expects "\BibTeX"
547                 # instead of "\bibliography" (I have no idea why), and because
548                 # we have to print extra stuff
549                 #    Because we might not have encountered the
550                 # \bibliographystyle command yet, we write
551                 # "insert bibstyle here", and replace that string
552                 # with the actual bibliographystyle argument in
553                 # LastLyX (i.e., the next pass through the file)
554                 if ($name eq "\\bibliography") {
555                     print OUTFILE "\\BibTeX[", $bibstyle_insert_string, "]";
556                 } else {
557                     print OUTFILE "$name";
558                 }
559
560                 # \cite takes an optional argument, e.g.
561                 my $args = $eaten->relyx_args ($fileobject);
562                 while ($args =~ s/^o//) {
563                     my $tok = $fileobject->eatOptionalArgument;
564                     my $dummy = $tok->exact_print;
565                     print OUTFILE $dummy;
566                 }
567
568                 print OUTFILE "\{";
569                 last TYPESW; # skip to the end of the switch
570             }
571
572             if (grep {$_ eq $name} @IncludeCommands) {
573                 &CheckForNewParagraph; #Start new paragraph if necessary
574                 print OUTFILE "$pre_space\n$Begin_Inset_Include $name\{";
575                 last TYPESW; # skip to the end of the switch
576             }
577
578             # This is to handle cases where _ is used, say, in a filename.
579             # When _ is used in math mode, it'll be copied by the math mode
580             # copying subs. Here we handle cases where it's used in non-math.
581             # Examples are filenames for \include & citation labels.
582             # (It's illegal to use it in regular LaTeX text.)
583             if ($name eq "_") {
584                print OUTFILE $eaten->exact_print;
585                last TYPESW;
586             }
587
588             # Sectioning and Title environments (using a LyX \layout command)
589             if (exists $ReadCommands::ToLayout->{$name}) {
590                 &ConvertToLayout($name);
591                 last TYPESW; #done translating
592
593             # Font characteristics
594             } elsif (exists $FontTransTable{$name}) {
595                 my $dum2;
596                 my $command = $FontTransTable{$name};
597                 ($dummy, $dum2) = ($command =~ /(\S+)\s+(\w+)/);
598
599                 # HACK so that "\emph{hi \emph{bye}}" yields unemph'ed "bye"
600                 if ( ($dummy eq "\\emph") && 
601                      ($CurrentFontStatus->{$dummy}->[-1] eq "on")) {
602                        $dum2 = "default"; # "on" instead of default?
603                        $command =~ s/on/default/;
604                 }
605
606                 # If we're about to start a new paragraph, save writing
607                 #    this command until *after* we write '\layout Standard'
608                 if (! $IsNewParagraph) {
609                     print OUTFILE "$pre_space$command";
610                 }
611
612                 # Store the current font change
613                 die "Font command error" if !exists $$CurrentFontStatus{$dummy};
614                 push (@{$CurrentFontStatus->{$dummy}}, $dum2);
615
616
617             # Handle footnotes and margin notes
618             # Make a new font table & layout stack which will be local to the 
619             #    footnote or marginpar
620             } elsif (exists $FloatTransTable{$name}) {
621                 my $command = $FloatTransTable{$name};
622
623                 # Open the footnote
624                 print OUTFILE "$pre_space$command";
625
626                 # Make $CurrentFontStatus point to a new (anonymous) font table
627                 $CurrentFontStatus =  {
628                     '\emph' => ["default"],
629                     '\family' => ["default"],
630                     '\series' => ["default"],
631                     '\shape' => ["default"],
632                     '\bar' => ["default"],
633                     '\size' => ["default"],
634                     '\noun' => ["default"],
635                 };
636
637                 # And make $CurrentLayoutStack point to a new (anon.) stack
638                 $CurrentLayoutStack = ["Standard"];
639
640                 # Store whether we're at the end of a paragraph or not
641                 #    for when we get to end of footnote AND 
642                 # Note that the footnote text will be starting a new paragraph
643                 # Also store the current alignment (justification)
644                 $OldINP = $IsNewParagraph; $OldMBD = $MayBeDeeper;
645                 $OldAlignment = $CurrentAlignment;
646                 $IsNewParagraph = 1;
647                 $MayBeDeeper = 0; #can't be deeper at beginning of footnote
648                 $CurrentAlignment = "";
649
650             # Accents
651             } elsif ($name =~ m/^$AccentTokens$/) {
652                 &CheckForNewParagraph; # may be at the beginning of a par
653
654                 print OUTFILE "$pre_space\n",'\i ',$name,'{'
655             
656             # Included Postscript Figures
657             # Currently, all postscript including commands take one
658             # required argument and 0 to 2 optional args, so we can
659             # clump them together in one else.
660             } elsif (grep {$_ eq $name} @GraphicsCommands) {
661                 &CheckForNewParagraph; # may be at the beginning of a par
662                 my $arg1 = $fileobject->eatOptionalArgument;
663                 # arg2 is a token of an empty string for most commands
664                 my $arg2 = $fileobject->eatOptionalArgument;
665                 my $arg3 = $fileobject->eatRequiredArgument;
666                 my $save = $arg1->exact_print . $arg2->exact_print .
667                            $arg3->exact_print;
668
669                 # Parse and put figure into LyX file
670                 # Print it verbatim if we didn't parse correctly
671                 my $thisfig = new RelyxFigure::Figure;
672                 if ($thisfig->parse_pscommand($name, $arg1, $arg2, $arg3)) {
673                     print OUTFILE $thisfig->print_info;
674                 } else {
675                     &print_tex_mode($eaten->exact_print . $save);
676                 }
677
678             # Tables
679
680             } elsif ($name eq "\\multicolumn") {
681                 if ($thistable = &RelyxTable::in_table) {
682                     # the (simple text) first arg.
683                     $dummy = $fileobject->eatRequiredArgument->contents->print;
684                     my $group = $fileobject->eatRequiredArgument;
685                     $thistable->multicolumn($dummy, $group);
686                 } else {warn "\\multicolumn is illegal outside a table!"}
687
688             } elsif ($name eq '\cline') {
689                 if ($thistable = &RelyxTable::in_table) {
690                     # the (simple text) first arg.
691                     $dummy = $fileobject->eatRequiredArgument->contents->print;
692                     # sub hcline does cline if an arg is given
693                     $thistable->hcline($dummy);
694                 } else {warn "\\cline is illegal outside a table!"}
695
696             # Bibliography
697
698             } elsif ($name eq '\bibliographystyle') {
699                 $tok = $fileobject->eatRequiredArgument;
700                 $bibstyle_file = "";
701                 # There may be >1 token in the {}, e.g. "{a_b}" -> 3 tokens
702                 my @toks = $tok->contents;
703                 foreach $tok (@toks) {
704                     # kludge: CleanTeX adds {} after _
705                     $tok = $tok->contents if ref($tok) eq "Text::TeX::Group";
706                     $bibstyle_file .= $tok->print;
707                 }
708                 print "\nBibliography style file is $bibstyle_file"if $debug_on;
709
710             # LyX \bibitem actually looks just like LaTeX bibitem, except
711             # it's in a Bibliography par & there must be a space after the
712             # bibitem command. Note we need to explicitly print the braces...
713             } elsif ($name eq "\\bibitem") {
714                 $IsNewParagraph=1; # \bibitem always starts new par. in LyX
715                 &CheckForNewParagraph;
716
717                 $tok = $fileobject->eatOptionalArgument;
718                 print OUTFILE "$name ", $tok->exact_print, "{";
719
720             # Miscellaneous
721
722             # ensuremath -- copy verbatim until you're done
723             # but add \( and \)
724             # Note that we'll only get here if the command is NOT in math mode
725             } elsif ($name eq '\ensuremath') {
726                 print "\nCopying math beginning with '$name'\n" if $debug_on;
727                 my $tok = $fileobject->eatGroup; # eat math expression
728                 my $dummy = $tok->exact_print;
729                 $dummy =~ s/\{(.*)\}/$1/;
730                 $dummy = &fixmath($dummy); # convert '\sp' to '^', etc.
731
732                 &CheckForNewParagraph; # math could be first thing in a par
733                 print OUTFILE "$pre_space\n\\begin_inset Formula \\( ";
734                 print $dummy if $debug_on;
735                 print OUTFILE $dummy;
736
737                 # end math
738                 print OUTFILE "\\)\n\\end_inset \n\n";
739                 print "\nDone copying math" if $debug_on;
740
741             # Token in the ReadCommands command list that basic_lyx doesn't
742             #    know how to handle
743             } else {
744                 &copy_latex_known($eaten,$fileobject);
745             } # end big if
746
747             # Exit the switch
748             last TYPESW;
749         }
750
751         # ArgTokens appear when we've used eatRequiredArgument
752         if (/^ArgToken$/) {
753             # If we're copying a recognized but untranslatable token in tex mode
754             my $tok = $tex_mode_tokens[-1] || 0;
755             if ($eaten->base_token == $tok) {
756                 &copy_latex_known($eaten,$fileobject);
757             }
758         
759             last TYPESW;
760         }
761
762         if (/^EndArgsToken$/) {
763             # If we're copying a recognized but untranslatable token in tex mode
764             my $tok = $tex_mode_tokens[-1] || 0;
765             if ($eaten->base_token eq $tok) {
766                 &copy_latex_known($eaten,$fileobject);
767                 last TYPESW;
768             }
769
770             my $name = $eaten->token_name;
771             print "$name" if $debug_on;
772
773             # Handle things that LyX translates as a "LatexCommand" inset
774             # or "Include" insets
775             if (grep {$_ eq $name} @LatexCommands, @IncludeCommands) {
776                 print OUTFILE "\}\n\n\\end_inset \n\n";
777
778             } elsif (exists $ReadCommands::ToLayout->{$name}) {
779                 &EndLayout($name);
780
781             # Font characteristics
782             # Pop the current FontStatus stack for a given characteristic
783             #    and give the new command (e.g., \emph default)
784             } elsif (exists $FontTransTable{$name}) {
785                 my $command = $FontTransTable{$name};
786                 ($dummy) = ($command =~ /(\S+)\s+\w+/);
787                 pop @{$CurrentFontStatus->{$dummy}};
788                 $command = "\n$dummy $CurrentFontStatus->{$dummy}->[-1] \n";
789                 print OUTFILE "$command";
790
791             # Footnotes and marginpars
792             } elsif (exists $FloatTransTable{$name}) {
793                 print OUTFILE "\n\\end_float \n\n";
794
795                 # Reset the layout stack and font status table pointers to
796                 #    point to the global stack/table again, instead of the
797                 #    footnote-specific stack/table
798                 $CurrentFontStatus = \%FontStatus;
799                 $CurrentLayoutStack = \@LayoutStack;
800
801                 # We need to reissue any font commands (but not layouts)
802                 foreach $dummy (keys %$CurrentFontStatus) {
803                     if ($CurrentFontStatus->{$dummy}->[-1] ne "default") {
804                         print OUTFILE $FontTransTable{$dummy};
805                     }
806                 }
807
808                 # Same paragraph status as we had before the footnote started
809                 $IsNewParagraph = $OldINP; $MayBeDeeper = $OldMBD;
810                 $CurrentAlignment = $OldAlignment;
811
812             } elsif ($name =~ m/^$AccentTokens$/) {
813                 print OUTFILE "}\n";
814             
815             } elsif ($name eq "\\bibitem") {
816                 print OUTFILE "}\n";
817             } # End if on $name
818
819             # Exit main switch
820             last TYPESW;
821         } # end if EndArgsToken
822
823         # Handle END of scope of local commands like \large
824         if (/^EndLocal$/) {
825             my $name = $eaten->token_name; #cmd we're ending, e.g.,\large
826             print $name if $debug_on;
827
828             if (exists $FontTransTable{$name}) {
829                 my $command = $FontTransTable{$name};
830                 ($dummy = $command) =~ s/\s*(\S*)\s+(\w+)\s*/$1/; #e.g., '\size'
831                 die "Font command error" if !exists $$CurrentFontStatus{$dummy};
832                 # TT::OF->check_presynthetic returns local commands FIFO!
833                 # So pop font stack, but warn if we pop the wrong thing
834                 warn " font confusion?" if
835                            pop @{$CurrentFontStatus->{$dummy}} ne $2;
836                 print "\nCurrent $dummy Stack: @{$CurrentFontStatus->{$dummy}}"
837                       if $debug_on;
838                 my $newfont = $CurrentFontStatus->{$dummy}->[-1];
839                 $command = "\n$dummy $newfont\n";
840                 print OUTFILE "$command";
841
842             } else {
843                 warn "Unknown EndLocal token!\n";
844             }
845
846             last TYPESW;
847         }
848
849         # We don't print { or }, but we make sure that the spacing is correct
850         # Handle '{'
851         if (/^Begin::Group$/) {
852             print OUTFILE "$pre_space";
853             last TYPESW;
854         }
855
856         # Handle '{'
857         if (/^End::Group$/) {
858             print OUTFILE "$pre_space";
859             last TYPESW;
860         }
861
862         # Handle \begin{foo}
863         if (/^Begin::Group::Args$/) {
864             print $eaten->print," " if $debug_on; # the string "\begin{foo}"
865             my $env = $eaten->environment;
866             
867             # Any environment found in the layouts files
868             if (exists $ReadCommands::ToLayout->{$env}) {
869                 &ConvertToLayout($env);
870
871                 # Some environments have an extra argument. In that case,
872                 # print the \layout command (cuz these environments always
873                 # start new pars). Then either print the extra arg or
874                 # ignore it (depending on the environment).
875                 if (exists $ExtraArgEnvironments{$env}) {
876                     # Should be just one token in the arg.
877                     my $arg = $fileobject->eatBalanced->contents->print;
878
879                     if ($ExtraArgEnvironments{$env}) { #print it
880                         print "\nArgument $arg to $env environment"
881                                                                 if $debug_on;
882                         $item_preface = $ExtraArgEnvironments{$env} . $arg."\n";
883
884                     } else { #ignore it
885                         print "\nIgnoring argument '$arg' to $env environment"
886                                                                 if $debug_on;
887                     }
888                 } # end if for reading extra args to \begin command
889
890             # Math environments
891             } elsif ($env =~ /^$MathEnvironments$/o) {
892                 &CheckForNewParagraph; # may be beginning of paragraph
893                 my $begin_text = $eaten->print;
894                 print "\nCopying math beginning with '$begin_text'\n"
895                                                               if $debug_on;
896                 print OUTFILE "\n\\begin_inset Formula $begin_text ";
897                 $dummy = &Verbatim::copy_verbatim($fileobject, $eaten);
898                 $dummy = &fixmath($dummy); # convert '\sp' to '^', etc.
899                 print $dummy if $debug_on;
900                 print OUTFILE $dummy;
901
902             # Alignment environments
903             } elsif (exists $AlignEnvironments{$env}) {
904                 # Set it to the command which creates this alignment
905                 $CurrentAlignment = $AlignEnvironments{$env};
906                 ($dummy) = ($CurrentAlignment =~ /\S+\s+(\w+)/);
907                 print "\nNow $dummy-aligning text " if $debug_on;
908
909                 # alignment environments automatically start a new paragraph
910                 $IsNewParagraph = 1;
911
912             # Environments lyx translates to floats
913             } elsif (exists $FloatEnvTransTable{$env}) {
914                 # this really only matters if it's at the very
915                 # beginning of the doc.
916                 &CheckForNewParagraph;
917
918                 $tok = $fileobject->eatOptionalArgument;
919                 if ($tok && defined ($dummy = $tok->print) && $dummy) {
920                     print "\nIgnoring float placement '$dummy'" if $debug_on;
921                 }
922                 my $command = $FloatEnvTransTable{$env};
923
924                 # Open the table/figure
925                 print OUTFILE "$command";
926
927             # table
928             } elsif ($env =~ /^tabular$/) { # don't allow tabular* or ctabular
929                 # Table must start a new paragraph
930                 $IsNewParagraph = 1; $MayBeDeeper = 1;
931                 # We want to print table stuff *after* a \layout Standard
932                 &CheckForNewParagraph;
933
934                 # Since table info needs to come *before* the table content,
935                 #    put a line in the output file saying that the *next*
936                 #    reLyX pass needs to put the table info there
937                 print OUTFILE "\n$RelyxTable::TableBeginString\n";
938
939                 # Read and ignore an optional argument [t] or [b]
940                 $tok = $fileobject->eatOptionalArgument;
941                 if ($tok && defined ($dummy = $tok->print) && $dummy) {
942                     print "\nIgnoring positioning arg '$dummy'" if $debug_on;
943                 }
944
945                 # Read the argument into a TT::Group
946                 #   (that group may contain groups, e.g. for {clp{10cm}}
947                 $tok = $fileobject->eatGroup;
948                 new RelyxTable::Table $tok;
949
950             # \begin document
951             } elsif ($env eq "document") {
952                 # do nothing
953                 #print "\nStarting to translate actual document" if $debug_on;
954
955             # Special environments to copy as regular text (-r option).
956             # Do this by copying the \begin & \end command in TeX mode
957             # (\Q\E around $env allows *'s in environment names!)
958             } elsif (grep /^\Q$env\E$/, @ReadCommands::regular_env) {
959                 print "\nCopying $env environment as regular text\n"
960                                                               if $debug_on;
961                 $dummy = $eaten->print; # \begin{env}, ignore initial whitespace
962                 &print_tex_mode($dummy);
963
964             # otherwise, it's an unknown environment
965             # In that case, copy everything up to the \end{env}
966             #    Save stuff in global tex_mode_string so we can print it
967             # when we read & handle the \end{env}
968             } else {
969
970                 print "\nUnknown environment $env" if $debug_on;
971                 $tex_mode_string = "";
972                 # print "\begin{env}
973                 # For reLyXskip env, don't print the \begin & \end commands!
974                 $tex_mode_string .= $eaten->exact_print 
975                                 unless $env eq "reLyXskip";
976                 $tex_mode_string .=&Verbatim::copy_verbatim($fileobject,$eaten);
977             }
978
979             last TYPESW;
980         }
981         
982         # Handle \end{foo}
983         if (/^End::Group::Args$/) {
984             print $eaten->print," " if $debug_on; # the string "\end{foo}"
985             my $env = $eaten->environment;
986
987             # End of list or quote/verse environment
988             # OR special environment given with -t option
989             if (exists $ReadCommands::ToLayout->{$env}) {
990                 &EndLayout($env);
991                 $item_preface = ""; # reset when at end of List env.
992
993             # End of math environments
994             } elsif ($env =~ /^$MathEnvironments$/o) {
995                 print OUTFILE "\\end{$env}\n\\end_inset \n\n";
996                 print "\nDone copying math environment '$env'" if $debug_on;
997
998             } elsif (exists $AlignEnvironments{$env}) {
999                 # Back to block alignment
1000                 $CurrentAlignment = "";
1001                 print "\nBack to block alignment" if $debug_on;
1002
1003                 # assume that \end should end a paragraph
1004                 # This isn't correct LaTeX, but LyX can't align part of a par
1005                 $IsNewParagraph = 1;
1006
1007             # Environments lyx translates to floats
1008             } elsif (exists $FloatEnvTransTable{$env}) {
1009                 print OUTFILE "\n\\end_float \n\n";
1010
1011             # table
1012             } elsif ($env =~ /tabular$/) { # don't allow tabular*
1013                 if ($thistable = &RelyxTable::in_table) {
1014                     $thistable->done_reading;
1015                     print OUTFILE "\n$RelyxTable::TableEndString\n";
1016                 } else {warn "found \\end{tabular} when not in table!"}
1017
1018                 # Anything after a table will be a new paragraph
1019                 $IsNewParagraph = 1; $MayBeDeeper = 1;
1020
1021             } elsif ($env eq "document") {
1022                 print "\nDone with document!" if $debug_on;
1023
1024             # "regular" environment given with -r option
1025             } elsif (grep /^\Q$env\E$/, @ReadCommands::regular_env) {
1026                 $dummy = $eaten->print; # \end{env}, ignore initial whitespace
1027                 &print_tex_mode($dummy);
1028
1029                 # Next stuff will be new env.
1030                 $IsNewParagraph = 1;
1031
1032             # End of unknown environments. We're already in TeX mode
1033             } else {
1034                 # Add \end{env} (including initial whitespace) to string
1035                 # For reLyXskip environment, don't print \begin & \end commands!
1036                 $tex_mode_string .= $eaten->exact_print
1037                                        unless $env eq "reLyXskip";
1038                 # Now print it
1039                 &print_tex_mode($tex_mode_string);
1040                 print "Done copying unknown environment '$env'" if $debug_on;
1041             }
1042
1043             last TYPESW;
1044
1045         }
1046
1047         # Note for text handling: we have to do lots of stuff to handle
1048         # spaces in (as close as possible to) the same way that LaTeX does
1049         #    LaTeX considers all whitespace to be the same, so basically, we
1050         # convert each clump of whitespace to one space. Unfortunately, there
1051         # are special cases, like whitespace at the beginning/end of a par,
1052         # which we have to get rid of to avoid extra spaces in the LyX display.
1053         #    \n at the end of a paragraph must be considered like a space,
1054         # because the next line might begin with a token like \LyX. But
1055         # if the next line starts with \begin, say, then an extra space will be
1056         # generated in the LyX file. Oh well. It doesn't affect the dvi file.
1057         if (/^Text$/) {
1058             my $outstr = $eaten->print; # the actual text
1059
1060             # don't bother printing whitespace
1061             #    Note: this avoids the problem of extra whitespace generating
1062             # extra Text::TeX::Paragraphs, which would generate extra
1063             # \layout commands
1064             last TYPESW if $outstr =~ /^\s+$/;
1065
1066             # whitespace at beginning of a paragraph is meaningless
1067             # e.g. \begin{foo}\n hello \end{foo} shouldn't print the \n
1068             # (Note: check IsNewParagraph BEFORE calling &CFNP, which zeros it)
1069             my $replace = $IsNewParagraph ? "" : " ";
1070             $outstr =~ s/^\s+/$replace/;
1071
1072             # Only write '\layout Standard' once per paragraph
1073             &CheckForNewParagraph;
1074
1075             # \n\n signals end of paragraph, so get rid of it (and any space
1076             # before it)
1077             $outstr =~ s/\s*\n\n$//;
1078
1079             # Print the LaTeX text to STDOUT
1080             print "'$outstr'" if $debug_on;
1081
1082             # LyX *ignores* \n and \t, whereas LaTeX considers them just
1083             # like a space.
1084             #    Also, many spaces are equivalent to one space in LaTeX
1085             # (But LyX misleadingly displays them on screen, so get rid of them)
1086             $outstr =~ s/\s+/ /g;
1087
1088             # protect spaces in an optional argument if necessary
1089             # Put a SPACE after the argument for List, Description layouts
1090             if ($protect_spaces) {
1091                 $dummy = $TextTokenTransTable{'~'};
1092
1093                 # This will not handle brackets in braces!
1094                 if ($outstr =~ /\]/) { # protect spaces only *until* the bracket
1095                     my $tempstr = $`;
1096                     my $tempstr2 = $';
1097                     # Note that any \t's have been changed to space already
1098                     $tempstr =~ s/ /$dummy/g;
1099
1100                     # Print 1 space after the argument (which finished with ])
1101                     # Don't print 2 (i.e. remove leading space from $tempstr2)
1102                     # don't print the bracket
1103                     $tempstr2 =~ s/^ //;
1104                     $outstr = "$tempstr $tempstr2";
1105                     $protect_spaces = 0; # Done with optional argument
1106                 } else { # protect all spaces, since we're inside brackets
1107                     $outstr =~ s/ /$dummy/g;
1108                 }
1109             } # end special stuff for protected spaces
1110
1111             # Translate any LaTeX text that requires special LyX handling
1112             foreach $dummy (keys %TextTransTable) {
1113                 $outstr =~ s/\Q$dummy\E/$TextTransTable{$dummy}/g;
1114             }
1115
1116             # "pretty-print" the string. It's not perfect, since there may
1117             # be text in the OUTFILE before $outstr, but it will keep from
1118             # having REALLY long lines.
1119             # Try to use approximately the same word-wrapping as LyX does:
1120             # - before space after a period, except at end of string
1121             # - before first space after column seventy-one
1122             # - after 80'th column
1123             while (1) {
1124                 $outstr =~ s/\. (?!$)/.\n /      or
1125                 $outstr =~ s/(.{71,79}?) /$1\n / or
1126                 $outstr =~ s/(.{80})(.)/$1\n$2/ or
1127                 last; # exit loop if string is < 79 characters
1128             }
1129
1130             # Actually print the text
1131             print OUTFILE "$outstr";
1132             last TYPESW;
1133         } # end TT::Text handling
1134
1135         # The default action - this should never happen!
1136         print("I don't know ",$eaten->print) if $debug_on;
1137
1138     } # end for ($type)
1139
1140     print "\n" if $debug_on;
1141
1142 } #end sub basic_lyx
1143
1144 #########################  TEX MODE  SUBROUTINES  #########################
1145
1146 # This subroutine copies and prints a latex token and its arguments if any.
1147 # This sub is only needed if the command was not found in the syntax file
1148 # Use exact_print to preserve, e.g., whitespace after macros
1149 sub copy_latex_unknown {
1150     my $eaten = shift;
1151     my $fileobject = shift;
1152     my $outstr = $eaten->exact_print;
1153     my ($dummy, $tok, $count);
1154
1155 # Copy the actual word. Copy while you've still got
1156 #     arguments. Assume all args must be in the same paragraph
1157 #     (There could be new paragraphs *within* args)
1158     #    We can't use copy_verbatim (unless we make it smarter) because
1159     # it would choke on nested braces
1160     print "\nUnknown token: '",$eaten->print,"': Copying in TeX mode\n"
1161                                                          if $debug_on;
1162     my $dum2;
1163     while (($dum2 = $fileobject->lookAheadToken) &&
1164            ($dum2 =~ /^[[{]$/)) {
1165         if ($dum2 eq '[') { #copy optional argument - assume it's simple
1166             $tok = $fileobject->eatOptionalArgument;
1167             $outstr .= $tok->exact_print; # also print brackets & whitespace
1168         } else {
1169             $count = 0;
1170             EAT: { #copied from eatBalanced, but allow paragraphs
1171                 die unless defined ($tok = $fileobject->eatMultiToken);
1172                 $outstr.="\n",redo EAT if ref($tok) eq "Text::TeX::Paragraph";
1173                 $dummy = $tok->exact_print;
1174                 $outstr .= $dummy;
1175                 # Sometimes, token will be '\n{', e.g.
1176                 $count++ if $dummy =~ /^\s*\{$/; # add a layer of nesting
1177                 $count-- if $dummy =~ /^\s*\}$/; # end one layer of nesting
1178                 redo EAT if $count; #don't dump out until all done nesting
1179             } #end EAT block
1180         } # end if $dummy = [{
1181
1182     } #end while
1183     # Add {} after macro if it's followed by '}'. Otherwise, {\foo}bar
1184     #     will yield \foobar when LyX creates LaTeX files
1185     $outstr.="{}" if $outstr=~/\\[a-zA-Z]+$/ && $dum2 eq '}';
1186
1187     # Print it out in TeX mode
1188     &print_tex_mode($outstr);
1189
1190     print "\nDone copying unknown token" if $debug_on;
1191 } # end sub copy_latex_unknown
1192
1193 # Copy an untranslatable latex command whose syntax we know, along with its
1194 # arguments
1195 #    The command itself, optional arguments, and untranslatable
1196 # arguments get copied in TeX mode. However, arguments which contain regular
1197 # LaTeX will get translated by reLyX. Do that by printing what you have so
1198 # far in TeX mode, leaving this subroutine, continuing with regular reLyX
1199 # translating, and then returning here when you reach the ArgToken or
1200 # EndArgsToken at the end of the translatable argument.
1201 #    We need to keep a stack of the tokens that brought us here, because
1202 # you might have nested commands (e.g., \mbox{hello \fbox{there} how are you}
1203 sub copy_latex_known {
1204     my ($eaten, $fileobject) = (shift,shift);
1205     my $type = ref($eaten);
1206     $type =~ s/^Text::TeX::// or die "unknown token?!";
1207
1208     # token itself for TT::Token, TT::BegArgsToken,
1209     # Corresponding BegArgsToken for ArgToken,EndArgsToken
1210     my $temp_start = $eaten->base_token;
1211
1212 # Initialize tex mode copying
1213     if ($type eq "BegArgsToken" or $type eq "Token") {
1214         print "\nCopying untranslatable token '",$eaten->print,
1215                                       "' in TeX mode" if $debug_on;
1216         push @tex_mode_tokens, $temp_start;
1217
1218         # initialize the string of stuff we're copying
1219         $tex_mode_string = $eaten->exact_print;
1220     } # Start tex copying?
1221
1222 # Handle arguments
1223     # This token's next arguments -- returns a string matching /o*[rR]?/
1224     my $curr_args = $eaten->next_args($fileobject);
1225
1226     if ($type eq "EndArgsToken" or $type eq "ArgToken") {
1227         # Print ending '}' for the group we just finished reading
1228         $tex_mode_string .= '}';
1229     }
1230
1231     # If there could be optional arguments next, copy them
1232     while ($curr_args =~ s/^o// && $fileobject->lookAheadToken eq '[') {
1233         my $opt = $fileobject->eatOptionalArgument;
1234         $tex_mode_string .= $opt->exact_print;
1235     }
1236     $curr_args =~ s/^o*//; # Some OptArgs may not have appeared
1237
1238     if ($type eq "BegArgsToken" or $type eq "ArgToken") {
1239         # Print beginning '{' for the group we're about to read
1240         $tex_mode_string .= '{';
1241     }
1242
1243     # Now copy the next required argument, if any
1244     # Copy it verbatim (r), or translate it as regular LaTeX (R)?
1245     if ($curr_args =~ s/^r//) {
1246         my $group = $fileobject->eatRequiredArgument;
1247         my $temp = $group->exact_print;
1248         # Remove braces. They're put in explicitly
1249         $temp =~ s/\{(.*)\}/$1/; # .* is greedy
1250         $tex_mode_string .= $temp;
1251
1252     } elsif ($curr_args =~ s/^R//) {
1253         print "\n" if $debug_on;
1254         &print_tex_mode($tex_mode_string);
1255         $tex_mode_string = "";
1256         print "\nTranslating this argument for ",$temp_start->print,
1257               " as regular LaTeX" if $debug_on;
1258
1259     } else { # anything but '' is weird
1260         warn "weird arg $curr_args to ",$temp_start->print,"\n" if $curr_args;
1261     }
1262
1263 # Finished tex mode copying
1264     if ($type eq "Token" or $type eq "EndArgsToken") {
1265
1266         # Add {} to plain tokens followed by { or }. Otherwise {\foo}bar
1267         # and \foo{bar} yield \foobar in the LaTeX files created by LyX
1268         my $dummy;
1269         if ($type eq "Token" and
1270                 $dummy=$fileobject->lookAheadToken and
1271                 $dummy =~ /[{}]/)
1272         {
1273             $tex_mode_string .= '{}';
1274         }
1275
1276         # Print out the string
1277         print "\n" if $debug_on;
1278         &print_tex_mode($tex_mode_string);
1279         $tex_mode_string = "";
1280
1281         # We're done with this token
1282         pop(@tex_mode_tokens);
1283
1284         my $i = $type eq "Token" ? "" : " and its arguments";
1285         my $j = $temp_start->print;
1286         print "\nDone copying untranslatable token '$j'$i in TeX mode"
1287                                                           if $debug_on;
1288     } # end tex copying?
1289 } # end sub copy_latex_known
1290
1291 # Print a string in LyX "TeX mode"
1292 #    The goal of this subroutine is to create a block of LyX which will be
1293 # translated exactly back to the original when LyX creates its temporary LaTeX
1294 # file prior to creating a dvi file.
1295 #    Don't print \n\n at the end of the string... instead just set the new
1296 # paragraph flag. Also, don't print whitespace at the beginning of the string.
1297 # Print nothing if it's the beginning of a paragraph, or space otherwise.
1298 # These two things avoid extra C-Enter's in the LyX file
1299 sub print_tex_mode {
1300     my $outstr = shift;
1301
1302     print "'$outstr'" if $debug_on;
1303
1304     # Handle extra \n's (& spaces) at beginning & end of string
1305     my $str_ends_par = ($outstr =~ s/\n{2,}$//);
1306     if ($IsNewParagraph) {
1307         $outstr =~ s/^\s+//;  # .e.g, $outstr follows '\begin{quote}'
1308     } else {
1309         # Any whitespace is equivalent to one space in LaTeX
1310         $outstr =~ s/^\s+/ /; # e.g. $outstr follows "\LaTeX{}" or "Hi{}"
1311     }
1312
1313     # Check whether string came right at the beginning of a new paragraph
1314     # This *might* not be necessary. Probably can't hurt.
1315     &CheckForNewParagraph;
1316
1317     # Get into TeX mode
1318     print OUTFILE "$start_tex_mode";
1319
1320     # Do TeX mode translation;
1321     $outstr =~ s/\\/\n\\backslash /g;
1322     # don't translate \n in '\n\backslash' that we just made!
1323     $outstr =~ s/\n(?!\\backslash)/\n\\newline \n/g;
1324
1325     # Print the actual token + arguments if any
1326     print OUTFILE $outstr;
1327
1328     # Get OUT of LaTeX mode (and end nesting if nec.)
1329     print OUTFILE "$end_tex_mode";
1330     $IsNewParagraph = $str_ends_par;
1331
1332     return;
1333 } # end sub print_tex_mode
1334
1335 ############################  LAYOUT  SUBROUTINES  ###########################
1336
1337 sub CheckForNewParagraph {
1338 # This subroutine makes sure we only write \layout command once per paragraph
1339 #    It's mostly necessary cuz 'Standard' layout is the default in LaTeX;
1340 #    there is no command which officially starts a standard environment
1341 # If we're in a table, new layouts aren't allowed, so just return
1342 # If $IsNewParagraph is 0, it does nothing
1343 # If $INP==1, It starts a new paragraph
1344 # If $CurrentAlignment is set, it prints the alignment command for this par.
1345 # If $MayBeDeeper==1 and we're currently within a list environment,
1346 #    it starts a "deeper" Standard paragraph
1347     my $dummy; 
1348     my $layout = $$CurrentLayoutStack[-1];
1349
1350     return if &RelyxTable::in_table;
1351
1352     if ($IsNewParagraph) {
1353         # Handle standard text within a list environment specially
1354         if ($MayBeDeeper) {
1355             if ($layout =~ /^$ListLayouts$/o) {
1356                 push (@$CurrentLayoutStack, "Standard");
1357                 print "\nCurrent Layout Stack: @$CurrentLayoutStack\n"
1358                                                      if $debug_on;
1359                 print OUTFILE "\n\\begin_deeper ";
1360                 $layout = "Standard";
1361             }
1362             $MayBeDeeper = 0; # Don't test again until new paragraph
1363         }
1364
1365         # Print layout command itself
1366         print OUTFILE "\n\\layout $layout\n\n";
1367         print OUTFILE $CurrentAlignment if $CurrentAlignment;
1368
1369         # Now that we've written the command, it's no longer a new paragraph
1370         $IsNewParagraph = 0;
1371
1372         # And we're no longer waiting to see if this paragraph is empty
1373         $PendingLayout = 0;
1374
1375         # When you write a new paragraph, reprint any font commands
1376         foreach $dummy (keys %$CurrentFontStatus) {
1377             my $currf = $CurrentFontStatus->{$dummy}->[-1];
1378             if ($currf ne "default") {
1379                 print OUTFILE "\n$dummy $currf \n";
1380             }
1381         }
1382     } # end if $INP
1383 } # end sub CheckForNewParagraph
1384
1385 sub ConvertToLayout {
1386 # This subroutine begins a new layout, pushing onto the layout stack, nesting
1387 # if necessary. It doesn't actually write the \layout command -- that's
1388 # done by CheckForNewParagraph.
1389 #    The subroutine assumes that it's being passed an environment name or macro
1390 # which is known and which creates a known layout
1391 #    It uses the ToLayout hash (created by the ReadCommands module) which
1392 # gives the LyX layout for a given LaTeX command or environment
1393 # Arg0 is the environment or macro
1394     my $name = shift;
1395
1396     my $layoutref = $ReadCommands::ToLayout->{$name};
1397     my $layout = $layoutref->{'layout'};
1398     my $keepempty = $layoutref->{'keepempty'};
1399     my $dummy = ($name =~ /^\\/ ? "macro" : "environment");
1400     print "\nChanging $dummy $name to layout $layout" if $debug_on;
1401
1402     # Nest if the layout stack has more than just "Standard" in it
1403     if ($#{$CurrentLayoutStack} > 0) {
1404         # Die here for sections & things that can't be nested!
1405         print " Nesting!" if $debug_on;
1406         print OUTFILE "\n\\begin_deeper ";
1407     }
1408
1409     # If we still haven't printed the *previous* \layout command because that
1410     # environment is empty, print it now! (This happens if an environment
1411     # is nested inside a keepempty, like slide.)
1412     &CheckForNewParagraph if $PendingLayout;
1413
1414     # Put the new layout onto the layout stack
1415     push @$CurrentLayoutStack, $layout;
1416     print "\nCurrent Layout Stack: @$CurrentLayoutStack" if $debug_on;
1417
1418     # Upcoming text will be new paragraph, needing a new layout cmd
1419     $IsNewParagraph = 1;
1420
1421     # Test for nested "Standard" paragraph in upcoming text?
1422     # Some environments can nest. Sections & Title commands can't
1423     $MayBeDeeper = $layoutref->{"nestable"};
1424
1425     # We haven't yet read any printable stuff in the new paragraph
1426     # If this is a layout that's allowed to be empty, prepare for an
1427     # empty paragraph
1428     $PendingLayout = $keepempty;
1429
1430 } # end sub ConvertToLayout
1431
1432 sub EndLayout {
1433 # This subroutine ends a layout, popping the layout stack, etc.
1434 #    The subroutine assumes that it's being passed an environment name or macro
1435 # which is known and which creates a known layout
1436 #    It uses the ToLayout hash (created by the ReadCommands module) which
1437 # gives the LyX layout for a given LaTeX command or environment
1438 # Arg0 is the environment or macro
1439     my $name = shift;
1440
1441     my $layoutref = $ReadCommands::ToLayout->{$name};
1442     my $layout = $layoutref->{'layout'};
1443     my $dummy = ($name =~ /^\\/ ? "macro" : "environment");
1444     print "\nEnding $dummy $name (layout $layout)" if $debug_on;
1445
1446     # If we still haven't printed the *previous* \layout command because that
1447     # environment is empty, print it now! Before we pop the stack!
1448     # This happens for a totally empty, non-nesting environment,
1449     # like hollywood.sty's fadein
1450     &CheckForNewParagraph if $PendingLayout;
1451
1452     my $mylayout = pop (@$CurrentLayoutStack);
1453
1454     # If a standard paragraph was the last thing in a list, then
1455     #     we need to end_deeper and then pop the actual list layout
1456     # This should only happen if the Standard layout was nested
1457     #    in a nestable layout. We don't check.
1458     if ($mylayout eq "Standard") {
1459         print OUTFILE "\n\\end_deeper ";
1460         print " End Standard Nesting!" if $debug_on;
1461         $mylayout = pop (@$CurrentLayoutStack);
1462     }
1463
1464     # The layout we popped off the stack had better match the
1465     #    environment (or macro) we're ending!
1466     if ($mylayout ne $layout) { die "Problem with Layout Stack!\n"};
1467     print "\nCurrent Layout Stack: @$CurrentLayoutStack" if $debug_on;
1468
1469     # If we're finishing a nested layout, we need to end_deeper
1470     # This should only happen if the layout was nested
1471     #    in a nestable layout. We don't check.
1472     # Note that if we're nested in a list environment and the
1473     #     NEXT paragraph is Standard, then we'll have an extra
1474     #     \end_deeper \begin_deeper in the LyX file. It's sloppy
1475     #     but it works, and LyX will get rid of it when it
1476     #     resaves the file.
1477     if ($#{$CurrentLayoutStack} > 0) {
1478         print " End Nesting!" if $debug_on;
1479         print OUTFILE "\n\\end_deeper ";
1480     }
1481
1482     # Upcoming text will be new paragraph, needing a new layout cmd
1483     $IsNewParagraph = 1;
1484
1485     # Test for nested "Standard" paragraph in upcoming text?
1486     # Some environments can nest. Sections & Title commands can't
1487     $MayBeDeeper = $layoutref->{"nestable"};
1488 } # end sub EndLayout
1489
1490 #######################  MISCELLANEOUS SUBROUTINES  ###########################
1491 sub fixmath {
1492 # Translate math commands LyX doesn't support into commands it does support
1493     my $input = shift;
1494     my $output = "";
1495
1496     while ($input =~ s/
1497             (.*?)    # non-token matter ($1)
1498             (\\      # token ($2) is a backslash followed by ...
1499                 ( ([^A-Za-z] \*?) |    # non-letter (and *) ($4) OR
1500                   ([A-Za-z]+ \*?)   )  # letters (and *) ($5)
1501             )//xs) # /x to allow whitespace/comments, /s to copy \n's
1502     { 
1503         $output .= $1;
1504         my $tok = $2;
1505         if (exists $ReadCommands::math_trans{$tok}) {
1506             $tok = $ReadCommands::math_trans{$tok};
1507             # add ' ' in case we had, e.g., \|a, which would become \Verta
1508             # Only need to do it in those special cases
1509             $tok .= ' ' if
1510                     defined $4 && $tok =~ /[A-Za-z]$/ && $input =~ /^[A-Za-z]/;
1511         }
1512         $output .= $tok;
1513     }
1514     $output .= $input; # copy what's left in $input
1515
1516     return $output;
1517 }
1518
1519 1; # return true to calling subroutine
1520