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