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