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"
18 #include "TextClass.h"
20 #include "ErrorList.h"
22 #include "InsetList.h"
27 #include "OutputParams.h"
28 #include "ParagraphList.h"
31 #include "frontends/alert.h"
33 #include "insets/InsetInclude.h"
35 #include "support/debug.h"
36 #include "support/FileNameList.h"
37 #include "support/filetools.h"
38 #include "support/gettext.h"
39 #include "support/lassert.h"
40 #include "support/lstrings.h"
41 #include "support/os.h"
42 #include "support/Package.h"
43 #include "support/PathChanger.h"
44 #include "support/Systemcall.h"
47 using namespace lyx::support;
51 namespace Alert = lyx::frontend::Alert;
56 string const token_from("$$i");
57 string const token_base("$$b");
58 string const token_to("$$o");
59 string const token_path("$$p");
60 string const token_orig_path("$$r");
61 string const token_orig_from("$$f");
62 string const token_textclass("$$c");
63 string const token_modules("$$m");
64 string const token_encoding("$$e");
65 string const token_latex_encoding("$$E");
66 string const token_python("$${python}");
68 string const add_options(string const & command, string const & options)
71 string const tail = split(command, head, ' ');
72 return head + ' ' + options + ' ' + tail;
76 string const dvipdfm_options(BufferParams const & bp)
80 if (bp.papersize != PAPER_CUSTOM) {
81 string const paper_size = bp.paperSizeName(BufferParams::DVIPDFM);
82 if (!paper_size.empty())
83 result = "-p "+ paper_size;
85 if (bp.orientation == ORIENTATION_LANDSCAPE)
93 class ConverterEqual {
95 ConverterEqual(string const & from, string const & to)
96 : from_(from), to_(to) {}
97 bool operator()(Converter const & c) const {
98 return c.from() == from_ && c.to() == to_;
108 Converter::Converter(string const & f, string const & t,
109 string const & c, string const & l)
110 : from_(f), to_(t), command_(c), flags_(l),
111 From_(nullptr), To_(nullptr), latex_(false), docbook_(false),
112 need_aux_(false), nice_(false), need_auth_(false)
116 void Converter::readFlags()
118 string flag_list(flags_);
119 while (!flag_list.empty()) {
120 string flag_name, flag_value;
121 flag_list = split(flag_list, flag_value, ',');
122 flag_value = split(flag_value, flag_name, '=');
123 if (flag_name == "latex") {
125 latex_flavor_ = flag_value.empty() ?
126 "latex" : flag_value;
127 } else if (flag_name == "xml")
129 else if (flag_name == "needaux") {
131 latex_flavor_ = flag_value.empty() ?
132 "latex" : flag_value;
133 } else if (flag_name == "resultdir")
134 result_dir_ = (flag_value.empty())
135 ? token_base : flag_value;
136 else if (flag_name == "resultfile")
137 result_file_ = flag_value;
138 else if (flag_name == "parselog")
139 parselog_ = flag_value;
140 else if (flag_name == "nice")
142 else if (flag_name == "needauth")
144 else if (flag_name == "hyperref-driver")
145 href_driver_ = flag_value;
147 if (!result_dir_.empty() && result_file_.empty())
148 result_file_ = "index." + theFormats().extension(to_);
149 //if (!contains(command, token_from))
154 void Converter::setCommand(std::string const & command)
156 command_ = subst(command, token_python, os::python());
160 Converter const * Converters::getConverter(string const & from,
161 string const & to) const
163 ConverterList::const_iterator const cit =
164 find_if(converterlist_.begin(), converterlist_.end(),
165 ConverterEqual(from, to));
166 if (cit != converterlist_.end())
173 int Converters::getNumber(string const & from, string const & to) const
175 ConverterList::const_iterator const cit =
176 find_if(converterlist_.begin(), converterlist_.end(),
177 ConverterEqual(from, to));
178 if (cit != converterlist_.end())
179 return distance(converterlist_.begin(), cit);
185 void Converters::add(string const & from, string const & to,
186 string const & command, string const & flags)
188 theFormats().add(from);
189 theFormats().add(to);
190 ConverterList::iterator it = find_if(converterlist_.begin(),
191 converterlist_.end(),
192 ConverterEqual(from , to));
194 Converter converter(from, to, command, flags);
195 if (it != converterlist_.end() && !flags.empty() && flags[0] == '*') {
197 converter.setCommand(command);
198 converter.setFlags(flags);
200 converter.readFlags();
202 // The latex_command is used to update the .aux file when running
203 // a converter that uses it.
204 if (converter.latex()) {
205 if (latex_command_.empty() ||
206 converter.latex_flavor() == "latex")
207 latex_command_ = subst(command, token_from, "");
208 if (dvilualatex_command_.empty() ||
209 converter.latex_flavor() == "dvilualatex")
210 dvilualatex_command_ = subst(command, token_from, "");
211 if (lualatex_command_.empty() ||
212 converter.latex_flavor() == "lualatex")
213 lualatex_command_ = subst(command, token_from, "");
214 if (pdflatex_command_.empty() ||
215 converter.latex_flavor() == "pdflatex")
216 pdflatex_command_ = subst(command, token_from, "");
217 if (xelatex_command_.empty() ||
218 converter.latex_flavor() == "xelatex")
219 xelatex_command_ = subst(command, token_from, "");
222 if (it == converterlist_.end()) {
223 converterlist_.push_back(converter);
225 converter.setFrom(it->From());
226 converter.setTo(it->To());
232 void Converters::erase(string const & from, string const & to)
234 ConverterList::iterator const it =
235 find_if(converterlist_.begin(),
236 converterlist_.end(),
237 ConverterEqual(from, to));
238 if (it != converterlist_.end())
239 converterlist_.erase(it);
243 // This method updates the pointers From and To in all the converters.
244 // The code is not very efficient, but it doesn't matter as the number
245 // of formats and converters is small.
246 // Furthermore, this method is called only on startup, or after
247 // adding/deleting a format in FormPreferences (the latter calls can be
248 // eliminated if the formats in the Formats class are stored using a map or
249 // a list (instead of a vector), but this will cause other problems).
250 void Converters::update(Formats const & formats)
252 for (auto & cv : converterlist_) {
253 cv.setFrom(formats.getFormat(cv.from()));
254 cv.setTo(formats.getFormat(cv.to()));
259 // This method updates the pointers From and To in the last converter.
260 // It is called when adding a new converter in FormPreferences
261 void Converters::updateLast(Formats const & formats)
263 if (converterlist_.begin() != converterlist_.end()) {
264 ConverterList::iterator it = converterlist_.end() - 1;
265 it->setFrom(formats.getFormat(it->from()));
266 it->setTo(formats.getFormat(it->to()));
271 Flavor Converters::getFlavor(Graph::EdgePath const & path,
272 Buffer const * buffer) const
274 for (auto const & edge : path) {
275 Converter const & conv = converterlist_[edge];
276 if (conv.latex() || conv.need_aux()) {
277 if (conv.latex_flavor() == "latex")
278 return Flavor::LaTeX;
279 if (conv.latex_flavor() == "xelatex")
280 return Flavor::XeTeX;
281 if (conv.latex_flavor() == "lualatex")
282 return Flavor::LuaTeX;
283 if (conv.latex_flavor() == "dvilualatex")
284 return Flavor::DviLuaTeX;
285 if (conv.latex_flavor() == "pdflatex")
286 return Flavor::PdfLaTeX;
289 return Flavor::DocBook5;
291 return buffer ? buffer->params().getOutputFlavor()
296 string Converters::getHyperrefDriver(Graph::EdgePath const & path) const
298 for (auto const & edge : path) {
299 Converter const & conv = converterlist_[edge];
300 if (!conv.hyperref_driver().empty())
301 return conv.hyperref_driver();
307 bool Converters::checkAuth(Converter const & conv, string const & doc_fname,
308 bool use_shell_escape)
310 string conv_command = conv.command();
311 bool const has_shell_escape = contains(conv_command, "-shell-escape")
312 || contains(conv_command, "-enable-write18");
313 if (conv.latex() && has_shell_escape && !use_shell_escape) {
314 // Only change font if gui is available otherwise Qt6 crashes
315 string const cmd = use_gui ? "<tt>" + conv_command + "</tt>"
317 docstring const shellescape_warning =
318 bformat(_("<p>The following LaTeX backend has been "
319 "configured to allow execution of external programs "
320 "for any document:</p>"
321 "<center><p>%1$s</p></center>"
322 "<p>This is a dangerous configuration. Please, "
323 "consider using the support offered by LyX for "
324 "allowing this privilege only to documents that "
325 "actually need it, instead.</p>"),
327 frontend::Alert::error(_("Security Warning"),
328 shellescape_warning , false);
329 } else if (!conv.latex())
330 use_shell_escape = false;
331 if (!conv.need_auth() && !use_shell_escape)
333 size_t const token_pos = conv_command.find("$$");
334 bool const has_token = token_pos != string::npos;
335 string const command = use_shell_escape && !has_shell_escape
336 ? (has_token ? conv_command.insert(token_pos, "-shell-escape ")
337 : conv_command.append(" -shell-escape"))
339 // Only change font if gui is available otherwise Qt6 crashes
340 string const cmd = use_gui ? "<tt>" + command + "</tt>" : command;
341 docstring const security_warning = (use_shell_escape
342 ? bformat(_("<p>The following LaTeX backend has been requested "
343 "to allow execution of external programs:</p>"
344 "<center><p>%1$s</p></center>"
345 "<p>The external programs can execute arbitrary commands on "
346 "your system, including dangerous ones, if instructed to do "
347 "so by a maliciously crafted LyX document.</p>"),
349 : bformat(_("<p>The requested operation requires the use of a "
350 "converter from %2$s to %3$s:</p>"
351 "<blockquote><p>%1$s</p></blockquote>"
352 "<p>This external program can execute arbitrary commands on "
353 "your system, including dangerous ones, if instructed to do "
354 "so by a maliciously crafted LyX document.</p>"),
355 from_utf8(cmd), from_utf8(conv.from()),
356 from_utf8(conv.to())));
357 if (lyxrc.use_converter_needauth_forbidden && !use_shell_escape) {
358 frontend::Alert::error(
359 _("An external converter is disabled for security reasons"),
360 security_warning + _(
361 "<p><b>Your current preference settings forbid its execution.</b></p>"
362 "<p>(To change this setting, go to <i>Preferences ▹ File "
363 "Handling ▹ Converters</i> and uncheck <i>Security ▹ "
364 "Forbid needauth converters</i>.)"), false);
367 if (!lyxrc.use_converter_needauth && !use_shell_escape)
369 docstring const security_title = use_shell_escape
370 ? _("A LaTeX backend requires your authorization")
371 : _("An external converter requires your authorization");
373 docstring const security_warning2 = security_warning + (use_shell_escape
374 ? _("<p>Should LaTeX backends be allowed to run external "
375 "programs?</p><p><b>Allow them only if you trust the "
376 "origin/sender of the LyX document!</b></p>")
377 : _("<p>Would you like to run this converter?</p>"
378 "<p><b>Only run if you trust the origin/sender of the LyX "
379 "document!</b></p>"));
380 docstring const no = use_shell_escape
381 ? _("Do ¬ allow") : _("Do ¬ run");
382 docstring const yes = use_shell_escape ? _("A&llow") : _("&Run");
383 docstring const always = use_shell_escape
384 ? _("&Always allow for this document")
385 : _("&Always run for this document");
386 if (!doc_fname.empty()) {
387 LYXERR(Debug::FILES, "looking up: " << doc_fname);
388 bool authorized = use_shell_escape
389 ? theSession().shellescapeFiles().findAuth(doc_fname)
390 : theSession().authFiles().find(doc_fname);
392 choice = frontend::Alert::prompt(security_title,
394 0, 0, no, yes, always);
396 if (use_shell_escape)
397 theSession().shellescapeFiles().insert(doc_fname, true);
399 theSession().authFiles().insert(doc_fname);
405 choice = frontend::Alert::prompt(security_title,
413 Converters::RetVal Converters::convert(Buffer const * buffer,
414 FileName const & from_file, FileName const & to_file,
415 FileName const & orig_from,
416 string const & from_format, string const & to_format,
417 ErrorList & errorList, int conversionflags, bool includeall)
419 if (from_format == to_format)
420 return move(from_format, from_file, to_file, false) ?
423 if ((conversionflags & try_cache) &&
424 ConverterCache::get().inCache(orig_from, to_format))
425 return ConverterCache::get().copy(orig_from, to_format, to_file) ?
428 Graph::EdgePath edgepath = getPath(from_format, to_format);
429 if (edgepath.empty()) {
430 if (conversionflags & try_default) {
431 // if no special converter defined, then we take the
432 // default one from ImageMagic.
433 string const from_ext = from_format.empty() ?
434 getExtension(from_file.absFileName()) :
435 theFormats().extension(from_format);
436 string const to_ext = theFormats().extension(to_format);
437 string const command =
439 quoteName(libFileSearch("scripts", "convertDefault.py").toFilesystemEncoding()) +
440 ' ' + from_ext + ' ' +
441 quoteName(from_file.toFilesystemEncoding()) +
443 quoteName(to_file.toFilesystemEncoding());
444 LYXERR(Debug::FILES, "No converter defined! "
445 "I use convertDefault.py:\n\t" << command);
447 Systemcall::Starttype starttype =
448 (buffer && buffer->isClone()) ?
449 Systemcall::WaitLoop : Systemcall::Wait;
450 int const exitval = one.startscript(starttype, command,
451 buffer ? buffer->filePath() : string(),
452 buffer ? buffer->layoutPos() : string());
453 if (exitval == Systemcall::KILLED) {
454 frontend::Alert::warning(
455 _("Converter killed"),
456 bformat(_("The following converter was killed by the user.\n %1$s\n"),
457 from_utf8(command)));
460 if (to_file.isReadableFile()) {
461 if (conversionflags & try_cache)
462 ConverterCache::get().add(orig_from,
468 // only warn once per session and per file type
469 static std::map<string, string> warned;
470 if (warned.find(from_format) != warned.end() && warned.find(from_format)->second == to_format) {
473 warned.insert(make_pair(from_format, to_format));
475 Alert::error(_("Cannot convert file"),
476 bformat(_("No information for converting %1$s "
477 "format files to %2$s.\n"
478 "Define a converter in the preferences."),
479 from_ascii(from_format), from_ascii(to_format)));
483 // buffer can only be null for importing, and then runparams is not
485 OutputParams runparams(buffer ? &buffer->params().encoding() : nullptr);
486 runparams.flavor = getFlavor(edgepath, buffer);
489 BufferParams const & bp = buffer->params();
490 runparams.use_japanese =
491 (bp.bufferFormat() == "latex"
492 || suffixIs(bp.bufferFormat(), "-ja"))
493 && bp.encoding().package() == Encoding::japanese;
494 runparams.use_indices = bp.use_indices;
495 runparams.bibtex_command = bp.bibtexCommand(true);
496 runparams.index_command = (bp.index_command == "default") ?
497 string() : bp.index_command;
498 runparams.document_language = bp.language->lang();
499 // Some macros rely on font encoding
500 runparams.main_fontenc = bp.main_font_encoding();
501 runparams.only_childbibs = !bp.useBiblatex()
503 && bp.multibib == "child";
504 runparams.includeall = includeall;
507 // Some converters (e.g. lilypond) can only output files to the
508 // current directory, so we need to change the current directory.
509 // This has the added benefit that all other files that may be
510 // generated by the converter are deleted when LyX closes and do not
511 // clutter the real working directory.
512 // FIXME: This does not work if path is an UNC path on windows
514 string const path(onlyPath(from_file.absFileName()));
515 // Prevent the compiler from optimizing away p
519 // empty the error list before any new conversion takes place.
522 bool run_latex = false;
523 string from_base = changeExtension(from_file.absFileName(), "");
524 string to_base = changeExtension(to_file.absFileName(), "");
526 FileName outfile = from_file;
527 for (auto const & edge : edgepath) {
528 Converter const & conv = converterlist_[edge];
529 bool dummy = conv.To()->dummy() && conv.to() != "program";
531 LYXERR(Debug::FILES, "Converting from "
532 << conv.from() << " to " << conv.to());
535 outfile = FileName(conv.result_file().empty()
536 ? changeExtension(from_file.absFileName(), conv.To()->extension())
537 : addName(subst(conv.result_dir(),
538 token_base, from_base),
539 subst(conv.result_file(),
540 token_base, onlyFileName(from_base))));
542 // if input and output files are equal, we use a
543 // temporary file as intermediary (JMarc)
544 FileName real_outfile;
545 if (!conv.result_file().empty())
546 real_outfile = FileName(changeExtension(from_file.absFileName(),
547 conv.To()->extension()));
548 if (outfile == infile) {
549 real_outfile = infile;
550 // when importing, a buffer does not necessarily exist
552 outfile = FileName(addName(buffer->temppath(), "tmpfile.out"));
554 outfile = FileName(addName(package().temp_dir().absFileName(),
558 if (buffer && buffer->params().use_minted
559 && lyxrc.pygmentize_command.empty() && conv.latex()) {
561 // Warn only if listings insets are actually used
562 for (Paragraph const & par : buffer->paragraphs()) {
563 InsetList const & insets = par.insetList();
564 pos_type lstpos = insets.find(LISTINGS_CODE, 0);
565 pos_type incpos = insets.find(INCLUDE_CODE, 0);
567 InsetInclude const * include =
568 static_cast<InsetInclude *>
569 (insets.get(incpos));
570 if (include->params().getCmdName() !=
575 if (lstpos >= 0 || incpos >= 0) {
581 Alert::warning(_("Pygments driver command not found!"),
582 _("The driver command necessary to use the minted package\n"
583 "(pygmentize) has not been found. Make sure you have\n"
584 "the python-pygments module installed or, if the driver\n"
585 "is named differently, to add the following line to the\n"
586 "document preamble:\n\n"
587 "\\AtBeginDocument{\\renewcommand{\\MintedPygmentize}{driver}}\n\n"
588 "where 'driver' is name of the driver command."));
592 if (!checkAuth(conv, buffer ? buffer->absFileName() : string(),
593 buffer && buffer->params().shell_escape))
597 // We are not importing, we have a buffer
598 LASSERT(buffer, return FAILURE);
600 string command = conv.command();
601 command = subst(command, token_from, "");
602 command = subst(command, token_latex_encoding,
603 buffer->params().encoding().latexName());
604 if (buffer->params().shell_escape
605 && !contains(command, "-shell-escape"))
606 command += " -shell-escape ";
607 LYXERR(Debug::FILES, "Running " << command);
609 // Check changed return value here.
610 RetVal const retval = runLaTeX(*buffer, command, runparams, errorList);
611 if (retval != SUCCESS)
614 if (conv.need_aux() && !run_latex) {
615 // We are not importing, we have a buffer
616 LASSERT(buffer, return FAILURE);
618 switch (runparams.flavor) {
619 case Flavor::DviLuaTeX:
620 command = dvilualatex_command_;
623 command = lualatex_command_;
625 case Flavor::PdfLaTeX:
626 command = pdflatex_command_;
629 command = xelatex_command_;
632 command = latex_command_;
635 if (!command.empty()) {
636 LYXERR(Debug::FILES, "Running "
638 << " to update aux file");
640 // Check changed return value here.
641 RetVal const retval = runLaTeX(*buffer, command, runparams, errorList);
642 if (retval != SUCCESS)
648 string const infile2 =
649 to_utf8(makeRelPath(from_utf8(infile.absFileName()), from_utf8(path)));
650 string const outfile2 =
651 to_utf8(makeRelPath(from_utf8(outfile.absFileName()), from_utf8(path)));
653 string command = conv.command();
654 BufferParams const & bparams = buffer ? buffer->params() : defaultBufferParams();
655 command = subst(command, token_from, quoteName(infile2));
656 command = subst(command, token_base, quoteName(from_base));
657 command = subst(command, token_to, quoteName(outfile2));
658 command = subst(command, token_path, quoteName(onlyPath(infile.absFileName())));
659 command = subst(command, token_orig_path, quoteName(onlyPath(orig_from.absFileName())));
660 command = subst(command, token_orig_from, quoteName(onlyFileName(orig_from.absFileName())));
661 command = subst(command, token_textclass, quoteName(bparams.documentClass().name()));
662 string modules = bparams.getModules().asString();
663 // FIXME: remove when SystemCall uses QProcess with the list API.
664 // Currently the QProcess parser is not able to encode an
665 // empty argument as ""; work around this by passing a
666 // single comma, that will be interpreted as a list of two
667 // empty module names.
670 command = subst(command, token_modules, quoteName(modules));
671 command = subst(command, token_encoding, quoteName(bparams.encoding().iconvName()));
672 command = subst(command, token_python, os::python());
674 if (!conv.parselog().empty())
675 command += " 2> " + quoteName(infile2 + ".out");
677 // it is not actually not necessary to test for buffer here,
678 // but it pleases coverity.
679 if (buffer && conv.from() == "dvi" && conv.to() == "ps")
680 command = add_options(command,
681 buffer->params().dvips_options());
682 else if (buffer && conv.from() == "dvi" && prefixIs(conv.to(), "pdf"))
683 command = add_options(command,
684 dvipdfm_options(buffer->params()));
686 LYXERR(Debug::FILES, "Calling " << command);
688 buffer->message(_("Executing command: ")
689 + from_utf8(command));
694 res = one.startscript(Systemcall::DontWait,
695 to_filesystem8bit(from_utf8(command)),
696 buffer ? buffer->filePath() : string(),
697 buffer ? buffer->layoutPos() : string());
698 // We're not waiting for the result, so we can't do anything
701 Systemcall::Starttype starttype =
702 (buffer && buffer->isClone()) ?
703 Systemcall::WaitLoop : Systemcall::Wait;
704 res = one.startscript(starttype,
705 to_filesystem8bit(from_utf8(command)),
706 buffer ? buffer->filePath()
708 buffer ? buffer->layoutPos()
710 if (res == Systemcall::KILLED) {
711 frontend::Alert::warning(
712 _("Converter killed"),
713 bformat(_("The following converter was killed by the user.\n %1$s\n"),
714 from_utf8(command)));
718 if (!real_outfile.empty()) {
719 Mover const & mover = getMover(conv.to());
720 if (!mover.rename(outfile, real_outfile))
723 LYXERR(Debug::FILES, "renaming file " << outfile
724 << " to " << real_outfile);
725 // Finally, don't forget to tell any future
726 // converters to use the renamed file...
727 outfile = real_outfile;
730 if (!conv.parselog().empty()) {
731 string const logfile = infile2 + ".log";
732 string const command2 = conv.parselog() +
733 " < " + quoteName(infile2 + ".out") +
734 " > " + quoteName(logfile);
735 res = one.startscript(starttype,
736 to_filesystem8bit(from_utf8(command2)),
737 buffer ? buffer->filePath() : string(),
738 buffer ? buffer->layoutPos() : string());
739 if (res == Systemcall::KILLED) {
740 frontend::Alert::warning(
741 _("Converter killed"),
742 bformat(_("The following converter was killed by the user.\n %1$s\n"),
743 from_utf8(command)));
746 if (buffer && !scanLog(*buffer, command, makeAbsPath(logfile, path), errorList))
752 if (res == Systemcall::KILLED) {
753 Alert::information(_("Process Killed"),
754 bformat(_("The conversion process was killed while running:\n%1$s"),
755 wrapParas(from_utf8(command))));
758 if (res == Systemcall::TIMEOUT) {
759 Alert::information(_("Process Timed Out"),
760 bformat(_("The conversion process:\n%1$s\ntimed out before completing."),
761 wrapParas(from_utf8(command))));
764 if (conv.to() == "program") {
765 Alert::error(_("Build errors"),
766 _("There were errors during the build process."));
768 // FIXME: this should go out of here. For example, here we cannot say if
769 // it is a document (.lyx) or something else. Same goes for elsewhere.
770 Alert::error(_("Cannot convert file"),
771 bformat(_("An error occurred while running:\n%1$s"),
772 wrapParas(from_utf8(command))));
779 Converter const & conv = converterlist_[edgepath.back()];
780 if (conv.To()->dummy())
783 if (!conv.result_dir().empty()) {
784 // The converter has put the file(s) in a directory.
785 // In this case we ignore the given to_file.
786 if (from_base != to_base) {
787 string const from = subst(conv.result_dir(),
788 token_base, from_base);
789 string const to = subst(conv.result_dir(),
790 token_base, to_base);
791 Mover const & mover = getMover(conv.from());
792 if (!mover.rename(FileName(from), FileName(to))) {
793 Alert::error(_("Cannot convert file"),
794 bformat(_("Could not move a temporary directory from %1$s to %2$s."),
795 from_utf8(from), from_utf8(to)));
801 if (conversionflags & try_cache)
802 ConverterCache::get().add(orig_from, to_format, outfile);
803 return move(conv.to(), outfile, to_file, conv.latex()) ? SUCCESS : FAILURE;
808 bool Converters::move(string const & fmt,
809 FileName const & from, FileName const & to, bool copy)
814 bool no_errors = true;
815 string const path = onlyPath(from.absFileName());
816 string const base = onlyFileName(removeExtension(from.absFileName()));
817 string const to_base = removeExtension(to.absFileName());
818 string const to_extension = getExtension(to.absFileName());
820 support::FileNameList const files = FileName(path).dirList(getExtension(from.absFileName()));
821 for (auto const & f : files) {
822 string const from2 = f.absFileName();
823 string const file2 = onlyFileName(from2);
824 if (prefixIs(file2, base)) {
825 string const to2 = changeExtension(
826 to_base + file2.substr(base.length()),
828 LYXERR(Debug::FILES, "moving " << from2 << " to " << to2);
830 Mover const & mover = getMover(fmt);
831 bool const moved = copy
832 ? mover.copy(f, FileName(to2))
833 : mover.rename(f, FileName(to2));
834 if (!moved && no_errors) {
835 Alert::error(_("Cannot convert file"),
837 _("Could not copy a temporary file from %1$s to %2$s.") :
838 _("Could not move a temporary file from %1$s to %2$s."),
839 from_utf8(from2), from_utf8(to2)));
848 bool Converters::formatIsUsed(string const & format) const
850 for (auto const & cvt : converterlist_) {
851 if (cvt.from() == format || cvt.to() == format)
858 bool Converters::scanLog(Buffer const & buffer, string const & /*command*/,
859 FileName const & filename, ErrorList & errorList)
861 OutputParams runparams(nullptr);
862 runparams.flavor = Flavor::LaTeX;
863 LaTeX latex("", runparams, filename);
865 int const result = latex.scanLogFile(terr);
867 if (result & LaTeX::ERRORS)
868 buffer.bufferErrors(terr, errorList);
874 Converters::RetVal Converters::runLaTeX(Buffer const & buffer, string const & command,
875 OutputParams const & runparams, ErrorList & errorList)
877 buffer.setBusy(true);
878 buffer.message(_("Running LaTeX..."));
880 // do the LaTeX run(s)
881 string const name = buffer.latexName();
882 LaTeX latex(command, runparams, makeAbsPath(name),
883 buffer.filePath(), buffer.layoutPos(),
884 buffer.isClone(), buffer.freshStartRequired());
886 // The connection closes itself at the end of the scope when latex is
887 // destroyed. One cannot close (and destroy) buffer while the converter is
889 latex.message.connect([&buffer](docstring const & msg){
892 int const result = latex.run(terr);
894 if (result == Systemcall::KILLED || result == Systemcall::TIMEOUT) {
895 Alert::error(_("Export canceled"),
896 _("The export process was terminated by the user."));
900 if (result & LaTeX::ERRORS)
901 buffer.bufferErrors(terr, errorList);
903 if ((result & LaTeX::UNDEF_CIT) || (result & LaTeX::UNDEF_UNKNOWN_REF)) {
904 buffer.bufferRefs(terr, errorList);
905 if (errorList.empty())
906 errorList.push_back(ErrorItem(_("Undefined reference"),
907 _("Undefined references or citations were found during the build.\n"
908 "Please check the warnings in the LaTeX log (Document > LaTeX Log)."),
912 if (!errorList.empty()) {
913 // We will show the LaTeX Errors GUI later which contains
914 // specific error messages so it would be repetitive to give
915 // e.g. the "finished with an error" dialog in addition.
917 else if (result & LaTeX::NO_LOGFILE) {
918 docstring const str =
919 bformat(_("LaTeX did not run successfully. "
920 "Additionally, LyX could not locate "
921 "the LaTeX log %1$s."), from_utf8(name));
922 Alert::error(_("LaTeX failed"), str);
923 } else if (result & LaTeX::NONZERO_ERROR) {
924 docstring const str =
925 bformat(_( "The external program\n%1$s\n"
926 "finished with an error. "
927 "It is recommended you fix the cause of the external "
928 "program's error (check the logs). "), from_utf8(command));
929 Alert::error(_("LaTeX failed"), str);
930 } else if (result & LaTeX::NO_OUTPUT) {
931 Alert::warning(_("Output is empty"),
932 _("No output file was generated."));
935 buffer.setBusy(false);
937 int const ERROR_MASK =
941 LaTeX::UNDEF_UNKNOWN_REF |
944 return (result & ERROR_MASK) == 0 ? SUCCESS : FAILURE;
949 void Converters::buildGraph()
951 // clear graph's data structures
952 G_.init(theFormats().size());
953 // each of the converters knows how to convert one format to another
954 // so, for each of them, we create an arrow on the graph, going from
955 // the one to the other
956 for (auto const & cvt : converterlist_) {
957 int const from = theFormats().getNumber(cvt.from());
958 int const to = theFormats().getNumber(cvt.to());
959 LASSERT(from >= 0, continue);
960 LASSERT(to >= 0, continue);
961 G_.addEdge(from, to);
966 FormatList const Converters::intToFormat(vector<int> const & input)
968 FormatList result(input.size());
970 vector<int>::const_iterator it = input.begin();
971 vector<int>::const_iterator const end = input.end();
972 FormatList::iterator rit = result.begin();
973 for ( ; it != end; ++it, ++rit) {
974 *rit = &theFormats().get(*it);
980 FormatList const Converters::getReachableTo(string const & target,
981 bool const clear_visited)
983 vector<int> const & reachablesto =
984 G_.getReachableTo(theFormats().getNumber(target), clear_visited);
986 return intToFormat(reachablesto);
990 FormatList const Converters::getReachable(string const & from,
991 bool const only_viewable, bool const clear_visited,
992 set<string> const & excludes)
994 set<int> excluded_numbers;
996 for (auto const & ex : excludes)
997 excluded_numbers.insert(theFormats().getNumber(ex));
999 vector<int> const & reachables =
1000 G_.getReachable(theFormats().getNumber(from),
1005 return intToFormat(reachables);
1009 bool Converters::isReachable(string const & from, string const & to)
1011 return G_.isReachable(theFormats().getNumber(from),
1012 theFormats().getNumber(to));
1016 Graph::EdgePath Converters::getPath(string const & from, string const & to)
1018 return G_.getPath(theFormats().getNumber(from),
1019 theFormats().getNumber(to));
1023 FormatList Converters::importableFormats()
1025 vector<string> l = loaders();
1026 FormatList result = getReachableTo(l[0], true);
1027 vector<string>::const_iterator it = l.begin() + 1;
1028 vector<string>::const_iterator en = l.end();
1029 for (; it != en; ++it) {
1030 FormatList r = getReachableTo(*it, false);
1031 result.insert(result.end(), r.begin(), r.end());
1037 FormatList Converters::exportableFormats(bool only_viewable)
1039 vector<string> s = savers();
1040 FormatList result = getReachable(s[0], only_viewable, true);
1041 vector<string>::const_iterator it = s.begin() + 1;
1042 vector<string>::const_iterator en = s.end();
1043 for (; it != en; ++it) {
1044 FormatList r = getReachable(*it, only_viewable, false);
1045 result.insert(result.end(), r.begin(), r.end());
1051 vector<string> Converters::loaders() const
1055 v.push_back("text");
1056 v.push_back("textparagraph");
1061 vector<string> Converters::savers() const
1064 v.push_back("docbook");
1065 v.push_back("latex");
1066 v.push_back("literate");
1067 v.push_back("luatex");
1068 v.push_back("dviluatex");
1070 v.push_back("xhtml");
1071 v.push_back("pdflatex");
1072 v.push_back("platex");
1073 v.push_back("text");
1074 v.push_back("xetex");