]> git.lyx.org Git - lyx.git/blob - src/Converter.cpp
Do not terminate size switches in front of insets with InheritFont() false
[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), docbook_(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                         docbook_ = 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.docbook())
280                         return OutputParams::DOCBOOK5;
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->lang();
485                 // Some macros rely on font encoding
486                 runparams.main_fontenc = bp.main_font_encoding();
487                 runparams.only_childbibs = !bp.useBiblatex()
488                                 && !bp.useBibtopic()
489                                 && bp.multibib == "child";
490                 runparams.includeall = includeall;
491         }
492
493         // Some converters (e.g. lilypond) can only output files to the
494         // current directory, so we need to change the current directory.
495         // This has the added benefit that all other files that may be
496         // generated by the converter are deleted when LyX closes and do not
497         // clutter the real working directory.
498         // FIXME: This does not work if path is an UNC path on windows
499         //        (bug 6127).
500         string const path(onlyPath(from_file.absFileName()));
501         // Prevent the compiler from optimizing away p
502         FileName pp(path);
503         PathChanger p(pp);
504
505         // empty the error list before any new conversion takes place.
506         errorList.clear();
507
508         bool run_latex = false;
509         string from_base = changeExtension(from_file.absFileName(), "");
510         string to_base = changeExtension(to_file.absFileName(), "");
511         FileName infile;
512         FileName outfile = from_file;
513         for (auto const & edge : edgepath) {
514                 Converter const & conv = converterlist_[edge];
515                 bool dummy = conv.To()->dummy() && conv.to() != "program";
516                 if (!dummy) {
517                         LYXERR(Debug::FILES, "Converting from  "
518                                << conv.from() << " to " << conv.to());
519                 }
520                 infile = outfile;
521                 outfile = FileName(conv.result_file().empty()
522                         ? changeExtension(from_file.absFileName(), conv.To()->extension())
523                         : addName(subst(conv.result_dir(),
524                                         token_base, from_base),
525                                   subst(conv.result_file(),
526                                         token_base, onlyFileName(from_base))));
527
528                 // if input and output files are equal, we use a
529                 // temporary file as intermediary (JMarc)
530                 FileName real_outfile;
531                 if (!conv.result_file().empty())
532                         real_outfile = FileName(changeExtension(from_file.absFileName(),
533                                 conv.To()->extension()));
534                 if (outfile == infile) {
535                         real_outfile = infile;
536                         // when importing, a buffer does not necessarily exist
537                         if (buffer)
538                                 outfile = FileName(addName(buffer->temppath(), "tmpfile.out"));
539                         else
540                                 outfile = FileName(addName(package().temp_dir().absFileName(),
541                                                    "tmpfile.out"));
542                 }
543
544                 if (buffer && buffer->params().use_minted
545                     && lyxrc.pygmentize_command.empty() && conv.latex()) {
546                         bool dowarn = false;
547                         // Warn only if listings insets are actually used
548                         for (Paragraph const & par : buffer->paragraphs()) {
549                                 InsetList const & insets = par.insetList();
550                                 pos_type lstpos = insets.find(LISTINGS_CODE, 0);
551                                 pos_type incpos = insets.find(INCLUDE_CODE, 0);
552                                 if (incpos >= 0) {
553                                         InsetInclude const * include =
554                                                 static_cast<InsetInclude *>
555                                                         (insets.get(incpos));
556                                         if (include->params().getCmdName() !=
557                                                                 "inputminted") {
558                                                 incpos = -1;
559                                         }
560                                 }
561                                 if (lstpos >= 0 || incpos >= 0) {
562                                         dowarn = true;
563                                         break;
564                                 }
565                         }
566                         if (dowarn) {
567                                 Alert::warning(_("Pygments driver command not found!"),
568                                     _("The driver command necessary to use the minted package\n"
569                                       "(pygmentize) has not been found. Make sure you have\n"
570                                       "the python-pygments module installed or, if the driver\n"
571                                       "is named differently, to add the following line to the\n"
572                                       "document preamble:\n\n"
573                                       "\\AtBeginDocument{\\renewcommand{\\MintedPygmentize}{driver}}\n\n"
574                                       "where 'driver' is name of the driver command."));
575                         }
576                 }
577
578                 if (!checkAuth(conv, buffer ? buffer->absFileName() : string(),
579                                buffer && buffer->params().shell_escape))
580                         return FAILURE;
581
582                 if (conv.latex()) {
583                         // We are not importing, we have a buffer
584                         LASSERT(buffer, return FAILURE);
585                         run_latex = true;
586                         string command = conv.command();
587                         command = subst(command, token_from, "");
588                         command = subst(command, token_latex_encoding,
589                                         buffer->params().encoding().latexName());
590                         if (buffer->params().shell_escape
591                             && !contains(command, "-shell-escape"))
592                                 command += " -shell-escape ";
593                         LYXERR(Debug::FILES, "Running " << command);
594                         // FIXME KILLED
595                         // Check changed return value here.
596                         RetVal const retval = runLaTeX(*buffer, command, runparams, errorList);
597                         if (retval != SUCCESS)
598                                 return retval;
599                 } else {
600                         if (conv.need_aux() && !run_latex) {
601                                 // We are not importing, we have a buffer
602                                 LASSERT(buffer, return FAILURE);
603                                 string command;
604                                 switch (runparams.flavor) {
605                                 case OutputParams::DVILUATEX:
606                                         command = dvilualatex_command_;
607                                         break;
608                                 case OutputParams::LUATEX:
609                                         command = lualatex_command_;
610                                         break;
611                                 case OutputParams::PDFLATEX:
612                                         command = pdflatex_command_;
613                                         break;
614                                 case OutputParams::XETEX:
615                                         command = xelatex_command_;
616                                         break;
617                                 default:
618                                         command = latex_command_;
619                                         break;
620                                 }
621                                 if (!command.empty()) {
622                                         LYXERR(Debug::FILES, "Running "
623                                                 << command
624                                                 << " to update aux file");
625                                         // FIXME KILLED
626                                         // Check changed return value here.
627                                         RetVal const retval = runLaTeX(*buffer, command, runparams, errorList);
628                                                 if (retval != SUCCESS)
629                                                         return retval;
630                                 }
631                         }
632
633                         // FIXME UNICODE
634                         string const infile2 =
635                                 to_utf8(makeRelPath(from_utf8(infile.absFileName()), from_utf8(path)));
636                         string const outfile2 =
637                                 to_utf8(makeRelPath(from_utf8(outfile.absFileName()), from_utf8(path)));
638
639                         string command = conv.command();
640                         command = subst(command, token_from, quoteName(infile2));
641                         command = subst(command, token_base, quoteName(from_base));
642                         command = subst(command, token_to, quoteName(outfile2));
643                         command = subst(command, token_path, quoteName(onlyPath(infile.absFileName())));
644                         command = subst(command, token_orig_path, quoteName(onlyPath(orig_from.absFileName())));
645                         command = subst(command, token_orig_from, quoteName(onlyFileName(orig_from.absFileName())));
646                         command = subst(command, token_encoding, buffer ? buffer->params().encoding().iconvName() : string());
647
648                         if (!conv.parselog().empty())
649                                 command += " 2> " + quoteName(infile2 + ".out");
650
651                         // it is not actually not necessary to test for buffer here,
652                         // but it pleases coverity.
653                         if (buffer && conv.from() == "dvi" && conv.to() == "ps")
654                                 command = add_options(command,
655                                                       buffer->params().dvips_options());
656                         else if (buffer && conv.from() == "dvi" && prefixIs(conv.to(), "pdf"))
657                                 command = add_options(command,
658                                                       dvipdfm_options(buffer->params()));
659
660                         LYXERR(Debug::FILES, "Calling " << command);
661                         if (buffer)
662                                 buffer->message(_("Executing command: ")
663                                 + from_utf8(command));
664
665                         Systemcall one;
666                         int res;
667                         if (dummy) {
668                                 res = one.startscript(Systemcall::DontWait,
669                                         to_filesystem8bit(from_utf8(command)),
670                                         buffer ? buffer->filePath() : string(),
671                                         buffer ? buffer->layoutPos() : string());
672                                 // We're not waiting for the result, so we can't do anything
673                                 // else here.
674                         } else {
675                                 Systemcall::Starttype starttype =
676                                                 (buffer && buffer->isClone()) ?
677                                                         Systemcall::WaitLoop : Systemcall::Wait;
678                                 res = one.startscript(starttype,
679                                                 to_filesystem8bit(from_utf8(command)),
680                                                 buffer ? buffer->filePath()
681                                                        : string(),
682                                                 buffer ? buffer->layoutPos()
683                                                        : string());
684                                 if (res == Systemcall::KILLED) {
685                                         frontend::Alert::warning(
686                                                 _("Converter killed"),
687                                                 bformat(_("The following converter was killed by the user.\n %1$s\n"), 
688                                                         from_utf8(command)));
689                                         return KILLED;
690                                 }
691                                 
692                                 if (!real_outfile.empty()) {
693                                         Mover const & mover = getMover(conv.to());
694                                         if (!mover.rename(outfile, real_outfile))
695                                                 res = -1;
696                                         else
697                                                 LYXERR(Debug::FILES, "renaming file " << outfile
698                                                         << " to " << real_outfile);
699                                         // Finally, don't forget to tell any future
700                                         // converters to use the renamed file...
701                                         outfile = real_outfile;
702                                 }
703
704                                 if (!conv.parselog().empty()) {
705                                         string const logfile =  infile2 + ".log";
706                                         string const command2 = conv.parselog() +
707                                                 " < " + quoteName(infile2 + ".out") +
708                                                 " > " + quoteName(logfile);
709                                         res = one.startscript(starttype,
710                                                 to_filesystem8bit(from_utf8(command2)),
711                                                 buffer ? buffer->filePath() : string(),
712                                                 buffer ? buffer->layoutPos() : string());
713                                         if (res == Systemcall::KILLED) {
714                                                 frontend::Alert::warning(
715                                                         _("Converter killed"),
716                                                         bformat(_("The following converter was killed by the user.\n %1$s\n"), 
717                                                                 from_utf8(command)));
718                                                 return KILLED;
719                                         }
720                                         if (buffer && !scanLog(*buffer, command, makeAbsPath(logfile, path), errorList))
721                                                 return FAILURE;
722                                 }
723                         }
724
725                         if (res) {
726                                 if (res == Systemcall::KILLED) {
727                                         Alert::information(_("Process Killed"),
728                                                 bformat(_("The conversion process was killed while running:\n%1$s"),
729                                                         wrapParas(from_utf8(command))));
730                                         return KILLED;
731                                 } 
732                                 if (res == Systemcall::TIMEOUT) {
733                                         Alert::information(_("Process Timed Out"),
734                                                 bformat(_("The conversion process:\n%1$s\ntimed out before completing."),
735                                                         wrapParas(from_utf8(command))));
736                                         return KILLED;
737                                 } 
738                                 if (conv.to() == "program") {
739                                         Alert::error(_("Build errors"),
740                                                 _("There were errors during the build process."));
741                                 } else {
742 // FIXME: this should go out of here. For example, here we cannot say if
743 // it is a document (.lyx) or something else. Same goes for elsewhere.
744                                         Alert::error(_("Cannot convert file"),
745                                                 bformat(_("An error occurred while running:\n%1$s"),
746                                                 wrapParas(from_utf8(command))));
747                                 }
748                                 return FAILURE;
749                         }
750                 }
751         }
752
753         Converter const & conv = converterlist_[edgepath.back()];
754         if (conv.To()->dummy())
755                 return SUCCESS;
756
757         if (!conv.result_dir().empty()) {
758                 // The converter has put the file(s) in a directory.
759                 // In this case we ignore the given to_file.
760                 if (from_base != to_base) {
761                         string const from = subst(conv.result_dir(),
762                                             token_base, from_base);
763                         string const to = subst(conv.result_dir(),
764                                           token_base, to_base);
765                         Mover const & mover = getMover(conv.from());
766                         if (!mover.rename(FileName(from), FileName(to))) {
767                                 Alert::error(_("Cannot convert file"),
768                                         bformat(_("Could not move a temporary directory from %1$s to %2$s."),
769                                                 from_utf8(from), from_utf8(to)));
770                                 return FAILURE;
771                         }
772                 }
773                 return SUCCESS;
774         } else {
775                 if (conversionflags & try_cache)
776                         ConverterCache::get().add(orig_from, to_format, outfile);
777                 return move(conv.to(), outfile, to_file, conv.latex()) ? SUCCESS : FAILURE;
778         }
779 }
780
781
782 bool Converters::move(string const & fmt,
783                       FileName const & from, FileName const & to, bool copy)
784 {
785         if (from == to)
786                 return true;
787
788         bool no_errors = true;
789         string const path = onlyPath(from.absFileName());
790         string const base = onlyFileName(removeExtension(from.absFileName()));
791         string const to_base = removeExtension(to.absFileName());
792         string const to_extension = getExtension(to.absFileName());
793
794         support::FileNameList const files = FileName(path).dirList(getExtension(from.absFileName()));
795         for (auto const & f : files) {
796                 string const from2 = f.absFileName();
797                 string const file2 = onlyFileName(from2);
798                 if (prefixIs(file2, base)) {
799                         string const to2 = changeExtension(
800                                 to_base + file2.substr(base.length()),
801                                 to_extension);
802                         LYXERR(Debug::FILES, "moving " << from2 << " to " << to2);
803
804                         Mover const & mover = getMover(fmt);
805                         bool const moved = copy
806                                 ? mover.copy(f, FileName(to2))
807                                 : mover.rename(f, FileName(to2));
808                         if (!moved && no_errors) {
809                                 Alert::error(_("Cannot convert file"),
810                                         bformat(copy ?
811                                                 _("Could not copy a temporary file from %1$s to %2$s.") :
812                                                 _("Could not move a temporary file from %1$s to %2$s."),
813                                                 from_utf8(from2), from_utf8(to2)));
814                                 no_errors = false;
815                         }
816                 }
817         }
818         return no_errors;
819 }
820
821
822 bool Converters::formatIsUsed(string const & format)
823 {
824         for (auto const & cvt : converterlist_) {
825                 if (cvt.from() == format || cvt.to() == format)
826                         return true;
827         }
828         return false;
829 }
830
831
832 bool Converters::scanLog(Buffer const & buffer, string const & /*command*/,
833                          FileName const & filename, ErrorList & errorList)
834 {
835         OutputParams runparams(nullptr);
836         runparams.flavor = OutputParams::LATEX;
837         LaTeX latex("", runparams, filename);
838         TeXErrors terr;
839         int const result = latex.scanLogFile(terr);
840
841         if (result & LaTeX::ERRORS)
842                 buffer.bufferErrors(terr, errorList);
843
844         return true;
845 }
846
847
848 Converters::RetVal Converters::runLaTeX(Buffer const & buffer, string const & command,
849                           OutputParams const & runparams, ErrorList & errorList)
850 {
851         buffer.setBusy(true);
852         buffer.message(_("Running LaTeX..."));
853
854         // do the LaTeX run(s)
855         string const name = buffer.latexName();
856         LaTeX latex(command, runparams, FileName(makeAbsPath(name)),
857                     buffer.filePath(), buffer.layoutPos(),
858                     buffer.isClone(), buffer.freshStartRequired());
859         TeXErrors terr;
860         // The connection closes itself at the end of the scope when latex is
861         // destroyed. One cannot close (and destroy) buffer while the converter is
862         // running.
863         latex.message.connect([&buffer](docstring const & msg){
864                         buffer.message(msg);
865                 });
866         int const result = latex.run(terr);
867
868         if (result == Systemcall::KILLED || result == Systemcall::TIMEOUT) {
869                 Alert::error(_("Export canceled"),
870                         _("The export process was terminated by the user."));
871                 return KILLED;
872         }
873
874         if (result & LaTeX::ERRORS)
875                 buffer.bufferErrors(terr, errorList);
876
877         if ((result & LaTeX::UNDEF_CIT) || (result & LaTeX::UNDEF_UNKNOWN_REF)) {
878                 buffer.bufferRefs(terr, errorList);
879                 if (errorList.empty())
880                         errorList.push_back(ErrorItem(_("Undefined reference"),
881                                 _("Undefined references or citations were found during the build.\n"
882                                   "Please check the warnings in the LaTeX log (Document > LaTeX Log)."),
883                                 &buffer));
884         }
885
886         if (!errorList.empty()) {
887           // We will show the LaTeX Errors GUI later which contains
888           // specific error messages so it would be repetitive to give
889           // e.g. the "finished with an error" dialog in addition.
890         }
891         else if (result & LaTeX::NO_LOGFILE) {
892                 docstring const str =
893                         bformat(_("LaTeX did not run successfully. "
894                                                "Additionally, LyX could not locate "
895                                                "the LaTeX log %1$s."), from_utf8(name));
896                 Alert::error(_("LaTeX failed"), str);
897         } else if (result & LaTeX::NONZERO_ERROR) {
898                 docstring const str =
899                         bformat(_( "The external program\n%1$s\n"
900                               "finished with an error. "
901                               "It is recommended you fix the cause of the external "
902                               "program's error (check the logs). "), from_utf8(command));
903                 Alert::error(_("LaTeX failed"), str);
904         } else if (result & LaTeX::NO_OUTPUT) {
905                 Alert::warning(_("Output is empty"),
906                                _("No output file was generated."));
907         }
908
909         buffer.setBusy(false);
910
911         int const ERROR_MASK =
912                         LaTeX::NO_LOGFILE |
913                         LaTeX::ERRORS |
914                         LaTeX::UNDEF_CIT |
915                         LaTeX::UNDEF_UNKNOWN_REF |
916                         LaTeX::NO_OUTPUT;
917
918         return (result & ERROR_MASK) == 0 ? SUCCESS : FAILURE;
919 }
920
921
922
923 void Converters::buildGraph()
924 {
925         // clear graph's data structures
926         G_.init(theFormats().size());
927         // each of the converters knows how to convert one format to another
928         // so, for each of them, we create an arrow on the graph, going from
929         // the one to the other
930         for (auto const & cvt : converterlist_) {
931                 int const from = theFormats().getNumber(cvt.from());
932                 int const to   = theFormats().getNumber(cvt.to());
933                 LASSERT(from >= 0, continue);
934                 LASSERT(to >= 0, continue);
935                 G_.addEdge(from, to);
936         }
937 }
938
939
940 FormatList const Converters::intToFormat(vector<int> const & input)
941 {
942         FormatList result(input.size());
943
944         vector<int>::const_iterator it = input.begin();
945         vector<int>::const_iterator const end = input.end();
946         FormatList::iterator rit = result.begin();
947         for ( ; it != end; ++it, ++rit) {
948                 *rit = &theFormats().get(*it);
949         }
950         return result;
951 }
952
953
954 FormatList const Converters::getReachableTo(string const & target,
955                 bool const clear_visited)
956 {
957         vector<int> const & reachablesto =
958                 G_.getReachableTo(theFormats().getNumber(target), clear_visited);
959
960         return intToFormat(reachablesto);
961 }
962
963
964 FormatList const Converters::getReachable(string const & from,
965                 bool const only_viewable, bool const clear_visited,
966                 set<string> const & excludes)
967 {
968         set<int> excluded_numbers;
969
970         for (auto const & ex : excludes)
971                 excluded_numbers.insert(theFormats().getNumber(ex));
972
973         vector<int> const & reachables =
974                 G_.getReachable(theFormats().getNumber(from),
975                                 only_viewable,
976                                 clear_visited,
977                                 excluded_numbers);
978
979         return intToFormat(reachables);
980 }
981
982
983 bool Converters::isReachable(string const & from, string const & to)
984 {
985         return G_.isReachable(theFormats().getNumber(from),
986                               theFormats().getNumber(to));
987 }
988
989
990 Graph::EdgePath Converters::getPath(string const & from, string const & to)
991 {
992         return G_.getPath(theFormats().getNumber(from),
993                           theFormats().getNumber(to));
994 }
995
996
997 FormatList Converters::importableFormats()
998 {
999         vector<string> l = loaders();
1000         FormatList result = getReachableTo(l[0], true);
1001         vector<string>::const_iterator it = l.begin() + 1;
1002         vector<string>::const_iterator en = l.end();
1003         for (; it != en; ++it) {
1004                 FormatList r = getReachableTo(*it, false);
1005                 result.insert(result.end(), r.begin(), r.end());
1006         }
1007         return result;
1008 }
1009
1010
1011 FormatList Converters::exportableFormats(bool only_viewable)
1012 {
1013         vector<string> s = savers();
1014         FormatList result = getReachable(s[0], only_viewable, true);
1015         vector<string>::const_iterator it = s.begin() + 1;
1016         vector<string>::const_iterator en = s.end();
1017         for (; it != en; ++it) {
1018                  FormatList r = getReachable(*it, only_viewable, false);
1019                 result.insert(result.end(), r.begin(), r.end());
1020         }
1021         return result;
1022 }
1023
1024
1025 vector<string> Converters::loaders() const
1026 {
1027         vector<string> v;
1028         v.push_back("lyx");
1029         v.push_back("text");
1030         v.push_back("textparagraph");
1031         return v;
1032 }
1033
1034
1035 vector<string> Converters::savers() const
1036 {
1037         vector<string> v;
1038         v.push_back("docbook");
1039         v.push_back("latex");
1040         v.push_back("literate");
1041         v.push_back("luatex");
1042         v.push_back("dviluatex");
1043         v.push_back("lyx");
1044         v.push_back("xhtml");
1045         v.push_back("pdflatex");
1046         v.push_back("platex");
1047         v.push_back("text");
1048         v.push_back("xetex");
1049         return v;
1050 }
1051
1052
1053 } // namespace lyx