]> git.lyx.org Git - lyx.git/blob - lib/reLyX/MakePreamble.pm
fix typo that put too many include paths for most people
[lyx.git] / lib / reLyX / MakePreamble.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 MakePreamble;
7 # This package reads a LaTeX preamble (everything before \begin{document}
8 #    and translates it to LaTeX.
9
10 use strict;
11
12 my $debug_on; # package-wide variable set if -d option is given
13 my $true_class; # which textclass to use (if -c option is given)
14
15 sub split_preamble {
16 # Split the file into two files, one with just the preamble
17 # Simply copy stuff verbatim, saving translation for later
18 # Skip the LyX-generated portion of the preamble, if any. (Otherwise,
19 #     when you try to "view dvi" in LyX, there will be two copies of the
20 #     preamble matter, which will break LyX.
21     my ($InFileName, $PreambleName, $OutFileName) = (shift, shift, shift);
22     my ($a, $b, $c);
23     my $forget=0;
24
25     # Was -d option given?
26     $debug_on = (defined($main::opt_d) && $main::opt_d);
27     # -c option?
28     $true_class = defined($main::opt_c) ? $main::opt_c : "";
29     my $zzz = $debug_on 
30         ? " from LaTeX file $InFileName into $PreambleName and $OutFileName" 
31         : "";
32     warn "Splitting Preamble$zzz\n";
33
34     open (INFILE, "<$InFileName") or die "problem opening $InFileName: $!\n";
35     open (PREAMBLE, ">$PreambleName") or
36                 die "problem opening $PreambleName: $!\n";
37     open (OUTFILE, ">$OutFileName") or die "problem opening $OutFileName: $!\n";
38
39     # Copy everything up to "\begin{document}" into the preamble
40     while (<INFILE>) {
41         if (s/\Q\begin{document}\E//) {
42             ($a, $b, $c) = ($`, $&, $'); # save for later
43             last;
44         }
45         # In real life, there should never be Textclass specific stuff unless
46         # there is also LyX specific. But it can't hurt to test for both.
47         $forget=1 if m/%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% LyX specific/ ||
48                      m/%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Textclass specific/;
49         print PREAMBLE $_ unless $forget;
50         $forget=0 if m/%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% User specified/;
51     }
52     die "Didn't find \\begin{document} command!" unless defined $b;
53     # There *could* be a preamble command on the same line as \begin{doc}!
54     print PREAMBLE $a;
55     print "Put preamble into file $PreambleName\n" if $debug_on;
56
57     # Copy everything else into another file
58     # Ignore anything after '\end{document}
59     print OUTFILE $b, $c; #'\begin{document}' plus anything else on the line
60     while (<INFILE>) {
61         print OUTFILE $_;
62         last if $_ =~ /^[^%]*\Q\end{document}\E/;
63     }
64
65     print "Put rest of file into $OutFileName\n" if $debug_on;
66     close INFILE; close OUTFILE; close PREAMBLE;
67     #warn "Done splitting preamble\n";
68 } #end sub split_preamble
69
70
71
72 # Actually translate a LaTeX preamble (in a file) into a LyX preamble.
73 # Input:
74 # First argument is the name of the file containing *only* the preamble
75 # Second argument is the LyX format (e.g., "2.15")
76 #
77 # Output: document class, LyX Preamble, LaTeX preamble
78 #    LyX premable contains the LyX options etc.
79 #    LaTeX preamble is stuff that doesn't translate into LyX options)
80 #
81 sub translate_preamble {
82     my $PreambleName = shift;
83     my $Format = shift;
84     $debug_on = (defined($main::opt_d) && $main::opt_d);
85     my $zzz=$debug_on ? " from $PreambleName" :"";
86     warn "Creating LyX preamble$zzz\n";
87     open (PREAMBLE, "<$PreambleName");
88
89     # Translate optional args to \documentclass to LyX preamble statements
90     my %Option_Trans_Table = (
91         "10pt"           => "\\paperfontsize 10",
92         "11pt"           => "\\paperfontsize 11",
93         "12pt"           => "\\paperfontsize 12",
94
95         "letterpaper"    => "\\papersize letterpaper",
96         "legalpaper"     => "\\papersize legalpaper",
97         "executivepaper" => "\\papersize executivepaper",
98         "a3paper"        => "\\papersize a3paper",
99         "a4paper"        => "\\papersize a4paper",
100         "a5paper"        => "\\papersize a5paper",
101         "b3paper"        => "\\papersize b3paper",
102         "b4paper"        => "\\papersize b4paper",
103         "b5paper"        => "\\papersize b5paper",
104
105         "twoside"        => "\\papersides 2",
106         "oneside"        => "\\papersides 1",
107
108         "landscape"      => "\\paperorientation landscape",
109
110         "onecolumn"      => "\\papercolumns 1",
111         "twocolumn"      => "\\papercolumns 2",
112     );
113
114     my %Languages_Table = ();
115     # if the language file is available then added it to the languages table
116     if(-e "$main::lyxdir/languages") {
117         open (LANGUAGES, "<$main::lyxdir/languages");
118
119         while(<LANGUAGES>) {
120             next if(/^\#/); #ignore comments
121             my @lang_field = split(/\s+/);
122             $Languages_Table{$lang_field[1]} = $lang_field[1];
123         }
124         close(LANGUAGES);
125     }
126
127     # This is the string in which we're concatenating everything we translate
128     my $LyX_Preamble = "";
129
130 # It would be nice to read the defaults.lyx file but for now we don't bother
131 #my $default_dir = "templates/";
132 #my $default_name = "defaults.lyx";
133 #my $default_file = $dot_lyxdir . $default_dir . $default_name;
134 #if (-e $default_file) {
135 #    print "Going to open default LyX file $default_file\n";
136 #    open (DEFAULT_LYX,$default_file) or warn "can't find default lyx file!";
137 #       if ($fmt =~ /^\s*\\lyxformat [0-9.]+/) {
138 #           print $fmt
139 #       } else {
140 #           die "Need \\lyxformat command in first line of default lyx file!";
141 #       }
142 #       AFTER printing the preamble, we'd print other commands from defaults.lyx
143 #       while (($line = <DEFAULT_LYX>) !~ /^.*\\layout/) {
144 #           if ($line !~ /^\s*(\#|\\textclass\W)/) { #already printed this line
145 #               print OUTFILE $line;
146 #           }
147 #       }
148 #}
149
150     # Write first line of the lyx file
151     $LyX_Preamble .= "\#LyX 1.2 created this file. For more info see http://www.lyx.org/\n";
152
153     # Print \lyxformat.
154     $LyX_Preamble .= "\\lyxformat $Format\n";
155
156     # Ignore everything up to the \documentclass
157     my $ignore = "";
158     while (<PREAMBLE>) {
159         next if /^\s*$/ || /^\s*%/; # skip whitespace or comment
160         # could just allow 'documentclass' and not support 2.09
161         last if s/^\s*\\document(style|class)//;
162         $ignore .= $_; # concatenate the ignored text
163     } # end while
164     warn "Uncommented text before \\documentclass command ignored!\n"if $ignore;
165     print "Ignored text was\n------\n$ignore------\n" if $debug_on && $ignore;
166
167     # concatenate all the extra options until the required argument to 
168     # \documentclass, which will be in braces
169     until (eof(PREAMBLE) || /\{/) {
170         my $instr = <PREAMBLE>;
171         $instr =~ s/\s*%.*$//; # get rid of comments
172         chomp; # remove the \n on $_ prior to concatenating
173         $_ .= $instr;
174     } # end loop; check the now longer $_ for a brace
175
176     # Read optional arguments, which are now guaranteed to be on one line
177     # (They're read here, but printed AFTER the \\textclass command)
178     #    Note: the below pattern match is *always* successful, so $& is always
179     # set, but it will be '' if there are no optional arguments. $1 will be
180     # whatever was inside the brackets (i.e., not including the [])
181     my $extra_options;
182     if (defined($_)) {
183         s/^\s*//; # there might be space before args
184         s/$Text::TeX::optionalArgument//;
185         $extra_options = $1 if $&;
186     }
187
188     # Read the document class, in braces, then convert it to a textclass
189     # However, if the user input a different class with the -c option, use that
190     s/\s*\{(\S+)\s*\}//;
191     my $class = $1;
192     $class = $true_class if $true_class; # override from -c option
193     die "no document class in file, no -c option given\n" unless $class;
194     $LyX_Preamble .= "\\textclass $class\n";
195     print "document class is $class\n" if $debug_on;
196
197     # Analyze the extra options, and remove those we know about
198     if ($extra_options) {
199         my $op;
200         foreach $op (keys %Option_Trans_Table) {
201             $extra_options =~ s/\b$op\b// && do {
202                 $LyX_Preamble .= "$Option_Trans_Table{$op}\n";
203                 print "Document option $op\n" if $debug_on;
204             }
205         }
206         $extra_options =~ s/^,+|,+(?=,)|,+$//g; # extra commas
207         # Analyze further the extra options for languages, the last language
208         # is the document language, so the order matters.
209         my $language ="";
210         foreach $op (split(/\s*,\s*/,$extra_options)) {
211             if (exists $Languages_Table{$op}) {
212                 $language = $op;
213                 $extra_options =~ s/\b$op\b//;
214                 print "Document language $op\n" if $debug_on;
215             }
216         }
217         if ($language) {
218             $LyX_Preamble .= "\\language $language\n";
219         }
220         $extra_options =~ s/^,+|,+(?=,)|,+$//g; # extra commas
221     }
222     # Convert any remaining options to an \options command
223     if ($extra_options) {
224         $LyX_Preamble .= "\\options $extra_options\n";
225         print "extra options: $extra_options\n" if $debug_on;
226     }
227
228     # Now copy the whole preamble into the preamble of the LyX document
229     #     (unless there is no preamble)
230     # Everything until the end of filehandle PREAMBLE is preamble matter
231     my $Latex_Preamble = $_; # there COULD be a preamble command on same line
232     while (<PREAMBLE>) {
233         $Latex_Preamble .= $_;
234     }
235
236     # Process $Latex_Preamble, and try to extract as much as possible to
237     # $Lyx_Preamble (jamatos 2001/07/21)
238
239     # Deal with counters, for now just "tocdepth" and "secnumdepth"
240     my %Counter_Table = (
241         "secnumdepth"   => "\\secnumdepth",
242         "tocdepth"      => "\\tocdepth"
243     );
244
245     my $ct;
246     foreach $ct (keys %Counter_Table) {
247         $Latex_Preamble =~ s/\\setcounter\{$ct\}\{(.*)\}\s*// && do {
248             $LyX_Preamble .= "$Counter_Table{$ct} $1\n";
249         }
250     }
251
252     if($Latex_Preamble =~ s/\\pagestyle\{(.*)\}\s*//) {
253         $LyX_Preamble .= "\\paperpagestyle $1\n";
254     }
255     if($Latex_Preamble =~ s/\\usepackage\[(.*)\]\{inputenc\}\s*//) {
256         $LyX_Preamble .= "\\inputencoding $1\n";
257     }
258     $Latex_Preamble =~ s/\\usepackage\[.*\]\{fontenc\}\s*//;
259
260     ## Deal with \usepackage{} cases, no optional argument
261     my %Usepackage_Table = (
262         "amsmath"       => "\\use_amsmath 1",
263         "amssymb"       => "",
264
265         "geometry"      => "\\use_geometry 1",
266
267         "babel"         => "",
268
269         "pslatex"       => "\\fontscheme pslatex",
270         "ae"            => "\\fontscheme ae",
271         "aecompl"       => "",
272         "times"         => "\\fontscheme times",
273         "palatino"      => "\\fontscheme palatino",
274         "helvet"        => "\\fontscheme helvet",
275         "avant"         => "\\fontscheme avant",
276         "newcent"       => "\\fontscheme newcent",
277         "bookman"       => "\\fontscheme bookman",
278
279         "a4wide"        => "\\paperpackage widemarginsa4",
280         "a4"            => "\\paperpackage a4wide",
281
282         "graphics"      => "\\graphics default",
283         "rotating"      => "",
284         "makeidx"       => "\\makeindex"
285     );
286
287     ## Babel with arguments specifing language
288     if($Latex_Preamble =~ s/\\usepackage\[(.*)\]\{babel\}\s*//) {
289         my @languages = split(',',$1);
290         my $lang = pop @languages;
291         $LyX_Preamble .= "\\language $lang\n";
292     }
293
294     my $up;
295     foreach $up (keys %Usepackage_Table) {
296         $Latex_Preamble =~ s/\\usepackage\{$up\}\s*// && do {
297             $LyX_Preamble .= "$Usepackage_Table{$up}";
298             $LyX_Preamble .= "\n" unless ($Usepackage_Table{$up} eq "");
299         }
300     }
301
302     ## Handle geometry options
303     ## The custom paper missing from the options list since it involves two parameters
304     my %Geometry_Options =(
305         'verbose'       => sub { return "" },
306
307         "letterpaper"   => sub { return "\\papersize letterpaper\n" },
308         "legalpaper"    => sub { return "\\papersize legalpaper\n" },
309         "executivepaper"=> sub { return "\\papersize executivepaper\n" },
310         "a3paper"       => sub { return "\\papersize a3paper\n" },
311         "a4paper"       => sub { return "\\papersize a4paper\n" },
312         "a5paper"       => sub { return "\\papersize a5paper\n" },
313         "b3paper"       => sub { return "\\papersize b3paper\n" },
314         "b4paper"       => sub { return "\\papersize b4paper\n" },
315         "b5paper"       => sub { return "\\papersize b5paper\n" },
316
317         'tmargin=(\w*)' => sub { return "\\topmargin $1\n" },
318         'bmargin=(\w*)' => sub { return "\\bottommargin $1\n" },
319         'lmargin=(\w*)' => sub { return "\\leftmargin $1\n" },
320         'rmargin=(\w*)' => sub { return "\\rightmargin $1\n" },
321         'headsep=(\w*)' => sub { return "\\headsep $1\n" },
322         'footskip=(\w*)'        => sub { return "\\footskip $1\n" },
323         'headheight=(\w*)'      => sub { return "\\headheight $1\n" }
324     );
325
326     if( $Latex_Preamble =~ /\\geometry\{(.*)\}/) {
327         my $geom_options = $1;
328         my $op;
329         foreach $op (keys %Geometry_Options) {
330             $geom_options =~ s/$op// && do {
331                 $LyX_Preamble .= &{$Geometry_Options{$op}}();
332                 print "Geometry option $op\n" if $debug_on;
333             }
334         }
335         $geom_options =~ s/^,+|,+(?=,)|,+$//g; # extra commas
336         if( $geom_options =~ /\s*/) {
337             $Latex_Preamble =~ s/\\geometry\{(.*)\}//;
338         }
339         else {
340             $Latex_Preamble =~ s/\\geometry\{(.*)\}/\\geometry\{$geom_options\}/;
341         }
342     }
343
344     ## Paragraph skip or indentation
345     if ( $Latex_Preamble =~ 
346          s/\\setlength\\parskip\{\\(.*)amount\}\s*\\setlength\\parindent\{0pt\}//) {
347         $LyX_Preamble .= "\\paragraph_separation skip\n";
348         $LyX_Preamble .= "\\defskip $1\n";
349     }
350
351     ## Paragraph spacing
352     if ( $Latex_Preamble =~ s/\\(\w*)spacing//) {
353         $LyX_Preamble .= "\\spacing  $1\n";
354     }
355
356     ## remove LyX specific stuff
357     $Latex_Preamble =~ s/\\IfFileExists\{url.sty\}\{\\usepackage\{url\}\}\s*\{\\newcommand\{\\url\}\{\\texttt\}\}\s*//;
358
359     ##  this two need probably a more fine grained control
360     $Latex_Preamble =~ s/\\makeatletter\s*//;
361     $Latex_Preamble =~ s/\\makeatother\s*//;
362
363     $Latex_Preamble =~ s/^\s*//;
364     print "LaTeX preamble, consists of:\n$Latex_Preamble" if $debug_on;
365     if($Latex_Preamble) {
366         $Latex_Preamble = "\\begin_preamble\n$Latex_Preamble\\end_preamble\n";
367     } #just comments, whitespace. Ignore them
368     print "End of LaTeX preamble\n" if $debug_on;
369
370     #warn "Done creating LyX Preamble\n";
371     return ($class, $LyX_Preamble, $Latex_Preamble);
372 }
373
374 1; # return true value to calling program