]> git.lyx.org Git - lyx.git/blob - lib/reLyX/MakePreamble.pm
Fun with reLyX.
[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     # if the language file is available then added it to the options table
115     if(-e "$main::lyxdir/languages") {
116         open (LANGUAGES, "<$main::lyxdir/languages");
117
118         while(<LANGUAGES>) {
119             next if(/^\#/); #ignore comments
120             my @lang_field = split(/\s+/);
121             $Option_Trans_Table{$lang_field[1]} = "\\language $lang_field[1]";
122         }
123         close(LANGUAGES);
124     }
125
126     # This is the string in which we're concatenating everything we translate
127     my $LyX_Preamble = "";
128
129 # It would be nice to read the defaults.lyx file but for now we don't bother
130 #my $default_dir = "templates/";
131 #my $default_name = "defaults.lyx";
132 #my $default_file = $dot_lyxdir . $default_dir . $default_name;
133 #if (-e $default_file) {
134 #    print "Going to open default LyX file $default_file\n";
135 #    open (DEFAULT_LYX,$default_file) or warn "can't find default lyx file!";
136 #       if ($fmt =~ /^\s*\\lyxformat [0-9.]+/) {
137 #           print $fmt
138 #       } else {
139 #           die "Need \\lyxformat command in first line of default lyx file!";
140 #       }
141 #       AFTER printing the preamble, we'd print other commands from defaults.lyx
142 #       while (($line = <DEFAULT_LYX>) !~ /^.*\\layout/) {
143 #           if ($line !~ /^\s*(\#|\\textclass\W)/) { #already printed this line
144 #               print OUTFILE $line;
145 #           }
146 #       }
147 #}
148
149     # Write first line of the lyx file
150     $LyX_Preamble .= "\#LyX 1.2 created this file. For more info see http://www.lyx.org/\n";
151
152     # Print \lyxformat.
153     $LyX_Preamble .= "\\lyxformat $Format\n";
154
155     # Ignore everything up to the \documentclass
156     my $ignore = "";
157     while (<PREAMBLE>) {
158         next if /^\s*$/ || /^\s*%/; # skip whitespace or comment
159         # could just allow 'documentclass' and not support 2.09
160         last if s/^\s*\\document(style|class)//;
161         $ignore .= $_; # concatenate the ignored text
162     } # end while
163     warn "Uncommented text before \\documentclass command ignored!\n"if $ignore;
164     print "Ignored text was\n------\n$ignore------\n" if $debug_on && $ignore;
165
166     # concatenate all the extra options until the required argument to 
167     # \documentclass, which will be in braces
168     until (eof(PREAMBLE) || /\{/) {
169         my $instr = <PREAMBLE>;
170         $instr =~ s/\s*%.*$//; # get rid of comments
171         chomp; # remove the \n on $_ prior to concatenating
172         $_ .= $instr;
173     } # end loop; check the now longer $_ for a brace
174
175     # Read optional arguments, which are now guaranteed to be on one line
176     # (They're read here, but printed AFTER the \\textclass command)
177     #    Note: the below pattern match is *always* successful, so $& is always
178     # set, but it will be '' if there are no optional arguments. $1 will be
179     # whatever was inside the brackets (i.e., not including the [])
180     my $extra_options;
181     if (defined($_)) {
182         s/^\s*//; # there might be space before args
183         s/$Text::TeX::optionalArgument//;
184         $extra_options = $1 if $&;
185     }
186
187     # Read the document class, in braces, then convert it to a textclass
188     # However, if the user input a different class with the -c option, use that
189     s/\s*\{(\S+)\s*\}//;
190     my $class = $1;
191     $class = $true_class if $true_class; # override from -c option
192     die "no document class in file, no -c option given\n" unless $class;
193     $LyX_Preamble .= "\\textclass $class\n";
194     print "document class is $class\n" if $debug_on;
195
196     # Analyze the extra options, and remove those we know about
197     if ($extra_options) {
198         my $op;
199         foreach $op (keys %Option_Trans_Table) {
200             $extra_options =~ s/\b$op\b// && do {
201                 $LyX_Preamble .= "$Option_Trans_Table{$op}\n";
202                 print "Document option $op\n" if $debug_on;
203             }
204         }
205         $extra_options =~ s/^,+|,+(?=,)|,+$//g; # extra commas
206     }
207     # Convert any remaining options to an \options command
208     if ($extra_options) {
209         $LyX_Preamble .= "\\options $extra_options\n";
210         print "extra options: $extra_options\n" if $debug_on;
211     }
212
213     # Now copy the whole preamble into the preamble of the LyX document
214     #     (unless there is no preamble)
215     # Everything until the end of filehandle PREAMBLE is preamble matter
216     my $Latex_Preamble = $_; # there COULD be a preamble command on same line
217     my $write_preamble = (! /^\s*$/ && ! /^\s*%/);
218     while (<PREAMBLE>) {
219         $Latex_Preamble .= $_;
220         # write an official preamble if we find anything that's not comment
221         $write_preamble ||= (! /^\s*$/ && ! /^\s*%/);
222     }
223
224     # Process $Latex_Preamble, and try to extarct as much as possible to
225     # $Lyx_Preamble (jamatos 2001/07/21)
226
227     # Deal with counters, for now just "tocdepth" and "secnumdepth"
228     my %Counter_Table = (
229         "secnumdepth"   => "\\secnumdepth",
230         "tocdepth"      => "\\tocdepth"
231     );
232
233     my $ct;
234     foreach $ct (keys %Counter_Table) {
235         $Latex_Preamble =~ s/\\setcounter\{$ct\}\{(.*)\}\s*// && do {
236             $LyX_Preamble .= "$Counter_Table{$ct} $1\n";
237         }
238     }
239
240     if($Latex_Preamble =~ s/\\pagestyle\{(.*)\}\s*//) {
241         $LyX_Preamble .= "\\paperpagestyle $1\n";
242     }
243     if($Latex_Preamble =~ s/\\usepackage\[(.*)\]\{inputenc\}\s*//) {
244         $LyX_Preamble .= "\\inputencoding $1\n";
245     }
246     $Latex_Preamble =~ s/\\usepackage\[.*\]\{fontenc\}\s*//;
247
248     ## Deal with several \usepackage{} cases
249     my %Usepackage_Table = (
250         "amsmath"       => "\\use_amsmath 1",
251         "amssymb"       => "",
252
253         "geometry"      => "\\use_geometry 1",
254
255         "babel"         => "",
256
257         "pslatex"       => "\\fontscheme pslatex",
258         "ae"            => "\\fontscheme ae",
259         "aecompl"       => "",
260         "times"         => "\\fontscheme times",
261         "palatino"      => "\\fontscheme palatino",
262         "helvet"        => "\\fontscheme helvet",
263         "avant"         => "\\fontscheme avant",
264         "newcent"       => "\\fontscheme newcent",
265         "bookman"       => "\\fontscheme bookman",
266
267         "a4wide"        => "\\paperpackage widemarginsa4",
268         "a4"            => "\\paperpackage a4wide",
269
270         "graphics"      => "\\graphics default",
271         "rotating"      => "",
272         "makeidx"       => "\\makeindex"
273     );
274
275     ## Babel with arguments specifing language
276     if($Latex_Preamble =~ s/\\usepackage\[(.*)\]\{babel\}\s*//) {
277         my @languages = split(',',$1);
278         my $lang = pop @languages;
279         $LyX_Preamble .= "\\language $lang\n";
280     }
281
282     my $up;
283     foreach $up (keys %Usepackage_Table) {
284         $Latex_Preamble =~ s/\\usepackage\{$up\}\s*// && do {
285             $LyX_Preamble .= "$Usepackage_Table{$up}";
286             $LyX_Preamble .= "\n" unless ($Usepackage_Table{$up} eq "");
287         }
288     }
289
290     ## Handle geometry options
291     ## The custom paper missing from the options list since it involves two parameters
292     my %Geometry_Options =(
293         'verbose'       => sub { return "" },
294
295         "letterpaper"   => sub { return "\\papersize letterpaper\n" },
296         "legalpaper"    => sub { return "\\papersize legalpaper\n" },
297         "executivepaper"=> sub { return "\\papersize executivepaper\n" },
298         "a3paper"       => sub { return "\\papersize a3paper\n" },
299         "a4paper"       => sub { return "\\papersize a4paper\n" },
300         "a5paper"       => sub { return "\\papersize a5paper\n" },
301         "b3paper"       => sub { return "\\papersize b3paper\n" },
302         "b4paper"       => sub { return "\\papersize b4paper\n" },
303         "b5paper"       => sub { return "\\papersize b5paper\n" },
304
305         'tmargin=(\w*)' => sub { return "\\topmargin $1\n" },
306         'bmargin=(\w*)' => sub { return "\\bottommargin $1\n" },
307         'lmargin=(\w*)' => sub { return "\\leftmargin $1\n" },
308         'rmargin=(\w*)' => sub { return "\\rightmargin $1\n" },
309         'headsep=(\w*)' => sub { return "\\headsep $1\n" },
310         'footskip=(\w*)'        => sub { return "\\footskip $1\n" },
311         'headheight=(\w*)'      => sub { return "\\headheight $1\n" }
312     );
313
314     if( $Latex_Preamble =~ /\\geometry\{(.*)\}/) {
315         my $geom_options = $1;
316         my $op;
317         foreach $op (keys %Geometry_Options) {
318             $geom_options =~ s/$op// && do {
319                 $LyX_Preamble .= &{$Geometry_Options{$op}}();
320                 print "Geometry option $op\n" if $debug_on;
321             }
322         }
323         $geom_options =~ s/^,+|,+(?=,)|,+$//g; # extra commas
324         if( $geom_options =~ /\s*/) {
325             $Latex_Preamble =~ s/\\geometry\{(.*)\}//;
326         }
327         else {
328             $Latex_Preamble =~ s/\\geometry\{(.*)\}/\\geometry\{$geom_options\}/;
329         }
330     }
331
332     ## Paragraph skip or indentation
333     if ( $Latex_Preamble =~ 
334          s/\\setlength\\parskip\{\\(.*)amount\}\s*\\setlength\\parindent\{0pt\}//) {
335         $LyX_Preamble .= "\\paragraph_separation skip\n";
336         $LyX_Preamble .= "\\defskip $1\n";
337     }
338
339     ## Paragraph spacing
340     if ( $Latex_Preamble =~ s/\\(\w*)spacing//) {
341         $LyX_Preamble .= "\\spacing  $1\n";
342     }
343
344     ## remove LyX specific stuff
345     $Latex_Preamble =~ s/\\IfFileExists\{url.sty\}\{\\usepackage\{url\}\}\s*\{\\newcommand\{\\url\}\{\\texttt\}\}\s*//;
346
347     ##  this two need probably a more fine grained control
348     $Latex_Preamble =~ s/\\makeatletter\s*//;
349     $Latex_Preamble =~ s/\\makeatother\s*//;
350
351     if ($write_preamble) {
352         $Latex_Preamble =~ s/^\s*//;
353         print "LaTeX preamble, consists of:\n$Latex_Preamble" if $debug_on;
354         if($Latex_Preamble) {
355             $Latex_Preamble = "\\begin_preamble\n$Latex_Preamble\\end_preamble\n";
356         }
357         print "End of LaTeX preamble\n" if $debug_on;
358     } else {
359         $Latex_Preamble = ""; #just comments, whitespace. Ignore them
360     }
361
362     #warn "Done creating LyX Preamble\n";
363     return ($class, $LyX_Preamble, $Latex_Preamble);
364 }
365
366 1; # return true value to calling program