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), 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 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::DOCBOOK5;
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->lang();
485 // Some macros rely on font encoding
486 runparams.main_fontenc = bp.main_font_encoding();
487 runparams.only_childbibs = !bp.useBiblatex()
489 && bp.multibib == "child";
490 runparams.includeall = includeall;
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
500 string const path(onlyPath(from_file.absFileName()));
501 // Prevent the compiler from optimizing away p
505 // empty the error list before any new conversion takes place.
508 bool run_latex = false;
509 string from_base = changeExtension(from_file.absFileName(), "");
510 string to_base = changeExtension(to_file.absFileName(), "");
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";
517 LYXERR(Debug::FILES, "Converting from "
518 << conv.from() << " to " << conv.to());
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))));
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
538 outfile = FileName(addName(buffer->temppath(), "tmpfile.out"));
540 outfile = FileName(addName(package().temp_dir().absFileName(),
544 if (buffer && buffer->params().use_minted
545 && lyxrc.pygmentize_command.empty() && conv.latex()) {
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);
553 InsetInclude const * include =
554 static_cast<InsetInclude *>
555 (insets.get(incpos));
556 if (include->params().getCmdName() !=
561 if (lstpos >= 0 || incpos >= 0) {
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."));
578 if (!checkAuth(conv, buffer ? buffer->absFileName() : string(),
579 buffer && buffer->params().shell_escape))
583 // We are not importing, we have a buffer
584 LASSERT(buffer, return FAILURE);
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);
595 // Check changed return value here.
596 RetVal const retval = runLaTeX(*buffer, command, runparams, errorList);
597 if (retval != SUCCESS)
600 if (conv.need_aux() && !run_latex) {
601 // We are not importing, we have a buffer
602 LASSERT(buffer, return FAILURE);
604 switch (runparams.flavor) {
605 case OutputParams::DVILUATEX:
606 command = dvilualatex_command_;
608 case OutputParams::LUATEX:
609 command = lualatex_command_;
611 case OutputParams::PDFLATEX:
612 command = pdflatex_command_;
614 case OutputParams::XETEX:
615 command = xelatex_command_;
618 command = latex_command_;
621 if (!command.empty()) {
622 LYXERR(Debug::FILES, "Running "
624 << " to update aux file");
626 // Check changed return value here.
627 RetVal const retval = runLaTeX(*buffer, command, runparams, errorList);
628 if (retval != SUCCESS)
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)));
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());
648 if (!conv.parselog().empty())
649 command += " 2> " + quoteName(infile2 + ".out");
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()));
660 LYXERR(Debug::FILES, "Calling " << command);
662 buffer->message(_("Executing command: ")
663 + from_utf8(command));
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
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()
682 buffer ? buffer->layoutPos()
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)));
692 if (!real_outfile.empty()) {
693 Mover const & mover = getMover(conv.to());
694 if (!mover.rename(outfile, real_outfile))
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;
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)));
720 if (buffer && !scanLog(*buffer, command, makeAbsPath(logfile, path), errorList))
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))));
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))));
738 if (conv.to() == "program") {
739 Alert::error(_("Build errors"),
740 _("There were errors during the build process."));
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))));
753 Converter const & conv = converterlist_[edgepath.back()];
754 if (conv.To()->dummy())
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)));
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;
782 bool Converters::move(string const & fmt,
783 FileName const & from, FileName const & to, bool copy)
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());
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()),
802 LYXERR(Debug::FILES, "moving " << from2 << " to " << to2);
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"),
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)));
822 bool Converters::formatIsUsed(string const & format)
824 for (auto const & cvt : converterlist_) {
825 if (cvt.from() == format || cvt.to() == format)
832 bool Converters::scanLog(Buffer const & buffer, string const & /*command*/,
833 FileName const & filename, ErrorList & errorList)
835 OutputParams runparams(nullptr);
836 runparams.flavor = OutputParams::LATEX;
837 LaTeX latex("", runparams, filename);
839 int const result = latex.scanLogFile(terr);
841 if (result & LaTeX::ERRORS)
842 buffer.bufferErrors(terr, errorList);
848 Converters::RetVal Converters::runLaTeX(Buffer const & buffer, string const & command,
849 OutputParams const & runparams, ErrorList & errorList)
851 buffer.setBusy(true);
852 buffer.message(_("Running LaTeX..."));
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());
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
863 latex.message.connect([&buffer](docstring const & msg){
866 int const result = latex.run(terr);
868 if (result == Systemcall::KILLED || result == Systemcall::TIMEOUT) {
869 Alert::error(_("Export canceled"),
870 _("The export process was terminated by the user."));
874 if (result & LaTeX::ERRORS)
875 buffer.bufferErrors(terr, errorList);
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)."),
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.
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."));
909 buffer.setBusy(false);
911 int const ERROR_MASK =
915 LaTeX::UNDEF_UNKNOWN_REF |
918 return (result & ERROR_MASK) == 0 ? SUCCESS : FAILURE;
923 void Converters::buildGraph()
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);
940 FormatList const Converters::intToFormat(vector<int> const & input)
942 FormatList result(input.size());
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);
954 FormatList const Converters::getReachableTo(string const & target,
955 bool const clear_visited)
957 vector<int> const & reachablesto =
958 G_.getReachableTo(theFormats().getNumber(target), clear_visited);
960 return intToFormat(reachablesto);
964 FormatList const Converters::getReachable(string const & from,
965 bool const only_viewable, bool const clear_visited,
966 set<string> const & excludes)
968 set<int> excluded_numbers;
970 for (auto const & ex : excludes)
971 excluded_numbers.insert(theFormats().getNumber(ex));
973 vector<int> const & reachables =
974 G_.getReachable(theFormats().getNumber(from),
979 return intToFormat(reachables);
983 bool Converters::isReachable(string const & from, string const & to)
985 return G_.isReachable(theFormats().getNumber(from),
986 theFormats().getNumber(to));
990 Graph::EdgePath Converters::getPath(string const & from, string const & to)
992 return G_.getPath(theFormats().getNumber(from),
993 theFormats().getNumber(to));
997 FormatList Converters::importableFormats()
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());
1011 FormatList Converters::exportableFormats(bool only_viewable)
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());
1025 vector<string> Converters::loaders() const
1029 v.push_back("text");
1030 v.push_back("textparagraph");
1035 vector<string> Converters::savers() const
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");
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");