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