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 docstring const shellescape_warning =
315 bformat(_("<p>The following LaTeX backend has been "
316 "configured to allow execution of external programs "
317 "for any document:</p>"
318 "<center><p><tt>%1$s</tt></p></center>"
319 "<p>This is a dangerous configuration. Please, "
320 "consider using the support offered by LyX for "
321 "allowing this privilege only to documents that "
322 "actually need it, instead.</p>"),
323 from_utf8(conv_command));
324 frontend::Alert::error(_("Security Warning"),
325 shellescape_warning , false);
326 } else if (!conv.latex())
327 use_shell_escape = false;
328 if (!conv.need_auth() && !use_shell_escape)
330 size_t const token_pos = conv_command.find("$$");
331 bool const has_token = token_pos != string::npos;
332 string const command = use_shell_escape && !has_shell_escape
333 ? (has_token ? conv_command.insert(token_pos, "-shell-escape ")
334 : conv_command.append(" -shell-escape"))
336 docstring const security_warning = (use_shell_escape
337 ? bformat(_("<p>The following LaTeX backend has been requested "
338 "to allow execution of external programs:</p>"
339 "<center><p><tt>%1$s</tt></p></center>"
340 "<p>The external programs can execute arbitrary commands on "
341 "your system, including dangerous ones, if instructed to do "
342 "so by a maliciously crafted LyX document.</p>"),
344 : bformat(_("<p>The requested operation requires the use of a "
345 "converter from %2$s to %3$s:</p>"
346 "<blockquote><p><tt>%1$s</tt></p></blockquote>"
347 "<p>This external program can execute arbitrary commands on "
348 "your system, including dangerous ones, if instructed to do "
349 "so by a maliciously crafted LyX document.</p>"),
350 from_utf8(command), from_utf8(conv.from()),
351 from_utf8(conv.to())));
352 if (lyxrc.use_converter_needauth_forbidden && !use_shell_escape) {
353 frontend::Alert::error(
354 _("An external converter is disabled for security reasons"),
355 security_warning + _(
356 "<p><b>Your current preference settings forbid its execution.</b></p>"
357 "<p>(To change this setting, go to <i>Preferences ▹ File "
358 "Handling ▹ Converters</i> and uncheck <i>Security ▹ "
359 "Forbid needauth converters</i>.)"), false);
362 if (!lyxrc.use_converter_needauth && !use_shell_escape)
364 docstring const security_title = use_shell_escape
365 ? _("A LaTeX backend requires your authorization")
366 : _("An external converter requires your authorization");
368 docstring const security_warning2 = security_warning + (use_shell_escape
369 ? _("<p>Should LaTeX backends be allowed to run external "
370 "programs?</p><p><b>Allow them only if you trust the "
371 "origin/sender of the LyX document!</b></p>")
372 : _("<p>Would you like to run this converter?</p>"
373 "<p><b>Only run if you trust the origin/sender of the LyX "
374 "document!</b></p>"));
375 docstring const no = use_shell_escape
376 ? _("Do ¬ allow") : _("Do ¬ run");
377 docstring const yes = use_shell_escape ? _("A&llow") : _("&Run");
378 docstring const always = use_shell_escape
379 ? _("&Always allow for this document")
380 : _("&Always run for this document");
381 if (!doc_fname.empty()) {
382 LYXERR(Debug::FILES, "looking up: " << doc_fname);
383 bool authorized = use_shell_escape
384 ? theSession().shellescapeFiles().findAuth(doc_fname)
385 : theSession().authFiles().find(doc_fname);
387 choice = frontend::Alert::prompt(security_title,
389 0, 0, no, yes, always);
391 if (use_shell_escape)
392 theSession().shellescapeFiles().insert(doc_fname, true);
394 theSession().authFiles().insert(doc_fname);
400 choice = frontend::Alert::prompt(security_title,
408 Converters::RetVal Converters::convert(Buffer const * buffer,
409 FileName const & from_file, FileName const & to_file,
410 FileName const & orig_from,
411 string const & from_format, string const & to_format,
412 ErrorList & errorList, int conversionflags, bool includeall)
414 if (from_format == to_format)
415 return move(from_format, from_file, to_file, false) ?
418 if ((conversionflags & try_cache) &&
419 ConverterCache::get().inCache(orig_from, to_format))
420 return ConverterCache::get().copy(orig_from, to_format, to_file) ?
423 Graph::EdgePath edgepath = getPath(from_format, to_format);
424 if (edgepath.empty()) {
425 if (conversionflags & try_default) {
426 // if no special converter defined, then we take the
427 // default one from ImageMagic.
428 string const from_ext = from_format.empty() ?
429 getExtension(from_file.absFileName()) :
430 theFormats().extension(from_format);
431 string const to_ext = theFormats().extension(to_format);
432 string const command =
434 quoteName(libFileSearch("scripts", "convertDefault.py").toFilesystemEncoding()) +
435 ' ' + from_ext + ' ' +
436 quoteName(from_file.toFilesystemEncoding()) +
438 quoteName(to_file.toFilesystemEncoding());
439 LYXERR(Debug::FILES, "No converter defined! "
440 "I use convertDefault.py:\n\t" << command);
442 Systemcall::Starttype starttype =
443 (buffer && buffer->isClone()) ?
444 Systemcall::WaitLoop : Systemcall::Wait;
445 int const exitval = one.startscript(starttype, command,
446 buffer ? buffer->filePath() : string(),
447 buffer ? buffer->layoutPos() : string());
448 if (exitval == Systemcall::KILLED) {
449 frontend::Alert::warning(
450 _("Converter killed"),
451 bformat(_("The following converter was killed by the user.\n %1$s\n"),
452 from_utf8(command)));
455 if (to_file.isReadableFile()) {
456 if (conversionflags & try_cache)
457 ConverterCache::get().add(orig_from,
463 // only warn once per session and per file type
464 static std::map<string, string> warned;
465 if (warned.find(from_format) != warned.end() && warned.find(from_format)->second == to_format) {
468 warned.insert(make_pair(from_format, to_format));
470 Alert::error(_("Cannot convert file"),
471 bformat(_("No information for converting %1$s "
472 "format files to %2$s.\n"
473 "Define a converter in the preferences."),
474 from_ascii(from_format), from_ascii(to_format)));
478 // buffer can only be null for importing, and then runparams is not
480 OutputParams runparams(buffer ? &buffer->params().encoding() : nullptr);
481 runparams.flavor = getFlavor(edgepath, buffer);
484 BufferParams const & bp = buffer->params();
485 runparams.use_japanese =
486 (bp.bufferFormat() == "latex"
487 || suffixIs(bp.bufferFormat(), "-ja"))
488 && bp.encoding().package() == Encoding::japanese;
489 runparams.use_indices = bp.use_indices;
490 runparams.bibtex_command = bp.bibtexCommand(true);
491 runparams.index_command = (bp.index_command == "default") ?
492 string() : bp.index_command;
493 runparams.document_language = bp.language->lang();
494 // Some macros rely on font encoding
495 runparams.main_fontenc = bp.main_font_encoding();
496 runparams.only_childbibs = !bp.useBiblatex()
498 && bp.multibib == "child";
499 runparams.includeall = includeall;
502 // Some converters (e.g. lilypond) can only output files to the
503 // current directory, so we need to change the current directory.
504 // This has the added benefit that all other files that may be
505 // generated by the converter are deleted when LyX closes and do not
506 // clutter the real working directory.
507 // FIXME: This does not work if path is an UNC path on windows
509 string const path(onlyPath(from_file.absFileName()));
510 // Prevent the compiler from optimizing away p
514 // empty the error list before any new conversion takes place.
517 bool run_latex = false;
518 string from_base = changeExtension(from_file.absFileName(), "");
519 string to_base = changeExtension(to_file.absFileName(), "");
521 FileName outfile = from_file;
522 for (auto const & edge : edgepath) {
523 Converter const & conv = converterlist_[edge];
524 bool dummy = conv.To()->dummy() && conv.to() != "program";
526 LYXERR(Debug::FILES, "Converting from "
527 << conv.from() << " to " << conv.to());
530 outfile = FileName(conv.result_file().empty()
531 ? changeExtension(from_file.absFileName(), conv.To()->extension())
532 : addName(subst(conv.result_dir(),
533 token_base, from_base),
534 subst(conv.result_file(),
535 token_base, onlyFileName(from_base))));
537 // if input and output files are equal, we use a
538 // temporary file as intermediary (JMarc)
539 FileName real_outfile;
540 if (!conv.result_file().empty())
541 real_outfile = FileName(changeExtension(from_file.absFileName(),
542 conv.To()->extension()));
543 if (outfile == infile) {
544 real_outfile = infile;
545 // when importing, a buffer does not necessarily exist
547 outfile = FileName(addName(buffer->temppath(), "tmpfile.out"));
549 outfile = FileName(addName(package().temp_dir().absFileName(),
553 if (buffer && buffer->params().use_minted
554 && lyxrc.pygmentize_command.empty() && conv.latex()) {
556 // Warn only if listings insets are actually used
557 for (Paragraph const & par : buffer->paragraphs()) {
558 InsetList const & insets = par.insetList();
559 pos_type lstpos = insets.find(LISTINGS_CODE, 0);
560 pos_type incpos = insets.find(INCLUDE_CODE, 0);
562 InsetInclude const * include =
563 static_cast<InsetInclude *>
564 (insets.get(incpos));
565 if (include->params().getCmdName() !=
570 if (lstpos >= 0 || incpos >= 0) {
576 Alert::warning(_("Pygments driver command not found!"),
577 _("The driver command necessary to use the minted package\n"
578 "(pygmentize) has not been found. Make sure you have\n"
579 "the python-pygments module installed or, if the driver\n"
580 "is named differently, to add the following line to the\n"
581 "document preamble:\n\n"
582 "\\AtBeginDocument{\\renewcommand{\\MintedPygmentize}{driver}}\n\n"
583 "where 'driver' is name of the driver command."));
587 if (!checkAuth(conv, buffer ? buffer->absFileName() : string(),
588 buffer && buffer->params().shell_escape))
592 // We are not importing, we have a buffer
593 LASSERT(buffer, return FAILURE);
595 string command = conv.command();
596 command = subst(command, token_from, "");
597 command = subst(command, token_latex_encoding,
598 buffer->params().encoding().latexName());
599 if (buffer->params().shell_escape
600 && !contains(command, "-shell-escape"))
601 command += " -shell-escape ";
602 LYXERR(Debug::FILES, "Running " << command);
604 // Check changed return value here.
605 RetVal const retval = runLaTeX(*buffer, command, runparams, errorList);
606 if (retval != SUCCESS)
609 if (conv.need_aux() && !run_latex) {
610 // We are not importing, we have a buffer
611 LASSERT(buffer, return FAILURE);
613 switch (runparams.flavor) {
614 case Flavor::DviLuaTeX:
615 command = dvilualatex_command_;
618 command = lualatex_command_;
620 case Flavor::PdfLaTeX:
621 command = pdflatex_command_;
624 command = xelatex_command_;
627 command = latex_command_;
630 if (!command.empty()) {
631 LYXERR(Debug::FILES, "Running "
633 << " to update aux file");
635 // Check changed return value here.
636 RetVal const retval = runLaTeX(*buffer, command, runparams, errorList);
637 if (retval != SUCCESS)
643 string const infile2 =
644 to_utf8(makeRelPath(from_utf8(infile.absFileName()), from_utf8(path)));
645 string const outfile2 =
646 to_utf8(makeRelPath(from_utf8(outfile.absFileName()), from_utf8(path)));
648 string command = conv.command();
649 BufferParams const & bparams = buffer ? buffer->params() : defaultBufferParams();
650 command = subst(command, token_from, quoteName(infile2));
651 command = subst(command, token_base, quoteName(from_base));
652 command = subst(command, token_to, quoteName(outfile2));
653 command = subst(command, token_path, quoteName(onlyPath(infile.absFileName())));
654 command = subst(command, token_orig_path, quoteName(onlyPath(orig_from.absFileName())));
655 command = subst(command, token_orig_from, quoteName(onlyFileName(orig_from.absFileName())));
656 command = subst(command, token_textclass, quoteName(bparams.documentClass().name()));
657 string modules = bparams.getModules().asString();
658 // FIXME: remove when SystemCall uses QProcess with the list API.
659 // Currently the QProcess parser is not able to encode an
660 // empty argument as ""; work around this by passing a
661 // single comma, that will be interpreted as a list of two
662 // empty module names.
665 command = subst(command, token_modules, quoteName(modules));
666 command = subst(command, token_encoding, quoteName(bparams.encoding().iconvName()));
667 command = subst(command, token_python, os::python());
669 if (!conv.parselog().empty())
670 command += " 2> " + quoteName(infile2 + ".out");
672 // it is not actually not necessary to test for buffer here,
673 // but it pleases coverity.
674 if (buffer && conv.from() == "dvi" && conv.to() == "ps")
675 command = add_options(command,
676 buffer->params().dvips_options());
677 else if (buffer && conv.from() == "dvi" && prefixIs(conv.to(), "pdf"))
678 command = add_options(command,
679 dvipdfm_options(buffer->params()));
681 LYXERR(Debug::FILES, "Calling " << command);
683 buffer->message(_("Executing command: ")
684 + from_utf8(command));
689 res = one.startscript(Systemcall::DontWait,
690 to_filesystem8bit(from_utf8(command)),
691 buffer ? buffer->filePath() : string(),
692 buffer ? buffer->layoutPos() : string());
693 // We're not waiting for the result, so we can't do anything
696 Systemcall::Starttype starttype =
697 (buffer && buffer->isClone()) ?
698 Systemcall::WaitLoop : Systemcall::Wait;
699 res = one.startscript(starttype,
700 to_filesystem8bit(from_utf8(command)),
701 buffer ? buffer->filePath()
703 buffer ? buffer->layoutPos()
705 if (res == Systemcall::KILLED) {
706 frontend::Alert::warning(
707 _("Converter killed"),
708 bformat(_("The following converter was killed by the user.\n %1$s\n"),
709 from_utf8(command)));
713 if (!real_outfile.empty()) {
714 Mover const & mover = getMover(conv.to());
715 if (!mover.rename(outfile, real_outfile))
718 LYXERR(Debug::FILES, "renaming file " << outfile
719 << " to " << real_outfile);
720 // Finally, don't forget to tell any future
721 // converters to use the renamed file...
722 outfile = real_outfile;
725 if (!conv.parselog().empty()) {
726 string const logfile = infile2 + ".log";
727 string const command2 = conv.parselog() +
728 " < " + quoteName(infile2 + ".out") +
729 " > " + quoteName(logfile);
730 res = one.startscript(starttype,
731 to_filesystem8bit(from_utf8(command2)),
732 buffer ? buffer->filePath() : string(),
733 buffer ? buffer->layoutPos() : string());
734 if (res == Systemcall::KILLED) {
735 frontend::Alert::warning(
736 _("Converter killed"),
737 bformat(_("The following converter was killed by the user.\n %1$s\n"),
738 from_utf8(command)));
741 if (buffer && !scanLog(*buffer, command, makeAbsPath(logfile, path), errorList))
747 if (res == Systemcall::KILLED) {
748 Alert::information(_("Process Killed"),
749 bformat(_("The conversion process was killed while running:\n%1$s"),
750 wrapParas(from_utf8(command))));
753 if (res == Systemcall::TIMEOUT) {
754 Alert::information(_("Process Timed Out"),
755 bformat(_("The conversion process:\n%1$s\ntimed out before completing."),
756 wrapParas(from_utf8(command))));
759 if (conv.to() == "program") {
760 Alert::error(_("Build errors"),
761 _("There were errors during the build process."));
763 // FIXME: this should go out of here. For example, here we cannot say if
764 // it is a document (.lyx) or something else. Same goes for elsewhere.
765 Alert::error(_("Cannot convert file"),
766 bformat(_("An error occurred while running:\n%1$s"),
767 wrapParas(from_utf8(command))));
774 Converter const & conv = converterlist_[edgepath.back()];
775 if (conv.To()->dummy())
778 if (!conv.result_dir().empty()) {
779 // The converter has put the file(s) in a directory.
780 // In this case we ignore the given to_file.
781 if (from_base != to_base) {
782 string const from = subst(conv.result_dir(),
783 token_base, from_base);
784 string const to = subst(conv.result_dir(),
785 token_base, to_base);
786 Mover const & mover = getMover(conv.from());
787 if (!mover.rename(FileName(from), FileName(to))) {
788 Alert::error(_("Cannot convert file"),
789 bformat(_("Could not move a temporary directory from %1$s to %2$s."),
790 from_utf8(from), from_utf8(to)));
796 if (conversionflags & try_cache)
797 ConverterCache::get().add(orig_from, to_format, outfile);
798 return move(conv.to(), outfile, to_file, conv.latex()) ? SUCCESS : FAILURE;
803 bool Converters::move(string const & fmt,
804 FileName const & from, FileName const & to, bool copy)
809 bool no_errors = true;
810 string const path = onlyPath(from.absFileName());
811 string const base = onlyFileName(removeExtension(from.absFileName()));
812 string const to_base = removeExtension(to.absFileName());
813 string const to_extension = getExtension(to.absFileName());
815 support::FileNameList const files = FileName(path).dirList(getExtension(from.absFileName()));
816 for (auto const & f : files) {
817 string const from2 = f.absFileName();
818 string const file2 = onlyFileName(from2);
819 if (prefixIs(file2, base)) {
820 string const to2 = changeExtension(
821 to_base + file2.substr(base.length()),
823 LYXERR(Debug::FILES, "moving " << from2 << " to " << to2);
825 Mover const & mover = getMover(fmt);
826 bool const moved = copy
827 ? mover.copy(f, FileName(to2))
828 : mover.rename(f, FileName(to2));
829 if (!moved && no_errors) {
830 Alert::error(_("Cannot convert file"),
832 _("Could not copy a temporary file from %1$s to %2$s.") :
833 _("Could not move a temporary file from %1$s to %2$s."),
834 from_utf8(from2), from_utf8(to2)));
843 bool Converters::formatIsUsed(string const & format) const
845 for (auto const & cvt : converterlist_) {
846 if (cvt.from() == format || cvt.to() == format)
853 bool Converters::scanLog(Buffer const & buffer, string const & /*command*/,
854 FileName const & filename, ErrorList & errorList)
856 OutputParams runparams(nullptr);
857 runparams.flavor = Flavor::LaTeX;
858 LaTeX latex("", runparams, filename);
860 int const result = latex.scanLogFile(terr);
862 if (result & LaTeX::ERRORS)
863 buffer.bufferErrors(terr, errorList);
869 Converters::RetVal Converters::runLaTeX(Buffer const & buffer, string const & command,
870 OutputParams const & runparams, ErrorList & errorList)
872 buffer.setBusy(true);
873 buffer.message(_("Running LaTeX..."));
875 // do the LaTeX run(s)
876 string const name = buffer.latexName();
877 LaTeX latex(command, runparams, makeAbsPath(name),
878 buffer.filePath(), buffer.layoutPos(),
879 buffer.isClone(), buffer.freshStartRequired());
881 // The connection closes itself at the end of the scope when latex is
882 // destroyed. One cannot close (and destroy) buffer while the converter is
884 latex.message.connect([&buffer](docstring const & msg){
887 int const result = latex.run(terr);
889 if (result == Systemcall::KILLED || result == Systemcall::TIMEOUT) {
890 Alert::error(_("Export canceled"),
891 _("The export process was terminated by the user."));
895 if (result & LaTeX::ERRORS)
896 buffer.bufferErrors(terr, errorList);
898 if ((result & LaTeX::UNDEF_CIT) || (result & LaTeX::UNDEF_UNKNOWN_REF)) {
899 buffer.bufferRefs(terr, errorList);
900 if (errorList.empty())
901 errorList.push_back(ErrorItem(_("Undefined reference"),
902 _("Undefined references or citations were found during the build.\n"
903 "Please check the warnings in the LaTeX log (Document > LaTeX Log)."),
907 if (!errorList.empty()) {
908 // We will show the LaTeX Errors GUI later which contains
909 // specific error messages so it would be repetitive to give
910 // e.g. the "finished with an error" dialog in addition.
912 else if (result & LaTeX::NO_LOGFILE) {
913 docstring const str =
914 bformat(_("LaTeX did not run successfully. "
915 "Additionally, LyX could not locate "
916 "the LaTeX log %1$s."), from_utf8(name));
917 Alert::error(_("LaTeX failed"), str);
918 } else if (result & LaTeX::NONZERO_ERROR) {
919 docstring const str =
920 bformat(_( "The external program\n%1$s\n"
921 "finished with an error. "
922 "It is recommended you fix the cause of the external "
923 "program's error (check the logs). "), from_utf8(command));
924 Alert::error(_("LaTeX failed"), str);
925 } else if (result & LaTeX::NO_OUTPUT) {
926 Alert::warning(_("Output is empty"),
927 _("No output file was generated."));
930 buffer.setBusy(false);
932 int const ERROR_MASK =
936 LaTeX::UNDEF_UNKNOWN_REF |
939 return (result & ERROR_MASK) == 0 ? SUCCESS : FAILURE;
944 void Converters::buildGraph()
946 // clear graph's data structures
947 G_.init(theFormats().size());
948 // each of the converters knows how to convert one format to another
949 // so, for each of them, we create an arrow on the graph, going from
950 // the one to the other
951 for (auto const & cvt : converterlist_) {
952 int const from = theFormats().getNumber(cvt.from());
953 int const to = theFormats().getNumber(cvt.to());
954 LASSERT(from >= 0, continue);
955 LASSERT(to >= 0, continue);
956 G_.addEdge(from, to);
961 FormatList const Converters::intToFormat(vector<int> const & input)
963 FormatList result(input.size());
965 vector<int>::const_iterator it = input.begin();
966 vector<int>::const_iterator const end = input.end();
967 FormatList::iterator rit = result.begin();
968 for ( ; it != end; ++it, ++rit) {
969 *rit = &theFormats().get(*it);
975 FormatList const Converters::getReachableTo(string const & target,
976 bool const clear_visited)
978 vector<int> const & reachablesto =
979 G_.getReachableTo(theFormats().getNumber(target), clear_visited);
981 return intToFormat(reachablesto);
985 FormatList const Converters::getReachable(string const & from,
986 bool const only_viewable, bool const clear_visited,
987 set<string> const & excludes)
989 set<int> excluded_numbers;
991 for (auto const & ex : excludes)
992 excluded_numbers.insert(theFormats().getNumber(ex));
994 vector<int> const & reachables =
995 G_.getReachable(theFormats().getNumber(from),
1000 return intToFormat(reachables);
1004 bool Converters::isReachable(string const & from, string const & to)
1006 return G_.isReachable(theFormats().getNumber(from),
1007 theFormats().getNumber(to));
1011 Graph::EdgePath Converters::getPath(string const & from, string const & to)
1013 return G_.getPath(theFormats().getNumber(from),
1014 theFormats().getNumber(to));
1018 FormatList Converters::importableFormats()
1020 vector<string> l = loaders();
1021 FormatList result = getReachableTo(l[0], true);
1022 vector<string>::const_iterator it = l.begin() + 1;
1023 vector<string>::const_iterator en = l.end();
1024 for (; it != en; ++it) {
1025 FormatList r = getReachableTo(*it, false);
1026 result.insert(result.end(), r.begin(), r.end());
1032 FormatList Converters::exportableFormats(bool only_viewable)
1034 vector<string> s = savers();
1035 FormatList result = getReachable(s[0], only_viewable, true);
1036 vector<string>::const_iterator it = s.begin() + 1;
1037 vector<string>::const_iterator en = s.end();
1038 for (; it != en; ++it) {
1039 FormatList r = getReachable(*it, only_viewable, false);
1040 result.insert(result.end(), r.begin(), r.end());
1046 vector<string> Converters::loaders() const
1050 v.push_back("text");
1051 v.push_back("textparagraph");
1056 vector<string> Converters::savers() const
1059 v.push_back("docbook");
1060 v.push_back("latex");
1061 v.push_back("literate");
1062 v.push_back("luatex");
1063 v.push_back("dviluatex");
1065 v.push_back("xhtml");
1066 v.push_back("pdflatex");
1067 v.push_back("platex");
1068 v.push_back("text");
1069 v.push_back("xetex");