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