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