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 "buffer_funcs.h"
17 #include "BufferParams.h"
18 #include "ConverterCache.h"
20 #include "ErrorList.h"
22 #include "InsetList.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");
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), xml_(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 Converter const * Converters::getConverter(string const & from,
152 string const & to) const
154 ConverterList::const_iterator const cit =
155 find_if(converterlist_.begin(), converterlist_.end(),
156 ConverterEqual(from, to));
157 if (cit != converterlist_.end())
164 int Converters::getNumber(string const & from, string const & to) const
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);
176 void Converters::add(string const & from, string const & to,
177 string const & command, string const & flags)
179 theFormats().add(from);
180 theFormats().add(to);
181 ConverterList::iterator it = find_if(converterlist_.begin(),
182 converterlist_.end(),
183 ConverterEqual(from , to));
185 Converter converter(from, to, command, flags);
186 if (it != converterlist_.end() && !flags.empty() && flags[0] == '*') {
188 converter.setCommand(command);
189 converter.setFlags(flags);
191 converter.readFlags();
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, "");
213 if (it == converterlist_.end()) {
214 converterlist_.push_back(converter);
216 converter.setFrom(it->From());
217 converter.setTo(it->To());
223 void Converters::erase(string const & from, string const & to)
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);
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)
243 for (auto & cv : converterlist_) {
244 cv.setFrom(formats.getFormat(cv.from()));
245 cv.setTo(formats.getFormat(cv.to()));
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)
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()));
262 OutputParams::FLAVOR Converters::getFlavor(Graph::EdgePath const & path,
263 Buffer const * buffer)
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;
280 return OutputParams::XML;
282 return buffer ? buffer->params().getOutputFlavor()
283 : OutputParams::LATEX;
287 string Converters::getHyperrefDriver(Graph::EdgePath const & path)
289 for (auto const & edge : path) {
290 Converter const & conv = converterlist_[edge];
291 if (!conv.hyperref_driver().empty())
292 return conv.hyperref_driver();
298 bool Converters::checkAuth(Converter const & conv, string const & doc_fname,
299 bool use_shell_escape)
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)
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"))
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>"),
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 ▹ File "
349 "Handling ▹ Converters</i> and uncheck <i>Security ▹ "
350 "Forbid needauth converters</i>.)"), false);
353 if (!lyxrc.use_converter_needauth && !use_shell_escape)
355 docstring const security_title = use_shell_escape
356 ? _("A LaTeX backend requires your authorization")
357 : _("An external converter requires your authorization");
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 ¬ allow") : _("Do ¬ 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);
378 choice = frontend::Alert::prompt(security_title,
380 0, 0, no, yes, always);
382 if (use_shell_escape)
383 theSession().shellescapeFiles().insert(doc_fname, true);
385 theSession().authFiles().insert(doc_fname);
391 choice = frontend::Alert::prompt(security_title,
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)
405 if (from_format == to_format)
406 return move(from_format, from_file, to_file, false) ?
409 if ((conversionflags & try_cache) &&
410 ConverterCache::get().inCache(orig_from, to_format))
411 return ConverterCache::get().copy(orig_from, to_format, to_file) ?
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 =
425 quoteName(libFileSearch("scripts", "convertDefault.py").toFilesystemEncoding()) +
426 ' ' + from_ext + ' ' +
427 quoteName(from_file.toFilesystemEncoding()) +
429 quoteName(to_file.toFilesystemEncoding());
430 LYXERR(Debug::FILES, "No converter defined! "
431 "I use convertDefault.py:\n\t" << command);
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)));
446 if (to_file.isReadableFile()) {
447 if (conversionflags & try_cache)
448 ConverterCache::get().add(orig_from,
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) {
459 warned.insert(make_pair(from_format, to_format));
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)));
469 // buffer is only invalid for importing, and then runparams is not
471 OutputParams runparams(buffer ? &buffer->params().encoding() : nullptr);
472 runparams.flavor = getFlavor(edgepath, 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()
490 && bp.multibib == "child";
491 runparams.includeall = includeall;
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
501 string const path(onlyPath(from_file.absFileName()));
502 // Prevent the compiler from optimizing away p
506 // empty the error list before any new conversion takes place.
509 bool run_latex = false;
510 string from_base = changeExtension(from_file.absFileName(), "");
511 string to_base = changeExtension(to_file.absFileName(), "");
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";
518 LYXERR(Debug::FILES, "Converting from "
519 << conv.from() << " to " << conv.to());
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))));
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
539 outfile = FileName(addName(buffer->temppath(), "tmpfile.out"));
541 outfile = FileName(addName(package().temp_dir().absFileName(),
545 if (buffer && buffer->params().use_minted
546 && lyxrc.pygmentize_command.empty() && conv.latex()) {
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);
554 InsetInclude const * include =
555 static_cast<InsetInclude *>
556 (insets.get(incpos));
557 if (include->params().getCmdName() !=
562 if (lstpos >= 0 || incpos >= 0) {
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."));
579 if (!checkAuth(conv, buffer ? buffer->absFileName() : string(),
580 buffer && buffer->params().shell_escape))
584 // We are not importing, we have a buffer
585 LASSERT(buffer, return FAILURE);
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);
596 // Check changed return value here.
597 RetVal const retval = runLaTeX(*buffer, command, runparams, errorList);
598 if (retval != SUCCESS)
601 if (conv.need_aux() && !run_latex) {
602 // We are not importing, we have a buffer
603 LASSERT(buffer, return FAILURE);
605 switch (runparams.flavor) {
606 case OutputParams::DVILUATEX:
607 command = dvilualatex_command_;
609 case OutputParams::LUATEX:
610 command = lualatex_command_;
612 case OutputParams::PDFLATEX:
613 command = pdflatex_command_;
615 case OutputParams::XETEX:
616 command = xelatex_command_;
619 command = latex_command_;
622 if (!command.empty()) {
623 LYXERR(Debug::FILES, "Running "
625 << " to update aux file");
627 // Check changed return value here.
628 RetVal const retval = runLaTeX(*buffer, command, runparams, errorList);
629 if (retval != SUCCESS)
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)));
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());
649 if (!conv.parselog().empty())
650 command += " 2> " + quoteName(infile2 + ".out");
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()));
661 LYXERR(Debug::FILES, "Calling " << command);
663 buffer->message(_("Executing command: ")
664 + from_utf8(command));
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
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()
683 buffer ? buffer->layoutPos()
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)));
693 if (!real_outfile.empty()) {
694 Mover const & mover = getMover(conv.to());
695 if (!mover.rename(outfile, real_outfile))
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;
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)));
721 if (buffer && !scanLog(*buffer, command, makeAbsPath(logfile, path), errorList))
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))));
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))));
739 if (conv.to() == "program") {
740 Alert::error(_("Build errors"),
741 _("There were errors during the build process."));
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))));
754 Converter const & conv = converterlist_[edgepath.back()];
755 if (conv.To()->dummy())
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)));
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;
783 bool Converters::move(string const & fmt,
784 FileName const & from, FileName const & to, bool copy)
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());
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()),
803 LYXERR(Debug::FILES, "moving " << from2 << " to " << to2);
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"),
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)));
823 bool Converters::formatIsUsed(string const & format)
825 for (auto const & cvt : converterlist_) {
826 if (cvt.from() == format || cvt.to() == format)
833 bool Converters::scanLog(Buffer const & buffer, string const & /*command*/,
834 FileName const & filename, ErrorList & errorList)
836 OutputParams runparams(nullptr);
837 runparams.flavor = OutputParams::LATEX;
838 LaTeX latex("", runparams, filename);
840 int const result = latex.scanLogFile(terr);
842 if (result & LaTeX::ERRORS)
843 buffer.bufferErrors(terr, errorList);
849 Converters::RetVal Converters::runLaTeX(Buffer const & buffer, string const & command,
850 OutputParams const & runparams, ErrorList & errorList)
852 buffer.setBusy(true);
853 buffer.message(_("Running LaTeX..."));
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());
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
864 latex.message.connect([&buffer](docstring const & msg){
867 int const result = latex.run(terr);
869 if (result == Systemcall::KILLED) {
870 Alert::error(_("Export canceled"),
871 _("The export process was terminated by the user."));
875 if (result & LaTeX::ERRORS)
876 buffer.bufferErrors(terr, errorList);
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)."),
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.
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."));
910 buffer.setBusy(false);
912 int const ERROR_MASK =
916 LaTeX::UNDEF_UNKNOWN_REF |
919 return (result & ERROR_MASK) == 0 ? SUCCESS : FAILURE;
924 void Converters::buildGraph()
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);
941 FormatList const Converters::intToFormat(vector<int> const & input)
943 FormatList result(input.size());
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);
955 FormatList const Converters::getReachableTo(string const & target,
956 bool const clear_visited)
958 vector<int> const & reachablesto =
959 G_.getReachableTo(theFormats().getNumber(target), clear_visited);
961 return intToFormat(reachablesto);
965 FormatList const Converters::getReachable(string const & from,
966 bool const only_viewable, bool const clear_visited,
967 set<string> const & excludes)
969 set<int> excluded_numbers;
971 for (auto const & ex : excludes)
972 excluded_numbers.insert(theFormats().getNumber(ex));
974 vector<int> const & reachables =
975 G_.getReachable(theFormats().getNumber(from),
980 return intToFormat(reachables);
984 bool Converters::isReachable(string const & from, string const & to)
986 return G_.isReachable(theFormats().getNumber(from),
987 theFormats().getNumber(to));
991 Graph::EdgePath Converters::getPath(string const & from, string const & to)
993 return G_.getPath(theFormats().getNumber(from),
994 theFormats().getNumber(to));
998 FormatList Converters::importableFormats()
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());
1012 FormatList Converters::exportableFormats(bool only_viewable)
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());
1026 vector<string> Converters::loaders() const
1030 v.push_back("text");
1031 v.push_back("textparagraph");
1036 vector<string> Converters::savers() const
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");
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");