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