]> git.lyx.org Git - lyx.git/blob - src/converter.C
mathed31.diff
[lyx.git] / src / converter.C
1 /* This file is part of
2  * ====================================================== 
3  * 
4  *           LyX, The Document Processor
5  *        
6  *           Copyright 1995 Matthias Ettrich
7  *           Copyright 1995-2000 The LyX Team.
8  *
9  * ====================================================== */
10
11 #include <config.h>
12
13 #ifdef __GNUG__
14 #pragma implementation
15 #endif
16
17 #include <cctype>
18
19 #include "converter.h"
20 #include "lyxrc.h"
21 #include "support/syscall.h"
22 #include "support/path.h"
23 #include "support/filetools.h"
24 #include "buffer.h"
25 #include "bufferview_funcs.h"
26 #include "LaTeX.h"
27 #include "LyXView.h"
28 #include "minibuffer.h"
29 #include "lyx_gui_misc.h"
30 #include "lyx_cb.h" // ShowMessage()
31 #include "support/lyxfunctional.h"
32
33 using std::vector;
34 using std::queue;
35 using std::endl;
36 using std::fill;
37 using std::find_if;
38 using std::reverse;
39 using std::sort;
40
41 static string const token_from("$$i");
42 static string const token_base("$$b");
43 static string const token_to("$$o");
44
45 //////////////////////////////////////////////////////////////////////////////
46
47 static inline
48 string const add_options(string const & command, string const & options)
49 {
50         string head;
51         string const tail = split(command, head, ' ');
52         return head + ' ' + options + ' ' + tail;
53 }
54
55 //////////////////////////////////////////////////////////////////////////////
56
57 bool Format::dummy() const
58 {
59         return extension().empty();
60 }
61
62
63 bool Format::IsChildFormat() const
64 {
65         if (name_.empty())
66                 return false;
67         return isdigit(name_[name_.length() - 1]);
68 }
69
70
71 string const Format::ParentFormat() const
72 {
73         return name_.substr(0, name_.length() - 1);
74 }
75
76 //////////////////////////////////////////////////////////////////////////////
77
78 // This method should return a reference, and throw an exception
79 // if the format named name cannot be found (Lgb)
80 Format const * Formats::GetFormat(string const & name) const
81 {
82         FormatList::const_iterator cit =
83                 find_if(formatlist.begin(), formatlist.end(),
84                         compare_memfun(&Format::name, name));
85         if (cit != formatlist.end())
86                 return &(*cit);
87         else
88                 return 0;
89 }
90
91
92 int Formats::GetNumber(string const & name) const
93 {
94         FormatList::const_iterator cit =
95                 find_if(formatlist.begin(), formatlist.end(),
96                         compare_memfun(&Format::name, name));
97         if (cit != formatlist.end())
98                 return cit - formatlist.begin();
99         else
100                 return -1;
101 }
102
103
104 void Formats::Add(string const & name)
105 {
106         if (!GetFormat(name))
107                 Add(name, name, name, string());
108 }
109
110
111 void Formats::Add(string const & name, string const & extension, 
112                   string const & prettyname, string const & shortcut)
113 {
114         FormatList::iterator it = 
115                 find_if(formatlist.begin(), formatlist.end(),
116                         compare_memfun(&Format::name, name));
117         if (it == formatlist.end())
118                 formatlist.push_back(Format(name, extension, prettyname,
119                                             shortcut, ""));
120         else {
121                 string viewer = it->viewer();
122                 *it = Format(name, extension, prettyname, shortcut, viewer);
123         }
124 }
125
126
127 void Formats::Delete(string const & name)
128 {
129         FormatList::iterator it = 
130                 find_if(formatlist.begin(), formatlist.end(),
131                         compare_memfun(&Format::name, name));
132         if (it != formatlist.end())
133                 formatlist.erase(it);
134 }
135
136
137 void Formats::Sort()
138 {
139         sort(formatlist.begin(), formatlist.end());
140 }
141
142
143 void Formats::SetViewer(string const & name, string const & command)
144 {
145         Add(name);
146         FormatList::iterator it =
147                 find_if(formatlist.begin(), formatlist.end(),
148                         compare_memfun(&Format::name, name));
149         if (it != formatlist.end())
150                 it->setViewer(command);
151 }
152
153
154 bool Formats::View(Buffer const * buffer, string const & filename,
155                    string const & format_name) const
156 {
157         if (filename.empty())
158                 return false;
159
160         Format const * format = GetFormat(format_name);
161         if (format && format->viewer().empty() &&
162             format->IsChildFormat())
163                 format = GetFormat(format->ParentFormat());
164         if (!format || format->viewer().empty()) {
165                 WriteAlert(_("Can not view file"),
166                            _("No information for viewing ")
167                            + PrettyName(format_name));
168                            return false;
169         }
170
171         string command = format->viewer();
172
173         if (format_name == "dvi" &&
174             !lyxrc.view_dvi_paper_option.empty()) {
175                 command += " " + lyxrc.view_dvi_paper_option;
176                 string paper_size = converters.papersize(buffer);
177                 if (paper_size == "letter")
178                         paper_size = "us";
179                 command += " " + paper_size;
180                 if (buffer->params.orientation 
181                     == BufferParams::ORIENTATION_LANDSCAPE)
182                         command += 'r';
183         }
184
185         command += " " + QuoteName(OnlyFilename((filename)));
186
187         lyxerr << "Executing command: " << command << endl;
188         ShowMessage(buffer, _("Executing command:"), command);
189
190         Path p(OnlyPath(filename));
191         Systemcalls one;
192         int const res = one.startscript(Systemcalls::SystemDontWait, command);
193
194         if (res) {
195                 WriteAlert(_("Can not view file"),
196                            _("Error while executing"),
197                            command.substr(0, 50));
198                 return false;
199         }
200         return true;
201 }
202
203
204 string const Formats::PrettyName(string const & name) const
205 {
206         Format const * format = GetFormat(name);
207         if (format)
208                 return format->prettyname();
209         else
210                 return name;
211 }
212
213
214 string const Formats::Extension(string const & name) const
215 {
216         Format const * format = GetFormat(name);
217         if (format)
218                 return format->extension();
219         else
220                 return name;
221 }
222
223 //////////////////////////////////////////////////////////////////////////////
224
225 void Converter::ReadFlags()
226 {
227         string flag_list(flags);
228         while (!flag_list.empty()) {
229                 string flag_name, flag_value;
230                 flag_list = split(flag_list, flag_value, ',');
231                 flag_value = split(flag_value, flag_name, '=');
232                 if (flag_name == "latex")
233                         latex = true;
234                 else if (flag_name == "originaldir")
235                         original_dir = true;
236                 else if (flag_name == "needaux")
237                         need_aux = true;
238                 else if (flag_name == "resultdir")
239                         result_dir = (flag_value.empty())
240                                 ? token_base : flag_value;
241                 else if (flag_name == "resultfile")
242                         result_file = flag_value;
243                 else if (flag_name == "parselog")
244                         parselog = flag_value;
245         }
246         if (!result_dir.empty() && result_file.empty())
247                 result_file = "index." + formats.Extension(to);
248         //if (!contains(command, token_from))
249         //      latex = true;
250 }
251
252
253 bool operator<(Converter const & a, Converter const & b)
254 {
255         int const i = compare_no_case(a.From->prettyname(),
256                                       b.From->prettyname());
257         if (i == 0)
258                 return compare_no_case(a.To->prettyname(), b.To->prettyname())
259                         < 0;
260         else
261                 return i < 0;
262 }
263
264 //////////////////////////////////////////////////////////////////////////////
265
266 class compare_Converter {
267 public:
268         compare_Converter(string const & f, string const & t)
269                 : from(f), to(t) {}
270         bool operator()(Converter const & c) {
271                 return c.from == from && c.to == to;
272         }
273 private:
274         string const & from;
275         string const & to;
276 };
277
278
279 Converter const * Converters::GetConverter(string const & from,
280                                             string const & to)
281 {
282         ConverterList::const_iterator cit =
283                 find_if(converterlist.begin(), converterlist.end(),
284                         compare_Converter(from, to));
285         if (cit != converterlist.end())
286                 return &(*cit);
287         else
288                 return 0;
289 }
290
291
292 int Converters::GetNumber(string const & from, string const & to)
293 {
294         ConverterList::const_iterator cit =
295                 find_if(converterlist.begin(), converterlist.end(),
296                         compare_Converter(from, to));
297         if (cit != converterlist.end())
298                 return cit - converterlist.begin();
299         else
300                 return -1;
301 }
302
303
304 void Converters::Add(string const & from, string const & to,
305                      string const & command, string const & flags)
306 {
307         formats.Add(from);
308         formats.Add(to);
309         ConverterList::iterator it = find_if(converterlist.begin(),
310                                              converterlist.end(),
311                                              compare_Converter(from, to));
312
313         Converter converter(from, to, command, flags);
314         if (it != converterlist.end() && !flags.empty() && flags[0] == '*') {
315                 converter = *it;
316                 converter.command = command;
317                 converter.flags = flags;
318         }
319         converter.ReadFlags();
320         
321         if (converter.latex && (latex_command.empty() || to == "dvi"))
322                 latex_command = subst(command, token_from, "");
323         // If we have both latex & pdflatex, we set latex_command to latex.
324         // The latex_command is used to update the .aux file when running
325         // a converter that uses it.
326
327         if (it == converterlist.end())
328                 converterlist.push_back(converter);
329         else {
330                 converter.From = it->From;
331                 converter.To = it->To;
332                 *it = converter;
333         }
334 }
335
336
337 void Converters::Delete(string const & from, string const & to)
338 {
339         ConverterList::iterator it = find_if(converterlist.begin(),
340                                              converterlist.end(),
341                                              compare_Converter(from, to));
342         if (it != converterlist.end())
343                 converterlist.erase(it);
344 }
345
346
347 // This method updates the pointers From and To in all the converters.
348 // The code is not very efficient, but it doesn't matter as the number
349 // of formats and converters is small.
350 // Furthermore, this method is called only on startup, or after 
351 // adding/deleting a format in FormPreferences (the latter calls can be
352 // eliminated if the formats in the Formats class are stored using a map or
353 // a list (instead of a vector), but this will cause other problems). 
354 void Converters::Update(Formats const & formats)
355 {
356         for (ConverterList::iterator it = converterlist.begin();
357              it != converterlist.end(); ++it) {
358                 it->From = formats.GetFormat(it->from);
359                 it->To = formats.GetFormat(it->to);
360         }
361 }
362
363
364 // This method updates the pointers From and To in the last converter.
365 // It is called when adding a new converter in FormPreferences
366 void Converters::UpdateLast(Formats const & formats)
367 {
368         if (converterlist.begin() != converterlist.end()) {
369                 ConverterList::iterator it = converterlist.end()-1;
370                 it->From = formats.GetFormat(it->from);
371                 it->To = formats.GetFormat(it->to);
372         }
373 }
374
375
376 void Converters::Sort()
377 {
378         sort(converterlist.begin(), converterlist.end());
379 }
380
381
382 int Converters::BFS_init(string const & start, bool clear_visited)
383 {
384         int const s = formats.GetNumber(start);
385         if (s < 0)
386                 return s;
387
388         Q = queue<int>();
389         if (clear_visited)
390                 fill(visited.begin(), visited.end(), false);
391         if (visited[s] == false) {
392                 Q.push(s);
393                 visited[s] = true;
394         }
395         return s;
396 }
397
398
399 vector<Format const *> const
400 Converters::GetReachableTo(string const & target, bool clear_visited)
401 {
402         vector<Format const *> result;
403         int const s = BFS_init(target, clear_visited);
404         if (s < 0)
405                 return result;
406
407         while (!Q.empty()) {
408                 int const i = Q.front();
409                 Q.pop();
410                 if (i != s || target != "lyx")
411                         result.push_back(&formats.Get(i));
412                 for (vector<int>::iterator it = vertices[i].in_vertices.begin();
413                      it != vertices[i].in_vertices.end(); ++it)
414                         if (!visited[*it]) {
415                                 visited[*it] = true;
416                                 Q.push(*it);
417                         }
418         }
419
420         return result;
421 }
422
423
424 vector<Format const *> const
425 Converters::GetReachable(string const & from, bool only_viewable,
426                          bool clear_visited)
427 {
428         vector<Format const *> result;
429
430         if (BFS_init(from, clear_visited) < 0)
431                 return result;
432
433         while (!Q.empty()) {
434                 int const i = Q.front();
435                 Q.pop();
436                 Format const & format = formats.Get(i);
437                 if (format.name() == "lyx")
438                         continue;
439                 if (!only_viewable || !format.viewer().empty() ||
440                     format.IsChildFormat())
441                         result.push_back(&format);
442                 for (vector<int>::iterator it = vertices[i].out_vertices.begin();
443                      it != vertices[i].out_vertices.end(); ++it)
444                         if (!visited[*it]) {
445                                 visited[*it] = true;
446                                 Q.push(*it);
447                         }
448         }
449
450         return result;
451 }
452
453
454 bool Converters::IsReachable(string const & from, string const & to)
455 {
456         if (from == to)
457                 return true;
458
459         int const s = BFS_init(from);
460         int const t = formats.GetNumber(to);
461         if (s < 0 || t < 0)
462                 return false;
463
464         while (!Q.empty()) {
465                 int const i = Q.front();
466                 Q.pop();
467                 if (i == t)
468                         return true;
469                 for (vector<int>::iterator it = vertices[i].out_vertices.begin();
470                      it != vertices[i].out_vertices.end(); ++it)
471                         if (!visited[*it]) {
472                                 visited[*it] = true;
473                                 Q.push(*it);
474                         }
475         }
476
477         return false;
478 }
479
480
481 Converters::EdgePath const
482 Converters::GetPath(string const & from, string const & to)
483 {
484         EdgePath path;
485         if (from == to)
486                 return path;
487
488         int const s = BFS_init(from);
489         int t = formats.GetNumber(to);
490         if (s < 0 || t < 0)
491                 return path;
492
493         vector<int> prev_edge(formats.size());
494         vector<int> prev_vertex(formats.size());
495
496         bool found = false;
497         while (!Q.empty()) {
498                 int const i = Q.front();
499                 Q.pop();
500                 if (i == t) {
501                         found = true;
502                         break;
503                 }
504                 for (vector<int>::iterator it = vertices[i].out_vertices.begin();
505                      it != vertices[i].out_vertices.end(); ++it)
506                         if (!visited[*it]) {
507                                 int const j = *it;
508                                 visited[j] = true;
509                                 Q.push(j);
510                                 int const k = it - vertices[i].out_vertices.begin();
511                                 prev_edge[j] = vertices[i].out_edges[k];
512                                 prev_vertex[j] = i;
513                         }
514         }
515         if (!found)
516                 return path;
517
518         while (t != s) {
519                 path.push_back(prev_edge[t]);
520                 t = prev_vertex[t];
521         }
522         reverse(path.begin(), path.end());
523         return path;
524 }
525
526
527 bool Converters::UsePdflatex(EdgePath const & path)
528 {
529         for (EdgePath::const_iterator cit = path.begin();
530              cit != path.end(); ++cit) {
531                 Converter const & conv = converterlist[*cit];
532                 if (conv.latex)
533                         return contains(conv.to, "pdf");
534         }
535         return false;
536 }
537
538
539 bool Converters::Convert(Buffer const * buffer,
540                          string const & from_file, string const & to_file_base,
541                          string const & from_format, string const & to_format,
542                          string & to_file)
543 {
544         to_file = ChangeExtension(to_file_base,
545                                   formats.Extension(to_format));
546
547         if (from_format == to_format)
548                 return Move(from_file, to_file, false);
549
550         EdgePath edgepath = GetPath(from_format, to_format);
551         if (edgepath.empty()) {
552                 WriteAlert(_("Can not convert file"),
553                            _("No information for converting from ")
554                            + formats.PrettyName(from_format) + _(" to ")
555                            + formats.PrettyName(to_format));
556                 return false;
557         }
558
559         string path = OnlyPath(from_file);
560         Path p(path);
561
562         bool run_latex = false;
563         string from_base = ChangeExtension(from_file, "");
564         string to_base = ChangeExtension(to_file, "");
565         string infile;
566         string outfile = from_file;
567         for (EdgePath::const_iterator cit = edgepath.begin();
568              cit != edgepath.end(); ++cit) {
569                 Converter const & conv = converterlist[*cit];
570                 bool dummy = conv.To->dummy() && conv.to != "program";
571                 if (!dummy)
572                         lyxerr << "Converting from  "
573                                << conv.from << " to " << conv.to << endl;
574                 infile = outfile;
575                 outfile = conv.result_dir.empty()
576                         ? ChangeExtension(from_file, conv.To->extension())
577                         : AddName(subst(conv.result_dir,
578                                         token_base, from_base),
579                                   subst(conv.result_file,
580                                         token_base, OnlyFilename(from_base)));
581
582                 if (conv.latex) {
583                         run_latex = true;
584                         string command = subst(conv.command, token_from, "");
585                         lyxerr << "Running " << command << endl;
586                         if (!runLaTeX(buffer, command))
587                                 return false;
588                 } else {
589                         if (conv.need_aux && !run_latex
590                             && !latex_command.empty()) {
591                                 lyxerr << "Running " << latex_command 
592                                        << " to update aux file"<<  endl;
593                                 runLaTeX(buffer, latex_command);
594                         }
595
596                         string infile2 = (conv.original_dir)
597                                 ? infile : MakeRelPath(infile, path);
598                         string outfile2 = (conv.original_dir)
599                                 ? outfile : MakeRelPath(outfile, path);
600
601                         string command = conv.command;
602                         command = subst(command, token_from, QuoteName(infile2));
603                         command = subst(command, token_base, QuoteName(from_base));
604                         command = subst(command, token_to, QuoteName(outfile2));
605
606                         if (!conv.parselog.empty())
607                                 command += " 2> " + QuoteName(infile2 + ".out");
608
609                         if (conv.from == "dvi" && conv.to == "ps")
610                                 command = add_options(command,
611                                                       dvips_options(buffer));
612                         else if (conv.from == "dvi" && prefixIs(conv.to, "pdf"))
613                                 command = add_options(command,
614                                                       dvipdfm_options(buffer));
615
616                         lyxerr << "Calling " << command << endl;
617                         if (buffer)
618                                 ShowMessage(buffer, _("Executing command:"), command);
619
620                         Systemcalls::Starttype type = (dummy)
621                                 ? Systemcalls::SystemDontWait : Systemcalls::System;
622                         Systemcalls one;
623                         int res;
624                         if (conv.original_dir && buffer) {
625                                 Path p(buffer->filepath);
626                                 res = one.startscript(type, command);
627                         } else
628                                 res = one.startscript(type, command);
629
630                         if (!conv.parselog.empty()) {
631                                 string const logfile =  infile2 + ".log";
632                                 string const command2 = conv.parselog +
633                                         " < " + QuoteName(infile2 + ".out") +
634                                         " > " + QuoteName(logfile);
635                                 one.startscript(Systemcalls::System, command2);
636                                 if (!scanLog(buffer, command, logfile))
637                                         return false;
638                         }
639
640                         if (res) {
641                                 if (conv.to == "program")
642                                         WriteAlert(_("There were errors during the Build process."),
643                                                    _("You should try to fix them."));
644                                 else
645                                         WriteAlert(_("Can not convert file"),
646                                                    "Error while executing",
647                                                    command.substr(0, 50));
648                                 return false;
649                         }
650                 }
651         }
652
653         Converter const & conv = converterlist[edgepath.back()];
654         if (conv.To->dummy())
655                 return true;
656
657
658         if (!conv.result_dir.empty()) {
659                 to_file = AddName(subst(conv.result_dir, token_base, to_base),
660                                   subst(conv.result_file,
661                                         token_base, OnlyFilename(to_base)));
662                 if (from_base != to_base) {
663                         string from = subst(conv.result_dir,
664                                             token_base, from_base);
665                         string to = subst(conv.result_dir,
666                                           token_base, to_base);
667                         if (!lyx::rename(from, to)) {
668                                 WriteAlert(_("Error while trying to move directory:"),
669                                            from, ("to ") + to);
670                                 return false;
671                         }
672                 }
673                 return true;
674         } else 
675                 return Move(outfile, to_file, conv.latex);
676 }
677
678 // If from = /path/file.ext and to = /path2/file2.ext2 then this method 
679 // moves each /path/file*.ext file to /path2/file2*.ext2'
680 bool Converters::Move(string const & from, string const & to, bool copy)
681 {
682         if (from == to)
683                 return true;
684
685         bool no_errors = true;
686         string const path = OnlyPath(from);
687         string const base = OnlyFilename(ChangeExtension(from, ""));
688         string const to_base = ChangeExtension(to, "");
689         string const to_extension = GetExtension(to);
690
691         vector<string> files = DirList(OnlyPath(from), GetExtension(from));
692         for (vector<string>::const_iterator it = files.begin();
693              it != files.end(); ++it)
694                 if (prefixIs(*it, base)) {
695                         string from2 = path + *it;
696                         string to2 = to_base + (*it).substr(base.length());
697                         to2 = ChangeExtension(to2, to_extension);
698                         lyxerr << "moving " << from2 << " to " << to2 << endl;
699                         bool moved = (copy)
700                                 ? lyx::copy(from2, to2)
701                                 : lyx::rename(from2, to2);
702                         if (!moved && no_errors) {
703                                 WriteAlert(_("Error while trying to move file:"),
704                                            from2, _("to ") + to2);
705                                 no_errors = false;
706                         }
707                 }
708         return no_errors;
709 }
710
711 bool Converters::Convert(Buffer const * buffer,
712                         string const & from_file, string const & to_file_base,
713                         string const & from_format, string const & to_format)
714 {
715         string to_file;
716         return Convert(buffer, from_file, to_file_base, from_format, to_format,
717                        to_file);
718 }
719
720
721
722 void Converters::BuildGraph()
723 {
724         vertices = vector<Vertex>(formats.size());
725         visited.resize(formats.size());
726
727         for (ConverterList::iterator it = converterlist.begin();
728              it != converterlist.end(); ++it) {
729                 int const s = formats.GetNumber(it->from);
730                 int const t = formats.GetNumber(it->to);
731                 vertices[t].in_vertices.push_back(s);
732                 vertices[s].out_vertices.push_back(t);
733                 vertices[s].out_edges.push_back(it - converterlist.begin());
734         }
735 }
736
737
738 bool Converters::FormatIsUsed(string const & format)
739 {
740         for (ConverterList::const_iterator cit = converterlist.begin();
741             cit != converterlist.end(); ++cit)
742                 if (cit->from == format || cit->to == format)
743                         return true;
744         return false;
745 }
746
747
748 bool Converters::scanLog(Buffer const * buffer, string const & command,
749                         string const & filename)
750 {
751         if (!buffer)
752                 return false;
753
754         BufferView * bv = buffer->getUser();
755         bool need_redraw = false;
756         if (bv) {
757                 ProhibitInput(bv);
758                 // Remove all error insets
759                 need_redraw = bv->removeAutoInsets();
760         }
761
762         LaTeX latex("", filename, "");
763         TeXErrors terr;
764         int result = latex.scanLogFile(terr);
765         if (bv) {
766                 if ((result & LaTeX::ERRORS)) {
767                         // Insert all errors as errors boxes
768                         bv->insertErrors(terr);
769                         need_redraw = true;
770                 }
771                 if (need_redraw) {
772                         bv->redraw();
773                         bv->fitCursor(bv->text);
774                 }
775                 AllowInput(bv);
776         }
777
778         if ((result & LaTeX::ERRORS)) {
779                 int num_errors = latex.getNumErrors();
780                 string s;
781                 string t;
782                 if (num_errors == 1) {
783                         s = _("One error detected");
784                         t = _("You should try to fix it.");
785                 } else {
786                         s = tostr(num_errors);
787                         s += _(" errors detected.");
788                         t = _("You should try to fix them.");
789                 }
790                 string head;
791                 split(command, head, ' ');
792                 WriteAlert(_("There were errors during running of ") + head,
793                            s, t);
794                 return false;
795         } else if (result & LaTeX::NO_OUTPUT) {
796                 string const s = _("The operation resulted in");
797                 string const t = _("an empty file.");
798                 WriteAlert(_("Resulting file is empty"), s, t);
799                 return false;
800         }
801         return true;
802 }
803
804
805 bool Converters::runLaTeX(Buffer const * buffer, string const & command)
806 {
807         if (!buffer)
808                 return false;
809
810         BufferView * bv = buffer->getUser();
811         string name = buffer->getLatexName();
812         bool need_redraw = false;
813
814         if (bv) {
815                 ProhibitInput(bv);
816                 bv->owner()->getMiniBuffer()->Set(_("Running LaTeX..."));
817                 // Remove all error insets
818                 need_redraw = bv->removeAutoInsets();
819         }
820
821
822         // do the LaTex run(s)
823         TeXErrors terr;
824         LaTeX latex(command, name, buffer->filepath);
825         int result = latex.run(terr,
826                                bv ? bv->owner()->getMiniBuffer() : 0);
827         
828
829         if (bv) {
830                 if ((result & LaTeX::ERRORS)) {
831                         // Insert all errors as errors boxes
832                         bv->insertErrors(terr);
833                         need_redraw = true;
834                 }
835
836                 // if we removed error insets before we ran LaTeX or if we inserted
837                 // error insets after we ran LaTeX this must be run:
838                 if (need_redraw) {
839                         bv->redraw();
840                         bv->fitCursor(bv->text);
841                 }
842         }
843
844         // check return value from latex.run().
845         if ((result & LaTeX::NO_LOGFILE)) {
846                 WriteAlert(_("LaTeX did not work!"),
847                            _("Missing log file:"), name);
848         } else if ((result & LaTeX::ERRORS)) {
849                 int num_errors = latex.getNumErrors();
850                 string s;
851                 string t;
852                 if (num_errors == 1) {
853                         s = _("One error detected");
854                         t = _("You should try to fix it.");
855                 } else {
856                         s = tostr(num_errors);
857                         s += _(" errors detected.");
858                         t = _("You should try to fix them.");
859                 }
860                 WriteAlert(_("There were errors during the LaTeX run."),
861                            s, t);
862         }  else if (result & LaTeX::NO_OUTPUT) {
863                 string const s = _("The operation resulted in");
864                 string const t = _("an empty file.");
865                 WriteAlert(_("Resulting file is empty"), s, t);
866         }
867
868         if (bv)
869                 AllowInput(bv);
870  
871         int const ERROR_MASK = 
872                         LaTeX::NO_LOGFILE |
873                         LaTeX::ERRORS |
874                         LaTeX::NO_OUTPUT;
875         
876         return (result & ERROR_MASK) == 0;
877
878 }
879
880
881 string const Converters::papersize(Buffer const * buffer)
882 {
883         char real_papersize = buffer->params.papersize;
884         if (real_papersize == BufferParams::PAPER_DEFAULT)
885                 real_papersize = lyxrc.default_papersize;
886
887         switch (real_papersize) {
888         case BufferParams::PAPER_A3PAPER:
889                 return "a3";
890         case BufferParams::PAPER_A4PAPER:
891                 return "a4";
892         case BufferParams::PAPER_A5PAPER:
893                 return "a5";
894         case BufferParams::PAPER_B5PAPER:
895                 return "b5";
896         case BufferParams::PAPER_EXECUTIVEPAPER:
897                 return "foolscap";
898         case BufferParams::PAPER_LEGALPAPER:
899                 return "legal";
900         case BufferParams::PAPER_USLETTER:
901         default:
902                 return "letter";
903         }
904 }
905
906
907 string const Converters::dvips_options(Buffer const * buffer)
908 {
909         string result;
910         if (!buffer)
911                 return result;
912
913         if (buffer->params.use_geometry
914             && buffer->params.papersize2 == BufferParams::VM_PAPER_CUSTOM
915             && !lyxrc.print_paper_dimension_flag.empty()
916             && !buffer->params.paperwidth.empty()
917             && !buffer->params.paperheight.empty()) {
918                 // using a custom papersize
919                 result = lyxrc.print_paper_dimension_flag;
920                 result += ' ' + buffer->params.paperwidth;
921                 result += ',' + buffer->params.paperheight;
922         } else {
923                 string paper_option = papersize(buffer);
924                 if (paper_option != "letter" ||
925                     buffer->params.orientation != BufferParams::ORIENTATION_LANDSCAPE) {
926                         // dvips won't accept -t letter -t landscape.  In all other
927                         // cases, include the paper size explicitly.
928                         result = lyxrc.print_paper_flag;
929                         result += ' ' + paper_option;
930                 }
931         }
932         if (buffer->params.orientation == BufferParams::ORIENTATION_LANDSCAPE &&
933             buffer->params.papersize2 != BufferParams::VM_PAPER_CUSTOM)
934                 result += ' ' + lyxrc.print_landscape_flag;
935         return result;
936 }
937
938
939 string const Converters::dvipdfm_options(Buffer const * buffer)
940 {
941         string result;
942         if (!buffer)
943                 return result;
944
945         if (buffer->params.papersize2 != BufferParams::VM_PAPER_CUSTOM) {
946                 string paper_size = papersize(buffer);
947                 if (paper_size != "b5" && paper_size != "foolscap")
948                         result = "-p "+ paper_size;
949
950                 if (buffer->params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
951                         result += " -l";
952         }
953
954         return result;
955 }
956
957
958 vector<Converters::Vertex> Converters::vertices;
959
960
961 /// The global instance
962 Formats formats;
963 Converters converters;
964
965 // The global copy after reading lyxrc.defaults
966 Formats system_formats;
967 Converters system_converters;