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 "ParagraphList.h"
29 #include "frontends/alert.h"
31 #include "insets/InsetInclude.h"
33 #include "support/debug.h"
34 #include "support/FileNameList.h"
35 #include "support/filetools.h"
36 #include "support/gettext.h"
37 #include "support/lassert.h"
38 #include "support/lstrings.h"
39 #include "support/os.h"
40 #include "support/Package.h"
41 #include "support/PathChanger.h"
42 #include "support/Systemcall.h"
45 using namespace lyx::support;
49 namespace Alert = lyx::frontend::Alert;
54 string const token_from("$$i");
55 string const token_base("$$b");
56 string const token_to("$$o");
57 string const token_path("$$p");
58 string const token_orig_path("$$r");
59 string const token_orig_from("$$f");
60 string const token_encoding("$$e");
61 string const token_latex_encoding("$$E");
64 string const add_options(string const & command, string const & options)
67 string const tail = split(command, head, ' ');
68 return head + ' ' + options + ' ' + tail;
72 string const dvipdfm_options(BufferParams const & bp)
76 if (bp.papersize != PAPER_CUSTOM) {
77 string const paper_size = bp.paperSizeName(BufferParams::DVIPDFM);
78 if (!paper_size.empty())
79 result = "-p "+ paper_size;
81 if (bp.orientation == ORIENTATION_LANDSCAPE)
89 class ConverterEqual {
91 ConverterEqual(string const & from, string const & to)
92 : from_(from), to_(to) {}
93 bool operator()(Converter const & c) const {
94 return c.from() == from_ && c.to() == to_;
104 Converter::Converter(string const & f, string const & t,
105 string const & c, string const & l)
106 : from_(f), to_(t), command_(c), flags_(l),
107 From_(nullptr), To_(nullptr), latex_(false), docbook_(false),
108 need_aux_(false), nice_(false), need_auth_(false)
112 void Converter::readFlags()
114 string flag_list(flags_);
115 while (!flag_list.empty()) {
116 string flag_name, flag_value;
117 flag_list = split(flag_list, flag_value, ',');
118 flag_value = split(flag_value, flag_name, '=');
119 if (flag_name == "latex") {
121 latex_flavor_ = flag_value.empty() ?
122 "latex" : flag_value;
123 } else if (flag_name == "xml")
125 else if (flag_name == "needaux") {
127 latex_flavor_ = flag_value.empty() ?
128 "latex" : flag_value;
129 } else if (flag_name == "resultdir")
130 result_dir_ = (flag_value.empty())
131 ? token_base : flag_value;
132 else if (flag_name == "resultfile")
133 result_file_ = flag_value;
134 else if (flag_name == "parselog")
135 parselog_ = flag_value;
136 else if (flag_name == "nice")
138 else if (flag_name == "needauth")
140 else if (flag_name == "hyperref-driver")
141 href_driver_ = flag_value;
143 if (!result_dir_.empty() && result_file_.empty())
144 result_file_ = "index." + theFormats().extension(to_);
145 //if (!contains(command, token_from))
150 Converter const * Converters::getConverter(string const & from,
151 string const & to) const
153 ConverterList::const_iterator const cit =
154 find_if(converterlist_.begin(), converterlist_.end(),
155 ConverterEqual(from, to));
156 if (cit != converterlist_.end())
163 int Converters::getNumber(string const & from, string const & to) const
165 ConverterList::const_iterator const cit =
166 find_if(converterlist_.begin(), converterlist_.end(),
167 ConverterEqual(from, to));
168 if (cit != converterlist_.end())
169 return distance(converterlist_.begin(), cit);
175 void Converters::add(string const & from, string const & to,
176 string const & command, string const & flags)
178 theFormats().add(from);
179 theFormats().add(to);
180 ConverterList::iterator it = find_if(converterlist_.begin(),
181 converterlist_.end(),
182 ConverterEqual(from , to));
184 Converter converter(from, to, command, flags);
185 if (it != converterlist_.end() && !flags.empty() && flags[0] == '*') {
187 converter.setCommand(command);
188 converter.setFlags(flags);
190 converter.readFlags();
192 // The latex_command is used to update the .aux file when running
193 // a converter that uses it.
194 if (converter.latex()) {
195 if (latex_command_.empty() ||
196 converter.latex_flavor() == "latex")
197 latex_command_ = subst(command, token_from, "");
198 if (dvilualatex_command_.empty() ||
199 converter.latex_flavor() == "dvilualatex")
200 dvilualatex_command_ = subst(command, token_from, "");
201 if (lualatex_command_.empty() ||
202 converter.latex_flavor() == "lualatex")
203 lualatex_command_ = subst(command, token_from, "");
204 if (pdflatex_command_.empty() ||
205 converter.latex_flavor() == "pdflatex")
206 pdflatex_command_ = subst(command, token_from, "");
207 if (xelatex_command_.empty() ||
208 converter.latex_flavor() == "xelatex")
209 xelatex_command_ = subst(command, token_from, "");
212 if (it == converterlist_.end()) {
213 converterlist_.push_back(converter);
215 converter.setFrom(it->From());
216 converter.setTo(it->To());
222 void Converters::erase(string const & from, string const & to)
224 ConverterList::iterator const it =
225 find_if(converterlist_.begin(),
226 converterlist_.end(),
227 ConverterEqual(from, to));
228 if (it != converterlist_.end())
229 converterlist_.erase(it);
233 // This method updates the pointers From and To in all the converters.
234 // The code is not very efficient, but it doesn't matter as the number
235 // of formats and converters is small.
236 // Furthermore, this method is called only on startup, or after
237 // adding/deleting a format in FormPreferences (the latter calls can be
238 // eliminated if the formats in the Formats class are stored using a map or
239 // a list (instead of a vector), but this will cause other problems).
240 void Converters::update(Formats const & formats)
242 for (auto & cv : converterlist_) {
243 cv.setFrom(formats.getFormat(cv.from()));
244 cv.setTo(formats.getFormat(cv.to()));
249 // This method updates the pointers From and To in the last converter.
250 // It is called when adding a new converter in FormPreferences
251 void Converters::updateLast(Formats const & formats)
253 if (converterlist_.begin() != converterlist_.end()) {
254 ConverterList::iterator it = converterlist_.end() - 1;
255 it->setFrom(formats.getFormat(it->from()));
256 it->setTo(formats.getFormat(it->to()));
261 OutputParams::FLAVOR Converters::getFlavor(Graph::EdgePath const & path,
262 Buffer const * buffer) const
264 for (auto const & edge : path) {
265 Converter const & conv = converterlist_[edge];
266 if (conv.latex() || conv.need_aux()) {
267 if (conv.latex_flavor() == "latex")
268 return OutputParams::LATEX;
269 if (conv.latex_flavor() == "xelatex")
270 return OutputParams::XETEX;
271 if (conv.latex_flavor() == "lualatex")
272 return OutputParams::LUATEX;
273 if (conv.latex_flavor() == "dvilualatex")
274 return OutputParams::DVILUATEX;
275 if (conv.latex_flavor() == "pdflatex")
276 return OutputParams::PDFLATEX;
279 return OutputParams::DOCBOOK5;
281 return buffer ? buffer->params().getOutputFlavor()
282 : OutputParams::LATEX;
286 string Converters::getHyperrefDriver(Graph::EdgePath const & path) const
288 for (auto const & edge : path) {
289 Converter const & conv = converterlist_[edge];
290 if (!conv.hyperref_driver().empty())
291 return conv.hyperref_driver();
297 bool Converters::checkAuth(Converter const & conv, string const & doc_fname,
298 bool use_shell_escape)
300 string conv_command = conv.command();
301 bool const has_shell_escape = contains(conv_command, "-shell-escape")
302 || contains(conv_command, "-enable-write18");
303 if (conv.latex() && has_shell_escape && !use_shell_escape) {
304 docstring const shellescape_warning =
305 bformat(_("<p>The following LaTeX backend has been "
306 "configured to allow execution of external programs "
307 "for any document:</p>"
308 "<center><p><tt>%1$s</tt></p></center>"
309 "<p>This is a dangerous configuration. Please, "
310 "consider using the support offered by LyX for "
311 "allowing this privilege only to documents that "
312 "actually need it, instead.</p>"),
313 from_utf8(conv_command));
314 frontend::Alert::error(_("Security Warning"),
315 shellescape_warning , false);
316 } else if (!conv.latex())
317 use_shell_escape = false;
318 if (!conv.need_auth() && !use_shell_escape)
320 size_t const token_pos = conv_command.find("$$");
321 bool const has_token = token_pos != string::npos;
322 string const command = use_shell_escape && !has_shell_escape
323 ? (has_token ? conv_command.insert(token_pos, "-shell-escape ")
324 : conv_command.append(" -shell-escape"))
326 docstring const security_warning = (use_shell_escape
327 ? bformat(_("<p>The following LaTeX backend has been requested "
328 "to allow execution of external programs:</p>"
329 "<center><p><tt>%1$s</tt></p></center>"
330 "<p>The external programs can execute arbitrary commands on "
331 "your system, including dangerous ones, if instructed to do "
332 "so by a maliciously crafted LyX document.</p>"),
334 : bformat(_("<p>The requested operation requires the use of a "
335 "converter from %2$s to %3$s:</p>"
336 "<blockquote><p><tt>%1$s</tt></p></blockquote>"
337 "<p>This external program can execute arbitrary commands on "
338 "your system, including dangerous ones, if instructed to do "
339 "so by a maliciously crafted LyX document.</p>"),
340 from_utf8(command), from_utf8(conv.from()),
341 from_utf8(conv.to())));
342 if (lyxrc.use_converter_needauth_forbidden && !use_shell_escape) {
343 frontend::Alert::error(
344 _("An external converter is disabled for security reasons"),
345 security_warning + _(
346 "<p><b>Your current preference settings forbid its execution.</b></p>"
347 "<p>(To change this setting, go to <i>Preferences ▹ File "
348 "Handling ▹ Converters</i> and uncheck <i>Security ▹ "
349 "Forbid needauth converters</i>.)"), false);
352 if (!lyxrc.use_converter_needauth && !use_shell_escape)
354 docstring const security_title = use_shell_escape
355 ? _("A LaTeX backend requires your authorization")
356 : _("An external converter requires your authorization");
358 docstring const security_warning2 = security_warning + (use_shell_escape
359 ? _("<p>Should LaTeX backends be allowed to run external "
360 "programs?</p><p><b>Allow them only if you trust the "
361 "origin/sender of the LyX document!</b></p>")
362 : _("<p>Would you like to run this converter?</p>"
363 "<p><b>Only run if you trust the origin/sender of the LyX "
364 "document!</b></p>"));
365 docstring const no = use_shell_escape
366 ? _("Do ¬ allow") : _("Do ¬ run");
367 docstring const yes = use_shell_escape ? _("A&llow") : _("&Run");
368 docstring const always = use_shell_escape
369 ? _("&Always allow for this document")
370 : _("&Always run for this document");
371 if (!doc_fname.empty()) {
372 LYXERR(Debug::FILES, "looking up: " << doc_fname);
373 bool authorized = use_shell_escape
374 ? theSession().shellescapeFiles().findAuth(doc_fname)
375 : theSession().authFiles().find(doc_fname);
377 choice = frontend::Alert::prompt(security_title,
379 0, 0, no, yes, always);
381 if (use_shell_escape)
382 theSession().shellescapeFiles().insert(doc_fname, true);
384 theSession().authFiles().insert(doc_fname);
390 choice = frontend::Alert::prompt(security_title,
398 Converters::RetVal Converters::convert(Buffer const * buffer,
399 FileName const & from_file, FileName const & to_file,
400 FileName const & orig_from,
401 string const & from_format, string const & to_format,
402 ErrorList & errorList, int conversionflags, bool includeall)
404 if (from_format == to_format)
405 return move(from_format, from_file, to_file, false) ?
408 if ((conversionflags & try_cache) &&
409 ConverterCache::get().inCache(orig_from, to_format))
410 return ConverterCache::get().copy(orig_from, to_format, to_file) ?
413 Graph::EdgePath edgepath = getPath(from_format, to_format);
414 if (edgepath.empty()) {
415 if (conversionflags & try_default) {
416 // if no special converter defined, then we take the
417 // default one from ImageMagic.
418 string const from_ext = from_format.empty() ?
419 getExtension(from_file.absFileName()) :
420 theFormats().extension(from_format);
421 string const to_ext = theFormats().extension(to_format);
422 string const command =
424 quoteName(libFileSearch("scripts", "convertDefault.py").toFilesystemEncoding()) +
425 ' ' + from_ext + ' ' +
426 quoteName(from_file.toFilesystemEncoding()) +
428 quoteName(to_file.toFilesystemEncoding());
429 LYXERR(Debug::FILES, "No converter defined! "
430 "I use convertDefault.py:\n\t" << command);
432 Systemcall::Starttype starttype =
433 (buffer && buffer->isClone()) ?
434 Systemcall::WaitLoop : Systemcall::Wait;
435 int const exitval = one.startscript(starttype, command,
436 buffer ? buffer->filePath() : string(),
437 buffer ? buffer->layoutPos() : string());
438 if (exitval == Systemcall::KILLED) {
439 frontend::Alert::warning(
440 _("Converter killed"),
441 bformat(_("The following converter was killed by the user.\n %1$s\n"),
442 from_utf8(command)));
445 if (to_file.isReadableFile()) {
446 if (conversionflags & try_cache)
447 ConverterCache::get().add(orig_from,
453 // only warn once per session and per file type
454 static std::map<string, string> warned;
455 if (warned.find(from_format) != warned.end() && warned.find(from_format)->second == to_format) {
458 warned.insert(make_pair(from_format, to_format));
460 Alert::error(_("Cannot convert file"),
461 bformat(_("No information for converting %1$s "
462 "format files to %2$s.\n"
463 "Define a converter in the preferences."),
464 from_ascii(from_format), from_ascii(to_format)));
468 // buffer is only invalid for importing, and then runparams is not
470 OutputParams runparams(buffer ? &buffer->params().encoding() : nullptr);
471 runparams.flavor = getFlavor(edgepath, buffer);
474 BufferParams const & bp = buffer->params();
475 runparams.use_japanese =
476 (bp.bufferFormat() == "latex"
477 || suffixIs(bp.bufferFormat(), "-ja"))
478 && bp.encoding().package() == Encoding::japanese;
479 runparams.use_indices = bp.use_indices;
480 runparams.bibtex_command = bp.bibtexCommand();
481 runparams.index_command = (bp.index_command == "default") ?
482 string() : bp.index_command;
483 runparams.document_language = bp.language->lang();
484 // Some macros rely on font encoding
485 runparams.main_fontenc = bp.main_font_encoding();
486 runparams.only_childbibs = !bp.useBiblatex()
488 && bp.multibib == "child";
489 runparams.includeall = includeall;
492 // Some converters (e.g. lilypond) can only output files to the
493 // current directory, so we need to change the current directory.
494 // This has the added benefit that all other files that may be
495 // generated by the converter are deleted when LyX closes and do not
496 // clutter the real working directory.
497 // FIXME: This does not work if path is an UNC path on windows
499 string const path(onlyPath(from_file.absFileName()));
500 // Prevent the compiler from optimizing away p
504 // empty the error list before any new conversion takes place.
507 bool run_latex = false;
508 string from_base = changeExtension(from_file.absFileName(), "");
509 string to_base = changeExtension(to_file.absFileName(), "");
511 FileName outfile = from_file;
512 for (auto const & edge : edgepath) {
513 Converter const & conv = converterlist_[edge];
514 bool dummy = conv.To()->dummy() && conv.to() != "program";
516 LYXERR(Debug::FILES, "Converting from "
517 << conv.from() << " to " << conv.to());
520 outfile = FileName(conv.result_file().empty()
521 ? changeExtension(from_file.absFileName(), conv.To()->extension())
522 : addName(subst(conv.result_dir(),
523 token_base, from_base),
524 subst(conv.result_file(),
525 token_base, onlyFileName(from_base))));
527 // if input and output files are equal, we use a
528 // temporary file as intermediary (JMarc)
529 FileName real_outfile;
530 if (!conv.result_file().empty())
531 real_outfile = FileName(changeExtension(from_file.absFileName(),
532 conv.To()->extension()));
533 if (outfile == infile) {
534 real_outfile = infile;
535 // when importing, a buffer does not necessarily exist
537 outfile = FileName(addName(buffer->temppath(), "tmpfile.out"));
539 outfile = FileName(addName(package().temp_dir().absFileName(),
543 if (buffer && buffer->params().use_minted
544 && lyxrc.pygmentize_command.empty() && conv.latex()) {
546 // Warn only if listings insets are actually used
547 for (Paragraph const & par : buffer->paragraphs()) {
548 InsetList const & insets = par.insetList();
549 pos_type lstpos = insets.find(LISTINGS_CODE, 0);
550 pos_type incpos = insets.find(INCLUDE_CODE, 0);
552 InsetInclude const * include =
553 static_cast<InsetInclude *>
554 (insets.get(incpos));
555 if (include->params().getCmdName() !=
560 if (lstpos >= 0 || incpos >= 0) {
566 Alert::warning(_("Pygments driver command not found!"),
567 _("The driver command necessary to use the minted package\n"
568 "(pygmentize) has not been found. Make sure you have\n"
569 "the python-pygments module installed or, if the driver\n"
570 "is named differently, to add the following line to the\n"
571 "document preamble:\n\n"
572 "\\AtBeginDocument{\\renewcommand{\\MintedPygmentize}{driver}}\n\n"
573 "where 'driver' is name of the driver command."));
577 if (!checkAuth(conv, buffer ? buffer->absFileName() : string(),
578 buffer && buffer->params().shell_escape))
582 // We are not importing, we have a buffer
583 LASSERT(buffer, return FAILURE);
585 string command = conv.command();
586 command = subst(command, token_from, "");
587 command = subst(command, token_latex_encoding,
588 buffer->params().encoding().latexName());
589 if (buffer->params().shell_escape
590 && !contains(command, "-shell-escape"))
591 command += " -shell-escape ";
592 LYXERR(Debug::FILES, "Running " << command);
594 // Check changed return value here.
595 RetVal const retval = runLaTeX(*buffer, command, runparams, errorList);
596 if (retval != SUCCESS)
599 if (conv.need_aux() && !run_latex) {
600 // We are not importing, we have a buffer
601 LASSERT(buffer, return FAILURE);
603 switch (runparams.flavor) {
604 case OutputParams::DVILUATEX:
605 command = dvilualatex_command_;
607 case OutputParams::LUATEX:
608 command = lualatex_command_;
610 case OutputParams::PDFLATEX:
611 command = pdflatex_command_;
613 case OutputParams::XETEX:
614 command = xelatex_command_;
617 command = latex_command_;
620 if (!command.empty()) {
621 LYXERR(Debug::FILES, "Running "
623 << " to update aux file");
625 // Check changed return value here.
626 RetVal const retval = runLaTeX(*buffer, command, runparams, errorList);
627 if (retval != SUCCESS)
633 string const infile2 =
634 to_utf8(makeRelPath(from_utf8(infile.absFileName()), from_utf8(path)));
635 string const outfile2 =
636 to_utf8(makeRelPath(from_utf8(outfile.absFileName()), from_utf8(path)));
638 string command = conv.command();
639 command = subst(command, token_from, quoteName(infile2));
640 command = subst(command, token_base, quoteName(from_base));
641 command = subst(command, token_to, quoteName(outfile2));
642 command = subst(command, token_path, quoteName(onlyPath(infile.absFileName())));
643 command = subst(command, token_orig_path, quoteName(onlyPath(orig_from.absFileName())));
644 command = subst(command, token_orig_from, quoteName(onlyFileName(orig_from.absFileName())));
645 command = subst(command, token_encoding, buffer ? buffer->params().encoding().iconvName() : string());
647 if (!conv.parselog().empty())
648 command += " 2> " + quoteName(infile2 + ".out");
650 // it is not actually not necessary to test for buffer here,
651 // but it pleases coverity.
652 if (buffer && conv.from() == "dvi" && conv.to() == "ps")
653 command = add_options(command,
654 buffer->params().dvips_options());
655 else if (buffer && conv.from() == "dvi" && prefixIs(conv.to(), "pdf"))
656 command = add_options(command,
657 dvipdfm_options(buffer->params()));
659 LYXERR(Debug::FILES, "Calling " << command);
661 buffer->message(_("Executing command: ")
662 + from_utf8(command));
667 res = one.startscript(Systemcall::DontWait,
668 to_filesystem8bit(from_utf8(command)),
669 buffer ? buffer->filePath() : string(),
670 buffer ? buffer->layoutPos() : string());
671 // We're not waiting for the result, so we can't do anything
674 Systemcall::Starttype starttype =
675 (buffer && buffer->isClone()) ?
676 Systemcall::WaitLoop : Systemcall::Wait;
677 res = one.startscript(starttype,
678 to_filesystem8bit(from_utf8(command)),
679 buffer ? buffer->filePath()
681 buffer ? buffer->layoutPos()
683 if (res == Systemcall::KILLED) {
684 frontend::Alert::warning(
685 _("Converter killed"),
686 bformat(_("The following converter was killed by the user.\n %1$s\n"),
687 from_utf8(command)));
691 if (!real_outfile.empty()) {
692 Mover const & mover = getMover(conv.to());
693 if (!mover.rename(outfile, real_outfile))
696 LYXERR(Debug::FILES, "renaming file " << outfile
697 << " to " << real_outfile);
698 // Finally, don't forget to tell any future
699 // converters to use the renamed file...
700 outfile = real_outfile;
703 if (!conv.parselog().empty()) {
704 string const logfile = infile2 + ".log";
705 string const command2 = conv.parselog() +
706 " < " + quoteName(infile2 + ".out") +
707 " > " + quoteName(logfile);
708 res = one.startscript(starttype,
709 to_filesystem8bit(from_utf8(command2)),
710 buffer ? buffer->filePath() : string(),
711 buffer ? buffer->layoutPos() : string());
712 if (res == Systemcall::KILLED) {
713 frontend::Alert::warning(
714 _("Converter killed"),
715 bformat(_("The following converter was killed by the user.\n %1$s\n"),
716 from_utf8(command)));
719 if (buffer && !scanLog(*buffer, command, makeAbsPath(logfile, path), errorList))
725 if (res == Systemcall::KILLED) {
726 Alert::information(_("Process Killed"),
727 bformat(_("The conversion process was killed while running:\n%1$s"),
728 wrapParas(from_utf8(command))));
731 if (res == Systemcall::TIMEOUT) {
732 Alert::information(_("Process Timed Out"),
733 bformat(_("The conversion process:\n%1$s\ntimed out before completing."),
734 wrapParas(from_utf8(command))));
737 if (conv.to() == "program") {
738 Alert::error(_("Build errors"),
739 _("There were errors during the build process."));
741 // FIXME: this should go out of here. For example, here we cannot say if
742 // it is a document (.lyx) or something else. Same goes for elsewhere.
743 Alert::error(_("Cannot convert file"),
744 bformat(_("An error occurred while running:\n%1$s"),
745 wrapParas(from_utf8(command))));
752 Converter const & conv = converterlist_[edgepath.back()];
753 if (conv.To()->dummy())
756 if (!conv.result_dir().empty()) {
757 // The converter has put the file(s) in a directory.
758 // In this case we ignore the given to_file.
759 if (from_base != to_base) {
760 string const from = subst(conv.result_dir(),
761 token_base, from_base);
762 string const to = subst(conv.result_dir(),
763 token_base, to_base);
764 Mover const & mover = getMover(conv.from());
765 if (!mover.rename(FileName(from), FileName(to))) {
766 Alert::error(_("Cannot convert file"),
767 bformat(_("Could not move a temporary directory from %1$s to %2$s."),
768 from_utf8(from), from_utf8(to)));
774 if (conversionflags & try_cache)
775 ConverterCache::get().add(orig_from, to_format, outfile);
776 return move(conv.to(), outfile, to_file, conv.latex()) ? SUCCESS : FAILURE;
781 bool Converters::move(string const & fmt,
782 FileName const & from, FileName const & to, bool copy)
787 bool no_errors = true;
788 string const path = onlyPath(from.absFileName());
789 string const base = onlyFileName(removeExtension(from.absFileName()));
790 string const to_base = removeExtension(to.absFileName());
791 string const to_extension = getExtension(to.absFileName());
793 support::FileNameList const files = FileName(path).dirList(getExtension(from.absFileName()));
794 for (auto const & f : files) {
795 string const from2 = f.absFileName();
796 string const file2 = onlyFileName(from2);
797 if (prefixIs(file2, base)) {
798 string const to2 = changeExtension(
799 to_base + file2.substr(base.length()),
801 LYXERR(Debug::FILES, "moving " << from2 << " to " << to2);
803 Mover const & mover = getMover(fmt);
804 bool const moved = copy
805 ? mover.copy(f, FileName(to2))
806 : mover.rename(f, FileName(to2));
807 if (!moved && no_errors) {
808 Alert::error(_("Cannot convert file"),
810 _("Could not copy a temporary file from %1$s to %2$s.") :
811 _("Could not move a temporary file from %1$s to %2$s."),
812 from_utf8(from2), from_utf8(to2)));
821 bool Converters::formatIsUsed(string const & format) const
823 for (auto const & cvt : converterlist_) {
824 if (cvt.from() == format || cvt.to() == format)
831 bool Converters::scanLog(Buffer const & buffer, string const & /*command*/,
832 FileName const & filename, ErrorList & errorList)
834 OutputParams runparams(nullptr);
835 runparams.flavor = OutputParams::LATEX;
836 LaTeX latex("", runparams, filename);
838 int const result = latex.scanLogFile(terr);
840 if (result & LaTeX::ERRORS)
841 buffer.bufferErrors(terr, errorList);
847 Converters::RetVal Converters::runLaTeX(Buffer const & buffer, string const & command,
848 OutputParams const & runparams, ErrorList & errorList)
850 buffer.setBusy(true);
851 buffer.message(_("Running LaTeX..."));
853 // do the LaTeX run(s)
854 string const name = buffer.latexName();
855 LaTeX latex(command, runparams, FileName(makeAbsPath(name)),
856 buffer.filePath(), buffer.layoutPos(),
857 buffer.isClone(), buffer.freshStartRequired());
859 // The connection closes itself at the end of the scope when latex is
860 // destroyed. One cannot close (and destroy) buffer while the converter is
862 latex.message.connect([&buffer](docstring const & msg){
865 int const result = latex.run(terr);
867 if (result == Systemcall::KILLED || result == Systemcall::TIMEOUT) {
868 Alert::error(_("Export canceled"),
869 _("The export process was terminated by the user."));
873 if (result & LaTeX::ERRORS)
874 buffer.bufferErrors(terr, errorList);
876 if ((result & LaTeX::UNDEF_CIT) || (result & LaTeX::UNDEF_UNKNOWN_REF)) {
877 buffer.bufferRefs(terr, errorList);
878 if (errorList.empty())
879 errorList.push_back(ErrorItem(_("Undefined reference"),
880 _("Undefined references or citations were found during the build.\n"
881 "Please check the warnings in the LaTeX log (Document > LaTeX Log)."),
885 if (!errorList.empty()) {
886 // We will show the LaTeX Errors GUI later which contains
887 // specific error messages so it would be repetitive to give
888 // e.g. the "finished with an error" dialog in addition.
890 else if (result & LaTeX::NO_LOGFILE) {
891 docstring const str =
892 bformat(_("LaTeX did not run successfully. "
893 "Additionally, LyX could not locate "
894 "the LaTeX log %1$s."), from_utf8(name));
895 Alert::error(_("LaTeX failed"), str);
896 } else if (result & LaTeX::NONZERO_ERROR) {
897 docstring const str =
898 bformat(_( "The external program\n%1$s\n"
899 "finished with an error. "
900 "It is recommended you fix the cause of the external "
901 "program's error (check the logs). "), from_utf8(command));
902 Alert::error(_("LaTeX failed"), str);
903 } else if (result & LaTeX::NO_OUTPUT) {
904 Alert::warning(_("Output is empty"),
905 _("No output file was generated."));
908 buffer.setBusy(false);
910 int const ERROR_MASK =
914 LaTeX::UNDEF_UNKNOWN_REF |
917 return (result & ERROR_MASK) == 0 ? SUCCESS : FAILURE;
922 void Converters::buildGraph()
924 // clear graph's data structures
925 G_.init(theFormats().size());
926 // each of the converters knows how to convert one format to another
927 // so, for each of them, we create an arrow on the graph, going from
928 // the one to the other
929 for (auto const & cvt : converterlist_) {
930 int const from = theFormats().getNumber(cvt.from());
931 int const to = theFormats().getNumber(cvt.to());
932 LASSERT(from >= 0, continue);
933 LASSERT(to >= 0, continue);
934 G_.addEdge(from, to);
939 FormatList const Converters::intToFormat(vector<int> const & input)
941 FormatList result(input.size());
943 vector<int>::const_iterator it = input.begin();
944 vector<int>::const_iterator const end = input.end();
945 FormatList::iterator rit = result.begin();
946 for ( ; it != end; ++it, ++rit) {
947 *rit = &theFormats().get(*it);
953 FormatList const Converters::getReachableTo(string const & target,
954 bool const clear_visited)
956 vector<int> const & reachablesto =
957 G_.getReachableTo(theFormats().getNumber(target), clear_visited);
959 return intToFormat(reachablesto);
963 FormatList const Converters::getReachable(string const & from,
964 bool const only_viewable, bool const clear_visited,
965 set<string> const & excludes)
967 set<int> excluded_numbers;
969 for (auto const & ex : excludes)
970 excluded_numbers.insert(theFormats().getNumber(ex));
972 vector<int> const & reachables =
973 G_.getReachable(theFormats().getNumber(from),
978 return intToFormat(reachables);
982 bool Converters::isReachable(string const & from, string const & to)
984 return G_.isReachable(theFormats().getNumber(from),
985 theFormats().getNumber(to));
989 Graph::EdgePath Converters::getPath(string const & from, string const & to)
991 return G_.getPath(theFormats().getNumber(from),
992 theFormats().getNumber(to));
996 FormatList Converters::importableFormats()
998 vector<string> l = loaders();
999 FormatList result = getReachableTo(l[0], true);
1000 vector<string>::const_iterator it = l.begin() + 1;
1001 vector<string>::const_iterator en = l.end();
1002 for (; it != en; ++it) {
1003 FormatList r = getReachableTo(*it, false);
1004 result.insert(result.end(), r.begin(), r.end());
1010 FormatList Converters::exportableFormats(bool only_viewable)
1012 vector<string> s = savers();
1013 FormatList result = getReachable(s[0], only_viewable, true);
1014 vector<string>::const_iterator it = s.begin() + 1;
1015 vector<string>::const_iterator en = s.end();
1016 for (; it != en; ++it) {
1017 FormatList r = getReachable(*it, only_viewable, false);
1018 result.insert(result.end(), r.begin(), r.end());
1024 vector<string> Converters::loaders() const
1028 v.push_back("text");
1029 v.push_back("textparagraph");
1034 vector<string> Converters::savers() const
1037 v.push_back("docbook");
1038 v.push_back("latex");
1039 v.push_back("literate");
1040 v.push_back("luatex");
1041 v.push_back("dviluatex");
1043 v.push_back("xhtml");
1044 v.push_back("pdflatex");
1045 v.push_back("platex");
1046 v.push_back("text");
1047 v.push_back("xetex");