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