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