3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
8 * Full author contact details are available in file CREDITS.
13 #include "Converter.h"
16 #include "BufferParams.h"
17 #include "ConverterCache.h"
19 #include "ErrorList.h"
21 #include "InsetList.h"
26 #include "OutputParams.h"
27 #include "ParagraphList.h"
30 #include "frontends/alert.h"
32 #include "insets/InsetInclude.h"
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"
46 using namespace lyx::support;
50 namespace Alert = lyx::frontend::Alert;
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 string const token_python("$${python}");
65 string const add_options(string const & command, string const & options)
68 string const tail = split(command, head, ' ');
69 return head + ' ' + options + ' ' + tail;
73 string const dvipdfm_options(BufferParams const & bp)
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;
82 if (bp.orientation == ORIENTATION_LANDSCAPE)
90 class ConverterEqual {
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_;
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)
113 void Converter::readFlags()
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") {
122 latex_flavor_ = flag_value.empty() ?
123 "latex" : flag_value;
124 } else if (flag_name == "xml")
126 else if (flag_name == "needaux") {
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")
139 else if (flag_name == "needauth")
141 else if (flag_name == "hyperref-driver")
142 href_driver_ = flag_value;
144 if (!result_dir_.empty() && result_file_.empty())
145 result_file_ = "index." + theFormats().extension(to_);
146 //if (!contains(command, token_from))
151 void Converter::setCommand(std::string const & command)
153 command_ = subst(command, token_python, os::python());
157 Converter const * Converters::getConverter(string const & from,
158 string const & to) const
160 ConverterList::const_iterator const cit =
161 find_if(converterlist_.begin(), converterlist_.end(),
162 ConverterEqual(from, to));
163 if (cit != converterlist_.end())
170 int Converters::getNumber(string const & from, string const & to) const
172 ConverterList::const_iterator const cit =
173 find_if(converterlist_.begin(), converterlist_.end(),
174 ConverterEqual(from, to));
175 if (cit != converterlist_.end())
176 return distance(converterlist_.begin(), cit);
182 void Converters::add(string const & from, string const & to,
183 string const & command, string const & flags)
185 theFormats().add(from);
186 theFormats().add(to);
187 ConverterList::iterator it = find_if(converterlist_.begin(),
188 converterlist_.end(),
189 ConverterEqual(from , to));
191 Converter converter(from, to, command, flags);
192 if (it != converterlist_.end() && !flags.empty() && flags[0] == '*') {
194 converter.setCommand(command);
195 converter.setFlags(flags);
197 converter.readFlags();
199 // The latex_command is used to update the .aux file when running
200 // a converter that uses it.
201 if (converter.latex()) {
202 if (latex_command_.empty() ||
203 converter.latex_flavor() == "latex")
204 latex_command_ = subst(command, token_from, "");
205 if (dvilualatex_command_.empty() ||
206 converter.latex_flavor() == "dvilualatex")
207 dvilualatex_command_ = subst(command, token_from, "");
208 if (lualatex_command_.empty() ||
209 converter.latex_flavor() == "lualatex")
210 lualatex_command_ = subst(command, token_from, "");
211 if (pdflatex_command_.empty() ||
212 converter.latex_flavor() == "pdflatex")
213 pdflatex_command_ = subst(command, token_from, "");
214 if (xelatex_command_.empty() ||
215 converter.latex_flavor() == "xelatex")
216 xelatex_command_ = subst(command, token_from, "");
219 if (it == converterlist_.end()) {
220 converterlist_.push_back(converter);
222 converter.setFrom(it->From());
223 converter.setTo(it->To());
229 void Converters::erase(string const & from, string const & to)
231 ConverterList::iterator const it =
232 find_if(converterlist_.begin(),
233 converterlist_.end(),
234 ConverterEqual(from, to));
235 if (it != converterlist_.end())
236 converterlist_.erase(it);
240 // This method updates the pointers From and To in all the converters.
241 // The code is not very efficient, but it doesn't matter as the number
242 // of formats and converters is small.
243 // Furthermore, this method is called only on startup, or after
244 // adding/deleting a format in FormPreferences (the latter calls can be
245 // eliminated if the formats in the Formats class are stored using a map or
246 // a list (instead of a vector), but this will cause other problems).
247 void Converters::update(Formats const & formats)
249 for (auto & cv : converterlist_) {
250 cv.setFrom(formats.getFormat(cv.from()));
251 cv.setTo(formats.getFormat(cv.to()));
256 // This method updates the pointers From and To in the last converter.
257 // It is called when adding a new converter in FormPreferences
258 void Converters::updateLast(Formats const & formats)
260 if (converterlist_.begin() != converterlist_.end()) {
261 ConverterList::iterator it = converterlist_.end() - 1;
262 it->setFrom(formats.getFormat(it->from()));
263 it->setTo(formats.getFormat(it->to()));
268 Flavor Converters::getFlavor(Graph::EdgePath const & path,
269 Buffer const * buffer) const
271 for (auto const & edge : path) {
272 Converter const & conv = converterlist_[edge];
273 if (conv.latex() || conv.need_aux()) {
274 if (conv.latex_flavor() == "latex")
275 return Flavor::LaTeX;
276 if (conv.latex_flavor() == "xelatex")
277 return Flavor::XeTeX;
278 if (conv.latex_flavor() == "lualatex")
279 return Flavor::LuaTeX;
280 if (conv.latex_flavor() == "dvilualatex")
281 return Flavor::DviLuaTeX;
282 if (conv.latex_flavor() == "pdflatex")
283 return Flavor::PdfLaTeX;
286 return Flavor::DocBook5;
288 return buffer ? buffer->params().getOutputFlavor()
293 string Converters::getHyperrefDriver(Graph::EdgePath const & path) const
295 for (auto const & edge : path) {
296 Converter const & conv = converterlist_[edge];
297 if (!conv.hyperref_driver().empty())
298 return conv.hyperref_driver();
304 bool Converters::checkAuth(Converter const & conv, string const & doc_fname,
305 bool use_shell_escape)
307 string conv_command = conv.command();
308 bool const has_shell_escape = contains(conv_command, "-shell-escape")
309 || contains(conv_command, "-enable-write18");
310 if (conv.latex() && has_shell_escape && !use_shell_escape) {
311 docstring const shellescape_warning =
312 bformat(_("<p>The following LaTeX backend has been "
313 "configured to allow execution of external programs "
314 "for any document:</p>"
315 "<center><p><tt>%1$s</tt></p></center>"
316 "<p>This is a dangerous configuration. Please, "
317 "consider using the support offered by LyX for "
318 "allowing this privilege only to documents that "
319 "actually need it, instead.</p>"),
320 from_utf8(conv_command));
321 frontend::Alert::error(_("Security Warning"),
322 shellescape_warning , false);
323 } else if (!conv.latex())
324 use_shell_escape = false;
325 if (!conv.need_auth() && !use_shell_escape)
327 size_t const token_pos = conv_command.find("$$");
328 bool const has_token = token_pos != string::npos;
329 string const command = use_shell_escape && !has_shell_escape
330 ? (has_token ? conv_command.insert(token_pos, "-shell-escape ")
331 : conv_command.append(" -shell-escape"))
333 docstring const security_warning = (use_shell_escape
334 ? bformat(_("<p>The following LaTeX backend has been requested "
335 "to allow execution of external programs:</p>"
336 "<center><p><tt>%1$s</tt></p></center>"
337 "<p>The external programs can execute arbitrary commands on "
338 "your system, including dangerous ones, if instructed to do "
339 "so by a maliciously crafted LyX document.</p>"),
341 : bformat(_("<p>The requested operation requires the use of a "
342 "converter from %2$s to %3$s:</p>"
343 "<blockquote><p><tt>%1$s</tt></p></blockquote>"
344 "<p>This external program can execute arbitrary commands on "
345 "your system, including dangerous ones, if instructed to do "
346 "so by a maliciously crafted LyX document.</p>"),
347 from_utf8(command), from_utf8(conv.from()),
348 from_utf8(conv.to())));
349 if (lyxrc.use_converter_needauth_forbidden && !use_shell_escape) {
350 frontend::Alert::error(
351 _("An external converter is disabled for security reasons"),
352 security_warning + _(
353 "<p><b>Your current preference settings forbid its execution.</b></p>"
354 "<p>(To change this setting, go to <i>Preferences ▹ File "
355 "Handling ▹ Converters</i> and uncheck <i>Security ▹ "
356 "Forbid needauth converters</i>.)"), false);
359 if (!lyxrc.use_converter_needauth && !use_shell_escape)
361 docstring const security_title = use_shell_escape
362 ? _("A LaTeX backend requires your authorization")
363 : _("An external converter requires your authorization");
365 docstring const security_warning2 = security_warning + (use_shell_escape
366 ? _("<p>Should LaTeX backends be allowed to run external "
367 "programs?</p><p><b>Allow them only if you trust the "
368 "origin/sender of the LyX document!</b></p>")
369 : _("<p>Would you like to run this converter?</p>"
370 "<p><b>Only run if you trust the origin/sender of the LyX "
371 "document!</b></p>"));
372 docstring const no = use_shell_escape
373 ? _("Do ¬ allow") : _("Do ¬ run");
374 docstring const yes = use_shell_escape ? _("A&llow") : _("&Run");
375 docstring const always = use_shell_escape
376 ? _("&Always allow for this document")
377 : _("&Always run for this document");
378 if (!doc_fname.empty()) {
379 LYXERR(Debug::FILES, "looking up: " << doc_fname);
380 bool authorized = use_shell_escape
381 ? theSession().shellescapeFiles().findAuth(doc_fname)
382 : theSession().authFiles().find(doc_fname);
384 choice = frontend::Alert::prompt(security_title,
386 0, 0, no, yes, always);
388 if (use_shell_escape)
389 theSession().shellescapeFiles().insert(doc_fname, true);
391 theSession().authFiles().insert(doc_fname);
397 choice = frontend::Alert::prompt(security_title,
405 Converters::RetVal Converters::convert(Buffer const * buffer,
406 FileName const & from_file, FileName const & to_file,
407 FileName const & orig_from,
408 string const & from_format, string const & to_format,
409 ErrorList & errorList, int conversionflags, bool includeall)
411 if (from_format == to_format)
412 return move(from_format, from_file, to_file, false) ?
415 if ((conversionflags & try_cache) &&
416 ConverterCache::get().inCache(orig_from, to_format))
417 return ConverterCache::get().copy(orig_from, to_format, to_file) ?
420 Graph::EdgePath edgepath = getPath(from_format, to_format);
421 if (edgepath.empty()) {
422 if (conversionflags & try_default) {
423 // if no special converter defined, then we take the
424 // default one from ImageMagic.
425 string const from_ext = from_format.empty() ?
426 getExtension(from_file.absFileName()) :
427 theFormats().extension(from_format);
428 string const to_ext = theFormats().extension(to_format);
429 string const command =
431 quoteName(libFileSearch("scripts", "convertDefault.py").toFilesystemEncoding()) +
432 ' ' + from_ext + ' ' +
433 quoteName(from_file.toFilesystemEncoding()) +
435 quoteName(to_file.toFilesystemEncoding());
436 LYXERR(Debug::FILES, "No converter defined! "
437 "I use convertDefault.py:\n\t" << command);
439 Systemcall::Starttype starttype =
440 (buffer && buffer->isClone()) ?
441 Systemcall::WaitLoop : Systemcall::Wait;
442 int const exitval = one.startscript(starttype, command,
443 buffer ? buffer->filePath() : string(),
444 buffer ? buffer->layoutPos() : string());
445 if (exitval == Systemcall::KILLED) {
446 frontend::Alert::warning(
447 _("Converter killed"),
448 bformat(_("The following converter was killed by the user.\n %1$s\n"),
449 from_utf8(command)));
452 if (to_file.isReadableFile()) {
453 if (conversionflags & try_cache)
454 ConverterCache::get().add(orig_from,
460 // only warn once per session and per file type
461 static std::map<string, string> warned;
462 if (warned.find(from_format) != warned.end() && warned.find(from_format)->second == to_format) {
465 warned.insert(make_pair(from_format, to_format));
467 Alert::error(_("Cannot convert file"),
468 bformat(_("No information for converting %1$s "
469 "format files to %2$s.\n"
470 "Define a converter in the preferences."),
471 from_ascii(from_format), from_ascii(to_format)));
475 // buffer is only invalid for importing, and then runparams is not
477 OutputParams runparams(buffer ? &buffer->params().encoding() : nullptr);
478 runparams.flavor = getFlavor(edgepath, buffer);
481 BufferParams const & bp = buffer->params();
482 runparams.use_japanese =
483 (bp.bufferFormat() == "latex"
484 || suffixIs(bp.bufferFormat(), "-ja"))
485 && bp.encoding().package() == Encoding::japanese;
486 runparams.use_indices = bp.use_indices;
487 runparams.bibtex_command = bp.bibtexCommand(true);
488 runparams.index_command = (bp.index_command == "default") ?
489 string() : bp.index_command;
490 runparams.document_language = bp.language->lang();
491 // Some macros rely on font encoding
492 runparams.main_fontenc = bp.main_font_encoding();
493 runparams.only_childbibs = !bp.useBiblatex()
495 && bp.multibib == "child";
496 runparams.includeall = includeall;
499 // Some converters (e.g. lilypond) can only output files to the
500 // current directory, so we need to change the current directory.
501 // This has the added benefit that all other files that may be
502 // generated by the converter are deleted when LyX closes and do not
503 // clutter the real working directory.
504 // FIXME: This does not work if path is an UNC path on windows
506 string const path(onlyPath(from_file.absFileName()));
507 // Prevent the compiler from optimizing away p
511 // empty the error list before any new conversion takes place.
514 bool run_latex = false;
515 string from_base = changeExtension(from_file.absFileName(), "");
516 string to_base = changeExtension(to_file.absFileName(), "");
518 FileName outfile = from_file;
519 for (auto const & edge : edgepath) {
520 Converter const & conv = converterlist_[edge];
521 bool dummy = conv.To()->dummy() && conv.to() != "program";
523 LYXERR(Debug::FILES, "Converting from "
524 << conv.from() << " to " << conv.to());
527 outfile = FileName(conv.result_file().empty()
528 ? changeExtension(from_file.absFileName(), conv.To()->extension())
529 : addName(subst(conv.result_dir(),
530 token_base, from_base),
531 subst(conv.result_file(),
532 token_base, onlyFileName(from_base))));
534 // if input and output files are equal, we use a
535 // temporary file as intermediary (JMarc)
536 FileName real_outfile;
537 if (!conv.result_file().empty())
538 real_outfile = FileName(changeExtension(from_file.absFileName(),
539 conv.To()->extension()));
540 if (outfile == infile) {
541 real_outfile = infile;
542 // when importing, a buffer does not necessarily exist
544 outfile = FileName(addName(buffer->temppath(), "tmpfile.out"));
546 outfile = FileName(addName(package().temp_dir().absFileName(),
550 if (buffer && buffer->params().use_minted
551 && lyxrc.pygmentize_command.empty() && conv.latex()) {
553 // Warn only if listings insets are actually used
554 for (Paragraph const & par : buffer->paragraphs()) {
555 InsetList const & insets = par.insetList();
556 pos_type lstpos = insets.find(LISTINGS_CODE, 0);
557 pos_type incpos = insets.find(INCLUDE_CODE, 0);
559 InsetInclude const * include =
560 static_cast<InsetInclude *>
561 (insets.get(incpos));
562 if (include->params().getCmdName() !=
567 if (lstpos >= 0 || incpos >= 0) {
573 Alert::warning(_("Pygments driver command not found!"),
574 _("The driver command necessary to use the minted package\n"
575 "(pygmentize) has not been found. Make sure you have\n"
576 "the python-pygments module installed or, if the driver\n"
577 "is named differently, to add the following line to the\n"
578 "document preamble:\n\n"
579 "\\AtBeginDocument{\\renewcommand{\\MintedPygmentize}{driver}}\n\n"
580 "where 'driver' is name of the driver command."));
584 if (!checkAuth(conv, buffer ? buffer->absFileName() : string(),
585 buffer && buffer->params().shell_escape))
589 // We are not importing, we have a buffer
590 LASSERT(buffer, return FAILURE);
592 string command = conv.command();
593 command = subst(command, token_from, "");
594 command = subst(command, token_latex_encoding,
595 buffer->params().encoding().latexName());
596 if (buffer->params().shell_escape
597 && !contains(command, "-shell-escape"))
598 command += " -shell-escape ";
599 LYXERR(Debug::FILES, "Running " << command);
601 // Check changed return value here.
602 RetVal const retval = runLaTeX(*buffer, command, runparams, errorList);
603 if (retval != SUCCESS)
606 if (conv.need_aux() && !run_latex) {
607 // We are not importing, we have a buffer
608 LASSERT(buffer, return FAILURE);
610 switch (runparams.flavor) {
611 case Flavor::DviLuaTeX:
612 command = dvilualatex_command_;
615 command = lualatex_command_;
617 case Flavor::PdfLaTeX:
618 command = pdflatex_command_;
621 command = xelatex_command_;
624 command = latex_command_;
627 if (!command.empty()) {
628 LYXERR(Debug::FILES, "Running "
630 << " to update aux file");
632 // Check changed return value here.
633 RetVal const retval = runLaTeX(*buffer, command, runparams, errorList);
634 if (retval != SUCCESS)
640 string const infile2 =
641 to_utf8(makeRelPath(from_utf8(infile.absFileName()), from_utf8(path)));
642 string const outfile2 =
643 to_utf8(makeRelPath(from_utf8(outfile.absFileName()), from_utf8(path)));
645 string command = conv.command();
646 command = subst(command, token_from, quoteName(infile2));
647 command = subst(command, token_base, quoteName(from_base));
648 command = subst(command, token_to, quoteName(outfile2));
649 command = subst(command, token_path, quoteName(onlyPath(infile.absFileName())));
650 command = subst(command, token_orig_path, quoteName(onlyPath(orig_from.absFileName())));
651 command = subst(command, token_orig_from, quoteName(onlyFileName(orig_from.absFileName())));
652 command = subst(command, token_encoding, buffer ? buffer->params().encoding().iconvName() : string());
653 command = subst(command, token_python, os::python());
655 if (!conv.parselog().empty())
656 command += " 2> " + quoteName(infile2 + ".out");
658 // it is not actually not necessary to test for buffer here,
659 // but it pleases coverity.
660 if (buffer && conv.from() == "dvi" && conv.to() == "ps")
661 command = add_options(command,
662 buffer->params().dvips_options());
663 else if (buffer && conv.from() == "dvi" && prefixIs(conv.to(), "pdf"))
664 command = add_options(command,
665 dvipdfm_options(buffer->params()));
667 LYXERR(Debug::FILES, "Calling " << command);
669 buffer->message(_("Executing command: ")
670 + from_utf8(command));
675 res = one.startscript(Systemcall::DontWait,
676 to_filesystem8bit(from_utf8(command)),
677 buffer ? buffer->filePath() : string(),
678 buffer ? buffer->layoutPos() : string());
679 // We're not waiting for the result, so we can't do anything
682 Systemcall::Starttype starttype =
683 (buffer && buffer->isClone()) ?
684 Systemcall::WaitLoop : Systemcall::Wait;
685 res = one.startscript(starttype,
686 to_filesystem8bit(from_utf8(command)),
687 buffer ? buffer->filePath()
689 buffer ? buffer->layoutPos()
691 if (res == Systemcall::KILLED) {
692 frontend::Alert::warning(
693 _("Converter killed"),
694 bformat(_("The following converter was killed by the user.\n %1$s\n"),
695 from_utf8(command)));
699 if (!real_outfile.empty()) {
700 Mover const & mover = getMover(conv.to());
701 if (!mover.rename(outfile, real_outfile))
704 LYXERR(Debug::FILES, "renaming file " << outfile
705 << " to " << real_outfile);
706 // Finally, don't forget to tell any future
707 // converters to use the renamed file...
708 outfile = real_outfile;
711 if (!conv.parselog().empty()) {
712 string const logfile = infile2 + ".log";
713 string const command2 = conv.parselog() +
714 " < " + quoteName(infile2 + ".out") +
715 " > " + quoteName(logfile);
716 res = one.startscript(starttype,
717 to_filesystem8bit(from_utf8(command2)),
718 buffer ? buffer->filePath() : string(),
719 buffer ? buffer->layoutPos() : string());
720 if (res == Systemcall::KILLED) {
721 frontend::Alert::warning(
722 _("Converter killed"),
723 bformat(_("The following converter was killed by the user.\n %1$s\n"),
724 from_utf8(command)));
727 if (buffer && !scanLog(*buffer, command, makeAbsPath(logfile, path), errorList))
733 if (res == Systemcall::KILLED) {
734 Alert::information(_("Process Killed"),
735 bformat(_("The conversion process was killed while running:\n%1$s"),
736 wrapParas(from_utf8(command))));
739 if (res == Systemcall::TIMEOUT) {
740 Alert::information(_("Process Timed Out"),
741 bformat(_("The conversion process:\n%1$s\ntimed out before completing."),
742 wrapParas(from_utf8(command))));
745 if (conv.to() == "program") {
746 Alert::error(_("Build errors"),
747 _("There were errors during the build process."));
749 // FIXME: this should go out of here. For example, here we cannot say if
750 // it is a document (.lyx) or something else. Same goes for elsewhere.
751 Alert::error(_("Cannot convert file"),
752 bformat(_("An error occurred while running:\n%1$s"),
753 wrapParas(from_utf8(command))));
760 Converter const & conv = converterlist_[edgepath.back()];
761 if (conv.To()->dummy())
764 if (!conv.result_dir().empty()) {
765 // The converter has put the file(s) in a directory.
766 // In this case we ignore the given to_file.
767 if (from_base != to_base) {
768 string const from = subst(conv.result_dir(),
769 token_base, from_base);
770 string const to = subst(conv.result_dir(),
771 token_base, to_base);
772 Mover const & mover = getMover(conv.from());
773 if (!mover.rename(FileName(from), FileName(to))) {
774 Alert::error(_("Cannot convert file"),
775 bformat(_("Could not move a temporary directory from %1$s to %2$s."),
776 from_utf8(from), from_utf8(to)));
782 if (conversionflags & try_cache)
783 ConverterCache::get().add(orig_from, to_format, outfile);
784 return move(conv.to(), outfile, to_file, conv.latex()) ? SUCCESS : FAILURE;
789 bool Converters::move(string const & fmt,
790 FileName const & from, FileName const & to, bool copy)
795 bool no_errors = true;
796 string const path = onlyPath(from.absFileName());
797 string const base = onlyFileName(removeExtension(from.absFileName()));
798 string const to_base = removeExtension(to.absFileName());
799 string const to_extension = getExtension(to.absFileName());
801 support::FileNameList const files = FileName(path).dirList(getExtension(from.absFileName()));
802 for (auto const & f : files) {
803 string const from2 = f.absFileName();
804 string const file2 = onlyFileName(from2);
805 if (prefixIs(file2, base)) {
806 string const to2 = changeExtension(
807 to_base + file2.substr(base.length()),
809 LYXERR(Debug::FILES, "moving " << from2 << " to " << to2);
811 Mover const & mover = getMover(fmt);
812 bool const moved = copy
813 ? mover.copy(f, FileName(to2))
814 : mover.rename(f, FileName(to2));
815 if (!moved && no_errors) {
816 Alert::error(_("Cannot convert file"),
818 _("Could not copy a temporary file from %1$s to %2$s.") :
819 _("Could not move a temporary file from %1$s to %2$s."),
820 from_utf8(from2), from_utf8(to2)));
829 bool Converters::formatIsUsed(string const & format) const
831 for (auto const & cvt : converterlist_) {
832 if (cvt.from() == format || cvt.to() == format)
839 bool Converters::scanLog(Buffer const & buffer, string const & /*command*/,
840 FileName const & filename, ErrorList & errorList)
842 OutputParams runparams(nullptr);
843 runparams.flavor = Flavor::LaTeX;
844 LaTeX latex("", runparams, filename);
846 int const result = latex.scanLogFile(terr);
848 if (result & LaTeX::ERRORS)
849 buffer.bufferErrors(terr, errorList);
855 Converters::RetVal Converters::runLaTeX(Buffer const & buffer, string const & command,
856 OutputParams const & runparams, ErrorList & errorList)
858 buffer.setBusy(true);
859 buffer.message(_("Running LaTeX..."));
861 // do the LaTeX run(s)
862 string const name = buffer.latexName();
863 LaTeX latex(command, runparams, makeAbsPath(name),
864 buffer.filePath(), buffer.layoutPos(),
865 buffer.isClone(), buffer.freshStartRequired());
867 // The connection closes itself at the end of the scope when latex is
868 // destroyed. One cannot close (and destroy) buffer while the converter is
870 latex.message.connect([&buffer](docstring const & msg){
873 int const result = latex.run(terr);
875 if (result == Systemcall::KILLED || result == Systemcall::TIMEOUT) {
876 Alert::error(_("Export canceled"),
877 _("The export process was terminated by the user."));
881 if (result & LaTeX::ERRORS)
882 buffer.bufferErrors(terr, errorList);
884 if ((result & LaTeX::UNDEF_CIT) || (result & LaTeX::UNDEF_UNKNOWN_REF)) {
885 buffer.bufferRefs(terr, errorList);
886 if (errorList.empty())
887 errorList.push_back(ErrorItem(_("Undefined reference"),
888 _("Undefined references or citations were found during the build.\n"
889 "Please check the warnings in the LaTeX log (Document > LaTeX Log)."),
893 if (!errorList.empty()) {
894 // We will show the LaTeX Errors GUI later which contains
895 // specific error messages so it would be repetitive to give
896 // e.g. the "finished with an error" dialog in addition.
898 else if (result & LaTeX::NO_LOGFILE) {
899 docstring const str =
900 bformat(_("LaTeX did not run successfully. "
901 "Additionally, LyX could not locate "
902 "the LaTeX log %1$s."), from_utf8(name));
903 Alert::error(_("LaTeX failed"), str);
904 } else if (result & LaTeX::NONZERO_ERROR) {
905 docstring const str =
906 bformat(_( "The external program\n%1$s\n"
907 "finished with an error. "
908 "It is recommended you fix the cause of the external "
909 "program's error (check the logs). "), from_utf8(command));
910 Alert::error(_("LaTeX failed"), str);
911 } else if (result & LaTeX::NO_OUTPUT) {
912 Alert::warning(_("Output is empty"),
913 _("No output file was generated."));
916 buffer.setBusy(false);
918 int const ERROR_MASK =
922 LaTeX::UNDEF_UNKNOWN_REF |
925 return (result & ERROR_MASK) == 0 ? SUCCESS : FAILURE;
930 void Converters::buildGraph()
932 // clear graph's data structures
933 G_.init(theFormats().size());
934 // each of the converters knows how to convert one format to another
935 // so, for each of them, we create an arrow on the graph, going from
936 // the one to the other
937 for (auto const & cvt : converterlist_) {
938 int const from = theFormats().getNumber(cvt.from());
939 int const to = theFormats().getNumber(cvt.to());
940 LASSERT(from >= 0, continue);
941 LASSERT(to >= 0, continue);
942 G_.addEdge(from, to);
947 FormatList const Converters::intToFormat(vector<int> const & input)
949 FormatList result(input.size());
951 vector<int>::const_iterator it = input.begin();
952 vector<int>::const_iterator const end = input.end();
953 FormatList::iterator rit = result.begin();
954 for ( ; it != end; ++it, ++rit) {
955 *rit = &theFormats().get(*it);
961 FormatList const Converters::getReachableTo(string const & target,
962 bool const clear_visited)
964 vector<int> const & reachablesto =
965 G_.getReachableTo(theFormats().getNumber(target), clear_visited);
967 return intToFormat(reachablesto);
971 FormatList const Converters::getReachable(string const & from,
972 bool const only_viewable, bool const clear_visited,
973 set<string> const & excludes)
975 set<int> excluded_numbers;
977 for (auto const & ex : excludes)
978 excluded_numbers.insert(theFormats().getNumber(ex));
980 vector<int> const & reachables =
981 G_.getReachable(theFormats().getNumber(from),
986 return intToFormat(reachables);
990 bool Converters::isReachable(string const & from, string const & to)
992 return G_.isReachable(theFormats().getNumber(from),
993 theFormats().getNumber(to));
997 Graph::EdgePath Converters::getPath(string const & from, string const & to)
999 return G_.getPath(theFormats().getNumber(from),
1000 theFormats().getNumber(to));
1004 FormatList Converters::importableFormats()
1006 vector<string> l = loaders();
1007 FormatList result = getReachableTo(l[0], true);
1008 vector<string>::const_iterator it = l.begin() + 1;
1009 vector<string>::const_iterator en = l.end();
1010 for (; it != en; ++it) {
1011 FormatList r = getReachableTo(*it, false);
1012 result.insert(result.end(), r.begin(), r.end());
1018 FormatList Converters::exportableFormats(bool only_viewable)
1020 vector<string> s = savers();
1021 FormatList result = getReachable(s[0], only_viewable, true);
1022 vector<string>::const_iterator it = s.begin() + 1;
1023 vector<string>::const_iterator en = s.end();
1024 for (; it != en; ++it) {
1025 FormatList r = getReachable(*it, only_viewable, false);
1026 result.insert(result.end(), r.begin(), r.end());
1032 vector<string> Converters::loaders() const
1036 v.push_back("text");
1037 v.push_back("textparagraph");
1042 vector<string> Converters::savers() const
1045 v.push_back("docbook");
1046 v.push_back("latex");
1047 v.push_back("literate");
1048 v.push_back("luatex");
1049 v.push_back("dviluatex");
1051 v.push_back("xhtml");
1052 v.push_back("pdflatex");
1053 v.push_back("platex");
1054 v.push_back("text");
1055 v.push_back("xetex");