]> git.lyx.org Git - lyx.git/blob - src/Converter.cpp
Account for old versions of Pygments
[lyx.git] / src / Converter.cpp
1 /**
2  * \file Converter.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Dekel Tsur
7  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 #include <config.h>
12
13 #include "Converter.h"
14
15 #include "Buffer.h"
16 #include "buffer_funcs.h"
17 #include "BufferParams.h"
18 #include "ConverterCache.h"
19 #include "Encoding.h"
20 #include "ErrorList.h"
21 #include "Format.h"
22 #include "Language.h"
23 #include "LaTeX.h"
24 #include "LyXRC.h"
25 #include "Mover.h"
26 #include "Session.h"
27
28 #include "frontends/alert.h"
29
30 #include "support/debug.h"
31 #include "support/FileNameList.h"
32 #include "support/filetools.h"
33 #include "support/gettext.h"
34 #include "support/lassert.h"
35 #include "support/lstrings.h"
36 #include "support/os.h"
37 #include "support/Package.h"
38 #include "support/PathChanger.h"
39 #include "support/Systemcall.h"
40
41 using namespace std;
42 using namespace lyx::support;
43
44 namespace lyx {
45
46 namespace Alert = lyx::frontend::Alert;
47
48
49 namespace {
50
51 string const token_from("$$i");
52 string const token_base("$$b");
53 string const token_to("$$o");
54 string const token_path("$$p");
55 string const token_orig_path("$$r");
56 string const token_orig_from("$$f");
57 string const token_encoding("$$e");
58 string const token_latex_encoding("$$E");
59
60
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
69 string const dvipdfm_options(BufferParams const & bp)
70 {
71         string result;
72
73         if (bp.papersize != PAPER_CUSTOM) {
74                 string const paper_size = bp.paperSizeName(BufferParams::DVIPDFM);
75                 if (!paper_size.empty())
76                         result = "-p "+ paper_size;
77
78                 if (bp.orientation == ORIENTATION_LANDSCAPE)
79                         result += " -l";
80         }
81
82         return result;
83 }
84
85
86 class ConverterEqual {
87 public:
88         ConverterEqual(string const & from, string const & to)
89                 : from_(from), to_(to) {}
90         bool operator()(Converter const & c) const {
91                 return c.from() == from_ && c.to() == to_;
92         }
93 private:
94         string const from_;
95         string const to_;
96 };
97
98 } // namespace anon
99
100
101 Converter::Converter(string const & f, string const & t,
102                      string const & c, string const & l)
103         : from_(f), to_(t), command_(c), flags_(l),
104           From_(0), To_(0), latex_(false), xml_(false),
105           need_aux_(false), nice_(false), need_auth_(false)
106 {}
107
108
109 void Converter::readFlags()
110 {
111         string flag_list(flags_);
112         while (!flag_list.empty()) {
113                 string flag_name, flag_value;
114                 flag_list = split(flag_list, flag_value, ',');
115                 flag_value = split(flag_value, flag_name, '=');
116                 if (flag_name == "latex") {
117                         latex_ = true;
118                         latex_flavor_ = flag_value.empty() ?
119                                 "latex" : flag_value;
120                 } else if (flag_name == "xml")
121                         xml_ = true;
122                 else if (flag_name == "needaux")
123                         need_aux_ = true;
124                 else if (flag_name == "resultdir")
125                         result_dir_ = (flag_value.empty())
126                                 ? token_base : flag_value;
127                 else if (flag_name == "resultfile")
128                         result_file_ = flag_value;
129                 else if (flag_name == "parselog")
130                         parselog_ = flag_value;
131                 else if (flag_name == "nice")
132                         nice_ = true;
133                 else if (flag_name == "needauth")
134                         need_auth_ = true;
135         }
136         if (!result_dir_.empty() && result_file_.empty())
137                 result_file_ = "index." + theFormats().extension(to_);
138         //if (!contains(command, token_from))
139         //      latex = true;
140 }
141
142
143 Converter const * Converters::getConverter(string const & from,
144                                             string const & to) const
145 {
146         ConverterList::const_iterator const cit =
147                 find_if(converterlist_.begin(), converterlist_.end(),
148                         ConverterEqual(from, to));
149         if (cit != converterlist_.end())
150                 return &(*cit);
151         else
152                 return 0;
153 }
154
155
156 int Converters::getNumber(string const & from, string const & to) const
157 {
158         ConverterList::const_iterator const cit =
159                 find_if(converterlist_.begin(), converterlist_.end(),
160                         ConverterEqual(from, to));
161         if (cit != converterlist_.end())
162                 return distance(converterlist_.begin(), cit);
163         else
164                 return -1;
165 }
166
167
168 void Converters::add(string const & from, string const & to,
169                      string const & command, string const & flags)
170 {
171         theFormats().add(from);
172         theFormats().add(to);
173         ConverterList::iterator it = find_if(converterlist_.begin(),
174                                              converterlist_.end(),
175                                              ConverterEqual(from , to));
176
177         Converter converter(from, to, command, flags);
178         if (it != converterlist_.end() && !flags.empty() && flags[0] == '*') {
179                 converter = *it;
180                 converter.setCommand(command);
181                 converter.setFlags(flags);
182         }
183         converter.readFlags();
184
185         // The latex_command is used to update the .aux file when running
186         // a converter that uses it.
187         if (converter.latex()) {
188                 if (latex_command_.empty() ||
189                     converter.latex_flavor() == "latex")
190                         latex_command_ = subst(command, token_from, "");
191                 if (dvilualatex_command_.empty() ||
192                     converter.latex_flavor() == "dvilualatex")
193                         dvilualatex_command_ = subst(command, token_from, "");
194                 if (lualatex_command_.empty() ||
195                     converter.latex_flavor() == "lualatex")
196                         lualatex_command_ = subst(command, token_from, "");
197                 if (pdflatex_command_.empty() ||
198                     converter.latex_flavor() == "pdflatex")
199                         pdflatex_command_ = subst(command, token_from, "");
200                 if (xelatex_command_.empty() ||
201                     converter.latex_flavor() == "xelatex")
202                         xelatex_command_ = subst(command, token_from, "");
203         }
204
205         if (it == converterlist_.end()) {
206                 converterlist_.push_back(converter);
207         } else {
208                 converter.setFrom(it->From());
209                 converter.setTo(it->To());
210                 *it = converter;
211         }
212 }
213
214
215 void Converters::erase(string const & from, string const & to)
216 {
217         ConverterList::iterator const it =
218                 find_if(converterlist_.begin(),
219                         converterlist_.end(),
220                         ConverterEqual(from, to));
221         if (it != converterlist_.end())
222                 converterlist_.erase(it);
223 }
224
225
226 // This method updates the pointers From and To in all the converters.
227 // The code is not very efficient, but it doesn't matter as the number
228 // of formats and converters is small.
229 // Furthermore, this method is called only on startup, or after
230 // adding/deleting a format in FormPreferences (the latter calls can be
231 // eliminated if the formats in the Formats class are stored using a map or
232 // a list (instead of a vector), but this will cause other problems).
233 void Converters::update(Formats const & formats)
234 {
235         ConverterList::iterator it = converterlist_.begin();
236         ConverterList::iterator end = converterlist_.end();
237         for (; it != end; ++it) {
238                 it->setFrom(formats.getFormat(it->from()));
239                 it->setTo(formats.getFormat(it->to()));
240         }
241 }
242
243
244 // This method updates the pointers From and To in the last converter.
245 // It is called when adding a new converter in FormPreferences
246 void Converters::updateLast(Formats const & formats)
247 {
248         if (converterlist_.begin() != converterlist_.end()) {
249                 ConverterList::iterator it = converterlist_.end() - 1;
250                 it->setFrom(formats.getFormat(it->from()));
251                 it->setTo(formats.getFormat(it->to()));
252         }
253 }
254
255
256 OutputParams::FLAVOR Converters::getFlavor(Graph::EdgePath const & path,
257                                            Buffer const * buffer)
258 {
259         for (Graph::EdgePath::const_iterator cit = path.begin();
260              cit != path.end(); ++cit) {
261                 Converter const & conv = converterlist_[*cit];
262                 if (conv.latex()) {
263                         if (conv.latex_flavor() == "latex")
264                                 return OutputParams::LATEX;
265                         if (conv.latex_flavor() == "xelatex")
266                                 return OutputParams::XETEX;
267                         if (conv.latex_flavor() == "lualatex")
268                                 return OutputParams::LUATEX;
269                         if (conv.latex_flavor() == "dvilualatex")
270                                 return OutputParams::DVILUATEX;
271                         if (conv.latex_flavor() == "pdflatex")
272                                 return OutputParams::PDFLATEX;
273                 }
274                 if (conv.xml())
275                         return OutputParams::XML;
276         }
277         return buffer ? buffer->params().getOutputFlavor()
278                       : OutputParams::LATEX;
279 }
280
281
282 bool Converters::checkAuth(Converter const & conv, string const & doc_fname)
283 {
284         if (!conv.need_auth())
285                 return true;
286         const docstring security_warning = bformat(
287               _("<p>The requested operation requires the use of a converter from "
288                 "%2$s to %3$s:</p>"
289                 "<blockquote><p><tt>%1$s</tt></p></blockquote>"
290                 "<p>This external program can execute arbitrary commands on your "
291                 "system, including dangerous ones, if instructed to do so by a "
292                 "maliciously crafted .lyx document.</p>"),
293               from_utf8(conv.command()), from_utf8(conv.from()),
294               from_utf8(conv.to()));
295         if (lyxrc.use_converter_needauth_forbidden) {
296                 frontend::Alert::error(
297                     _("An external converter is disabled for security reasons"),
298                     security_warning + _(
299                     "<p><b>Your current preference settings forbid its execution.</b></p>"
300                     "<p>(To change this setting, go to <i>Preferences &#x25b9; File "
301                     "Handling &#x25b9; Converters</i> and uncheck <i>Security &#x25b9; "
302                     "Forbid needauth converters</i>.)"), false);
303                 return false;
304         }
305         if (!lyxrc.use_converter_needauth)
306                 return true;
307         static const docstring security_title =
308                 _("An external converter requires your authorization");
309         int choice;
310         const docstring security_warning2 = security_warning +
311                 _("<p>Would you like to run this converter?</p>"
312                   "<p><b>Only run if you trust the origin/sender of the LyX "
313                   "document!</b></p>");
314         if (!doc_fname.empty()) {
315                 LYXERR(Debug::FILES, "looking up: " << doc_fname);
316                 std::set<std::string> & auth_files = theSession().authFiles().authFiles();
317                 if (auth_files.find(doc_fname) == auth_files.end()) {
318                         choice = frontend::Alert::prompt(security_title, security_warning2,
319                                 0, 0, _("Do &not run"), _("&Run"), _("&Always run for this document"));
320                         if (choice == 2)
321                                 auth_files.insert(doc_fname);
322                 } else {
323                         choice = 1;
324                 }
325         } else {
326                 choice = frontend::Alert::prompt(security_title, security_warning2,
327                         0, 0, _("Do &not run"), _("&Run"));
328         }
329         return choice != 0;
330 }
331
332
333 bool Converters::convert(Buffer const * buffer,
334                          FileName const & from_file, FileName const & to_file,
335                          FileName const & orig_from,
336                          string const & from_format, string const & to_format,
337                          ErrorList & errorList, int conversionflags)
338 {
339         if (from_format == to_format)
340                 return move(from_format, from_file, to_file, false);
341
342         if ((conversionflags & try_cache) &&
343             ConverterCache::get().inCache(orig_from, to_format))
344                 return ConverterCache::get().copy(orig_from, to_format, to_file);
345
346         Graph::EdgePath edgepath = getPath(from_format, to_format);
347         if (edgepath.empty()) {
348                 if (conversionflags & try_default) {
349                         // if no special converter defined, then we take the
350                         // default one from ImageMagic.
351                         string const from_ext = from_format.empty() ?
352                                 getExtension(from_file.absFileName()) :
353                                 theFormats().extension(from_format);
354                         string const to_ext = theFormats().extension(to_format);
355                         string const command =
356                                 os::python() + ' ' +
357                                 quoteName(libFileSearch("scripts", "convertDefault.py").toFilesystemEncoding()) +
358                                 ' ' + from_ext + ' ' +
359                                 quoteName(from_file.toFilesystemEncoding()) +
360                                 ' ' + to_ext + ' ' +
361                                 quoteName(to_file.toFilesystemEncoding());
362                         LYXERR(Debug::FILES, "No converter defined! "
363                                    "I use convertDefault.py:\n\t" << command);
364                         Systemcall one;
365                         one.startscript(Systemcall::Wait, command,
366                                         buffer ? buffer->filePath() : string(),
367                                         buffer ? buffer->layoutPos() : string());
368                         if (to_file.isReadableFile()) {
369                                 if (conversionflags & try_cache)
370                                         ConverterCache::get().add(orig_from,
371                                                         to_format, to_file);
372                                 return true;
373                         }
374                 }
375
376                 // only warn once per session and per file type
377                 static std::map<string, string> warned;
378                 if (warned.find(from_format) != warned.end() && warned.find(from_format)->second == to_format) {
379                         return false;
380                 }
381                 warned.insert(make_pair(from_format, to_format));
382
383                 Alert::error(_("Cannot convert file"),
384                              bformat(_("No information for converting %1$s "
385                                                     "format files to %2$s.\n"
386                                                     "Define a converter in the preferences."),
387                                                         from_ascii(from_format), from_ascii(to_format)));
388                 return false;
389         }
390
391         // buffer is only invalid for importing, and then runparams is not
392         // used anyway.
393         OutputParams runparams(buffer ? &buffer->params().encoding() : 0);
394         runparams.flavor = getFlavor(edgepath, buffer);
395
396         if (buffer) {
397                 runparams.use_japanese =
398                         buffer->params().bufferFormat() == "latex"
399                         && buffer->params().encoding().package() == Encoding::japanese;
400                 runparams.use_indices = buffer->params().use_indices;
401                 runparams.bibtex_command = buffer->params().bibtexCommand();
402                 runparams.index_command = (buffer->params().index_command == "default") ?
403                         string() : buffer->params().index_command;
404                 runparams.document_language = buffer->params().language->babel();
405                 runparams.only_childbibs = !buffer->params().useBiblatex()
406                                 && !buffer->params().useBibtopic()
407                                 && buffer->params().multibib == "child";
408         }
409
410         // Some converters (e.g. lilypond) can only output files to the
411         // current directory, so we need to change the current directory.
412         // This has the added benefit that all other files that may be
413         // generated by the converter are deleted when LyX closes and do not
414         // clutter the real working directory.
415         // FIXME: This does not work if path is an UNC path on windows
416         //        (bug 6127).
417         string const path(onlyPath(from_file.absFileName()));
418         // Prevent the compiler from optimizing away p
419         FileName pp(path);
420         PathChanger p(pp);
421
422         // empty the error list before any new conversion takes place.
423         errorList.clear();
424
425         bool run_latex = false;
426         string from_base = changeExtension(from_file.absFileName(), "");
427         string to_base = changeExtension(to_file.absFileName(), "");
428         FileName infile;
429         FileName outfile = from_file;
430         for (Graph::EdgePath::const_iterator cit = edgepath.begin();
431              cit != edgepath.end(); ++cit) {
432                 Converter const & conv = converterlist_[*cit];
433                 bool dummy = conv.To()->dummy() && conv.to() != "program";
434                 if (!dummy) {
435                         LYXERR(Debug::FILES, "Converting from  "
436                                << conv.from() << " to " << conv.to());
437                 }
438                 infile = outfile;
439                 outfile = FileName(conv.result_file().empty()
440                         ? changeExtension(from_file.absFileName(), conv.To()->extension())
441                         : addName(subst(conv.result_dir(),
442                                         token_base, from_base),
443                                   subst(conv.result_file(),
444                                         token_base, onlyFileName(from_base))));
445
446                 // if input and output files are equal, we use a
447                 // temporary file as intermediary (JMarc)
448                 FileName real_outfile;
449                 if (!conv.result_file().empty())
450                         real_outfile = FileName(changeExtension(from_file.absFileName(),
451                                 conv.To()->extension()));
452                 if (outfile == infile) {
453                         real_outfile = infile;
454                         // when importing, a buffer does not necessarily exist
455                         if (buffer)
456                                 outfile = FileName(addName(buffer->temppath(), "tmpfile.out"));
457                         else
458                                 outfile = FileName(addName(package().temp_dir().absFileName(),
459                                                    "tmpfile.out"));
460                 }
461
462                 if (!checkAuth(conv, buffer ? buffer->absFileName() : string()))
463                         return false;
464
465                 if (conv.latex()) {
466                         // We are not importing, we have a buffer
467                         LATTEST(buffer);
468                         run_latex = true;
469                         string command = conv.command();
470                         command = subst(command, token_from, "");
471                         command = subst(command, token_latex_encoding,
472                                         buffer->params().encoding().latexName());
473                         LYXERR(Debug::FILES, "Running " << command);
474                         if (!runLaTeX(*buffer, command, runparams, errorList))
475                                 return false;
476                 } else {
477                         if (conv.need_aux() && !run_latex) {
478                                 // We are not importing, we have a buffer
479                                 LATTEST(buffer);
480                                 string command;
481                                 switch (runparams.flavor) {
482                                 case OutputParams::DVILUATEX:
483                                         command = dvilualatex_command_;
484                                         break;
485                                 case OutputParams::LUATEX:
486                                         command = lualatex_command_;
487                                         break;
488                                 case OutputParams::PDFLATEX:
489                                         command = pdflatex_command_;
490                                         break;
491                                 case OutputParams::XETEX:
492                                         command = xelatex_command_;
493                                         break;
494                                 default:
495                                         command = latex_command_;
496                                         break;
497                                 }
498                                 if (!command.empty()) {
499                                         LYXERR(Debug::FILES, "Running "
500                                                 << command
501                                                 << " to update aux file");
502                                         if (!runLaTeX(*buffer, command,
503                                                       runparams, errorList))
504                                                 return false;
505                                 }
506                         }
507
508                         // FIXME UNICODE
509                         string const infile2 =
510                                 to_utf8(makeRelPath(from_utf8(infile.absFileName()), from_utf8(path)));
511                         string const outfile2 =
512                                 to_utf8(makeRelPath(from_utf8(outfile.absFileName()), from_utf8(path)));
513
514                         string command = conv.command();
515                         command = subst(command, token_from, quoteName(infile2));
516                         command = subst(command, token_base, quoteName(from_base));
517                         command = subst(command, token_to, quoteName(outfile2));
518                         command = subst(command, token_path, quoteName(onlyPath(infile.absFileName())));
519                         command = subst(command, token_orig_path, quoteName(onlyPath(orig_from.absFileName())));
520                         command = subst(command, token_orig_from, quoteName(onlyFileName(orig_from.absFileName())));
521                         command = subst(command, token_encoding, buffer ? buffer->params().encoding().iconvName() : string());
522
523                         if (!conv.parselog().empty())
524                                 command += " 2> " + quoteName(infile2 + ".out");
525
526                         // it is not actually not necessary to test for buffer here,
527                         // but it pleases coverity.
528                         if (buffer && conv.from() == "dvi" && conv.to() == "ps")
529                                 command = add_options(command,
530                                                       buffer->params().dvips_options());
531                         else if (buffer && conv.from() == "dvi" && prefixIs(conv.to(), "pdf"))
532                                 command = add_options(command,
533                                                       dvipdfm_options(buffer->params()));
534
535                         LYXERR(Debug::FILES, "Calling " << command);
536                         if (buffer)
537                                 buffer->message(_("Executing command: ")
538                                 + from_utf8(command));
539
540                         Systemcall one;
541                         int res;
542                         if (dummy) {
543                                 res = one.startscript(Systemcall::DontWait,
544                                         to_filesystem8bit(from_utf8(command)),
545                                         buffer ? buffer->filePath() : string(),
546                                         buffer ? buffer->layoutPos() : string());
547                                 // We're not waiting for the result, so we can't do anything
548                                 // else here.
549                         } else {
550                                 res = one.startscript(Systemcall::Wait,
551                                                 to_filesystem8bit(from_utf8(command)),
552                                                 buffer ? buffer->filePath()
553                                                        : string(),
554                                                 buffer ? buffer->layoutPos()
555                                                        : string());
556                                 if (!real_outfile.empty()) {
557                                         Mover const & mover = getMover(conv.to());
558                                         if (!mover.rename(outfile, real_outfile))
559                                                 res = -1;
560                                         else
561                                                 LYXERR(Debug::FILES, "renaming file " << outfile
562                                                         << " to " << real_outfile);
563                                         // Finally, don't forget to tell any future
564                                         // converters to use the renamed file...
565                                         outfile = real_outfile;
566                                 }
567
568                                 if (!conv.parselog().empty()) {
569                                         string const logfile =  infile2 + ".log";
570                                         string const command2 = conv.parselog() +
571                                                 " < " + quoteName(infile2 + ".out") +
572                                                 " > " + quoteName(logfile);
573                                         one.startscript(Systemcall::Wait,
574                                                 to_filesystem8bit(from_utf8(command2)),
575                                                 buffer->filePath(),
576                                                 buffer->layoutPos());
577                                         if (!scanLog(*buffer, command, makeAbsPath(logfile, path), errorList))
578                                                 return false;
579                                 }
580                         }
581
582                         if (res) {
583                                 if (conv.to() == "program") {
584                                         Alert::error(_("Build errors"),
585                                                 _("There were errors during the build process."));
586                                 } else {
587 // FIXME: this should go out of here. For example, here we cannot say if
588 // it is a document (.lyx) or something else. Same goes for elsewhere.
589                                         Alert::error(_("Cannot convert file"),
590                                                 bformat(_("An error occurred while running:\n%1$s"),
591                                                 wrapParas(from_utf8(command))));
592                                 }
593                                 return false;
594                         }
595                 }
596         }
597
598         Converter const & conv = converterlist_[edgepath.back()];
599         if (conv.To()->dummy())
600                 return true;
601
602         if (!conv.result_dir().empty()) {
603                 // The converter has put the file(s) in a directory.
604                 // In this case we ignore the given to_file.
605                 if (from_base != to_base) {
606                         string const from = subst(conv.result_dir(),
607                                             token_base, from_base);
608                         string const to = subst(conv.result_dir(),
609                                           token_base, to_base);
610                         Mover const & mover = getMover(conv.from());
611                         if (!mover.rename(FileName(from), FileName(to))) {
612                                 Alert::error(_("Cannot convert file"),
613                                         bformat(_("Could not move a temporary directory from %1$s to %2$s."),
614                                                 from_utf8(from), from_utf8(to)));
615                                 return false;
616                         }
617                 }
618                 return true;
619         } else {
620                 if (conversionflags & try_cache)
621                         ConverterCache::get().add(orig_from, to_format, outfile);
622                 return move(conv.to(), outfile, to_file, conv.latex());
623         }
624 }
625
626
627 bool Converters::move(string const & fmt,
628                       FileName const & from, FileName const & to, bool copy)
629 {
630         if (from == to)
631                 return true;
632
633         bool no_errors = true;
634         string const path = onlyPath(from.absFileName());
635         string const base = onlyFileName(removeExtension(from.absFileName()));
636         string const to_base = removeExtension(to.absFileName());
637         string const to_extension = getExtension(to.absFileName());
638
639         support::FileNameList const files = FileName(path).dirList(getExtension(from.absFileName()));
640         for (support::FileNameList::const_iterator it = files.begin();
641              it != files.end(); ++it) {
642                 string const from2 = it->absFileName();
643                 string const file2 = onlyFileName(from2);
644                 if (prefixIs(file2, base)) {
645                         string const to2 = changeExtension(
646                                 to_base + file2.substr(base.length()),
647                                 to_extension);
648                         LYXERR(Debug::FILES, "moving " << from2 << " to " << to2);
649
650                         Mover const & mover = getMover(fmt);
651                         bool const moved = copy
652                                 ? mover.copy(*it, FileName(to2))
653                                 : mover.rename(*it, FileName(to2));
654                         if (!moved && no_errors) {
655                                 Alert::error(_("Cannot convert file"),
656                                         bformat(copy ?
657                                                 _("Could not copy a temporary file from %1$s to %2$s.") :
658                                                 _("Could not move a temporary file from %1$s to %2$s."),
659                                                 from_utf8(from2), from_utf8(to2)));
660                                 no_errors = false;
661                         }
662                 }
663         }
664         return no_errors;
665 }
666
667
668 bool Converters::formatIsUsed(string const & format)
669 {
670         ConverterList::const_iterator cit = converterlist_.begin();
671         ConverterList::const_iterator end = converterlist_.end();
672         for (; cit != end; ++cit) {
673                 if (cit->from() == format || cit->to() == format)
674                         return true;
675         }
676         return false;
677 }
678
679
680 bool Converters::scanLog(Buffer const & buffer, string const & /*command*/,
681                          FileName const & filename, ErrorList & errorList)
682 {
683         OutputParams runparams(0);
684         runparams.flavor = OutputParams::LATEX;
685         LaTeX latex("", runparams, filename);
686         TeXErrors terr;
687         int const result = latex.scanLogFile(terr);
688
689         if (result & LaTeX::ERRORS)
690                 buffer.bufferErrors(terr, errorList);
691
692         return true;
693 }
694
695
696 bool Converters::runLaTeX(Buffer const & buffer, string const & command,
697                           OutputParams const & runparams, ErrorList & errorList)
698 {
699         buffer.setBusy(true);
700         buffer.message(_("Running LaTeX..."));
701
702         // do the LaTeX run(s)
703         string const name = buffer.latexName();
704         LaTeX latex(command, runparams, FileName(makeAbsPath(name)),
705                     buffer.filePath(), buffer.layoutPos(),
706                     buffer.lastPreviewError());
707         TeXErrors terr;
708         // The connection closes itself at the end of the scope when latex is
709         // destroyed. One cannot close (and destroy) buffer while the converter is
710         // running.
711         latex.message.connect([&buffer](docstring const & msg){
712                         buffer.message(msg);
713                 });
714         int const result = latex.run(terr);
715
716         if (result & LaTeX::ERRORS)
717                 buffer.bufferErrors(terr, errorList);
718
719         if (!errorList.empty()) {
720           // We will show the LaTeX Errors GUI later which contains
721           // specific error messages so it would be repetitive to give
722           // e.g. the "finished with an error" dialog in addition.
723         }
724         else if (result & LaTeX::NO_LOGFILE) {
725                 docstring const str =
726                         bformat(_("LaTeX did not run successfully. "
727                                                "Additionally, LyX could not locate "
728                                                "the LaTeX log %1$s."), from_utf8(name));
729                 Alert::error(_("LaTeX failed"), str);
730         } else if (result & LaTeX::NONZERO_ERROR) {
731                 docstring const str =
732                         bformat(_( "The external program\n%1$s\n"
733                               "finished with an error. "
734                               "It is recommended you fix the cause of the external "
735                               "program's error (check the logs). "), from_utf8(command));
736                 Alert::error(_("LaTeX failed"), str);
737         } else if (result & LaTeX::NO_OUTPUT) {
738                 Alert::warning(_("Output is empty"),
739                                _("No output file was generated."));
740         }
741
742
743         buffer.setBusy(false);
744
745         int const ERROR_MASK =
746                         LaTeX::NO_LOGFILE |
747                         LaTeX::ERRORS |
748                         LaTeX::NO_OUTPUT;
749
750         return (result & ERROR_MASK) == 0;
751 }
752
753
754
755 void Converters::buildGraph()
756 {
757         // clear graph's data structures
758         G_.init(theFormats().size());
759         // each of the converters knows how to convert one format to another
760         // so, for each of them, we create an arrow on the graph, going from
761         // the one to the other
762         ConverterList::iterator it = converterlist_.begin();
763         ConverterList::iterator const end = converterlist_.end();
764         for (; it != end ; ++it) {
765                 int const from = theFormats().getNumber(it->from());
766                 int const to   = theFormats().getNumber(it->to());
767                 LASSERT(from >= 0, continue);
768                 LASSERT(to >= 0, continue);
769                 G_.addEdge(from, to);
770         }
771 }
772
773
774 FormatList const Converters::intToFormat(vector<int> const & input)
775 {
776         FormatList result(input.size());
777
778         vector<int>::const_iterator it = input.begin();
779         vector<int>::const_iterator const end = input.end();
780         FormatList::iterator rit = result.begin();
781         for ( ; it != end; ++it, ++rit) {
782                 *rit = &theFormats().get(*it);
783         }
784         return result;
785 }
786
787
788 FormatList const Converters::getReachableTo(string const & target, 
789                 bool const clear_visited)
790 {
791         vector<int> const & reachablesto =
792                 G_.getReachableTo(theFormats().getNumber(target), clear_visited);
793
794         return intToFormat(reachablesto);
795 }
796
797
798 FormatList const Converters::getReachable(string const & from, 
799                 bool const only_viewable, bool const clear_visited, 
800                 set<string> const & excludes)
801 {
802         set<int> excluded_numbers;
803
804         set<string>::const_iterator sit = excludes.begin();
805         set<string>::const_iterator const end = excludes.end();
806         for (; sit != end; ++sit)
807                 excluded_numbers.insert(theFormats().getNumber(*sit));
808
809         vector<int> const & reachables =
810                 G_.getReachable(theFormats().getNumber(from),
811                                 only_viewable,
812                                 clear_visited,
813                                 excluded_numbers);
814
815         return intToFormat(reachables);
816 }
817
818
819 bool Converters::isReachable(string const & from, string const & to)
820 {
821         return G_.isReachable(theFormats().getNumber(from),
822                               theFormats().getNumber(to));
823 }
824
825
826 Graph::EdgePath Converters::getPath(string const & from, string const & to)
827 {
828         return G_.getPath(theFormats().getNumber(from),
829                           theFormats().getNumber(to));
830 }
831
832
833 FormatList Converters::importableFormats()
834 {
835         vector<string> l = loaders();
836         FormatList result = getReachableTo(l[0], true);
837         vector<string>::const_iterator it = l.begin() + 1;
838         vector<string>::const_iterator en = l.end();
839         for (; it != en; ++it) {
840                 FormatList r = getReachableTo(*it, false);
841                 result.insert(result.end(), r.begin(), r.end());
842         }
843         return result;
844 }
845
846
847 FormatList Converters::exportableFormats(bool only_viewable)
848 {
849         vector<string> s = savers();
850         FormatList result = getReachable(s[0], only_viewable, true);
851         vector<string>::const_iterator it = s.begin() + 1;
852         vector<string>::const_iterator en = s.end();
853         for (; it != en; ++it) {
854                  FormatList r = getReachable(*it, only_viewable, false);
855                 result.insert(result.end(), r.begin(), r.end());
856         }
857         return result;
858 }
859
860
861 vector<string> Converters::loaders() const
862 {
863         vector<string> v;
864         v.push_back("lyx");
865         v.push_back("text");
866         v.push_back("textparagraph");
867         return v;
868 }
869
870
871 vector<string> Converters::savers() const
872 {
873         vector<string> v;
874         v.push_back("docbook");
875         v.push_back("latex");
876         v.push_back("literate");
877         v.push_back("luatex");
878         v.push_back("dviluatex");
879         v.push_back("lyx");
880         v.push_back("xhtml");
881         v.push_back("pdflatex");
882         v.push_back("platex");
883         v.push_back("text");
884         v.push_back("xetex");
885         return v;
886 }
887
888
889 } // namespace lyx