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