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_(0), To_(0), latex_(false), xml_(false),
109 need_aux_(false), nice_(false), need_auth_(false)
113 void Converter::readFlags()
115 string flag_list(flags_);
116 while (!flag_list.empty()) {
117 string flag_name, flag_value;
118 flag_list = split(flag_list, flag_value, ',');
119 flag_value = split(flag_value, flag_name, '=');
120 if (flag_name == "latex") {
122 latex_flavor_ = flag_value.empty() ?
123 "latex" : flag_value;
124 } else if (flag_name == "xml")
126 else if (flag_name == "needaux") {
128 latex_flavor_ = flag_value.empty() ?
129 "latex" : flag_value;
130 } else if (flag_name == "resultdir")
131 result_dir_ = (flag_value.empty())
132 ? token_base : flag_value;
133 else if (flag_name == "resultfile")
134 result_file_ = flag_value;
135 else if (flag_name == "parselog")
136 parselog_ = flag_value;
137 else if (flag_name == "nice")
139 else if (flag_name == "needauth")
141 else if (flag_name == "hyperref-driver")
142 href_driver_ = flag_value;
144 if (!result_dir_.empty() && result_file_.empty())
145 result_file_ = "index." + theFormats().extension(to_);
146 //if (!contains(command, token_from))
151 Converter const * Converters::getConverter(string const & from,
152 string const & to) const
154 ConverterList::const_iterator const cit =
155 find_if(converterlist_.begin(), converterlist_.end(),
156 ConverterEqual(from, to));
157 if (cit != converterlist_.end())
164 int Converters::getNumber(string const & from, string const & to) const
166 ConverterList::const_iterator const cit =
167 find_if(converterlist_.begin(), converterlist_.end(),
168 ConverterEqual(from, to));
169 if (cit != converterlist_.end())
170 return distance(converterlist_.begin(), cit);
176 void Converters::add(string const & from, string const & to,
177 string const & command, string const & flags)
179 theFormats().add(from);
180 theFormats().add(to);
181 ConverterList::iterator it = find_if(converterlist_.begin(),
182 converterlist_.end(),
183 ConverterEqual(from , to));
185 Converter converter(from, to, command, flags);
186 if (it != converterlist_.end() && !flags.empty() && flags[0] == '*') {
188 converter.setCommand(command);
189 converter.setFlags(flags);
191 converter.readFlags();
193 // The latex_command is used to update the .aux file when running
194 // a converter that uses it.
195 if (converter.latex()) {
196 if (latex_command_.empty() ||
197 converter.latex_flavor() == "latex")
198 latex_command_ = subst(command, token_from, "");
199 if (dvilualatex_command_.empty() ||
200 converter.latex_flavor() == "dvilualatex")
201 dvilualatex_command_ = subst(command, token_from, "");
202 if (lualatex_command_.empty() ||
203 converter.latex_flavor() == "lualatex")
204 lualatex_command_ = subst(command, token_from, "");
205 if (pdflatex_command_.empty() ||
206 converter.latex_flavor() == "pdflatex")
207 pdflatex_command_ = subst(command, token_from, "");
208 if (xelatex_command_.empty() ||
209 converter.latex_flavor() == "xelatex")
210 xelatex_command_ = subst(command, token_from, "");
213 if (it == converterlist_.end()) {
214 converterlist_.push_back(converter);
216 converter.setFrom(it->From());
217 converter.setTo(it->To());
223 void Converters::erase(string const & from, string const & to)
225 ConverterList::iterator const it =
226 find_if(converterlist_.begin(),
227 converterlist_.end(),
228 ConverterEqual(from, to));
229 if (it != converterlist_.end())
230 converterlist_.erase(it);
234 // This method updates the pointers From and To in all the converters.
235 // The code is not very efficient, but it doesn't matter as the number
236 // of formats and converters is small.
237 // Furthermore, this method is called only on startup, or after
238 // adding/deleting a format in FormPreferences (the latter calls can be
239 // eliminated if the formats in the Formats class are stored using a map or
240 // a list (instead of a vector), but this will cause other problems).
241 void Converters::update(Formats const & formats)
243 ConverterList::iterator it = converterlist_.begin();
244 ConverterList::iterator end = converterlist_.end();
245 for (; it != end; ++it) {
246 it->setFrom(formats.getFormat(it->from()));
247 it->setTo(formats.getFormat(it->to()));
252 // This method updates the pointers From and To in the last converter.
253 // It is called when adding a new converter in FormPreferences
254 void Converters::updateLast(Formats const & formats)
256 if (converterlist_.begin() != converterlist_.end()) {
257 ConverterList::iterator it = converterlist_.end() - 1;
258 it->setFrom(formats.getFormat(it->from()));
259 it->setTo(formats.getFormat(it->to()));
264 OutputParams::FLAVOR Converters::getFlavor(Graph::EdgePath const & path,
265 Buffer const * buffer)
267 for (Graph::EdgePath::const_iterator cit = path.begin();
268 cit != path.end(); ++cit) {
269 Converter const & conv = converterlist_[*cit];
270 if (conv.latex() || conv.need_aux()) {
271 if (conv.latex_flavor() == "latex")
272 return OutputParams::LATEX;
273 if (conv.latex_flavor() == "xelatex")
274 return OutputParams::XETEX;
275 if (conv.latex_flavor() == "lualatex")
276 return OutputParams::LUATEX;
277 if (conv.latex_flavor() == "dvilualatex")
278 return OutputParams::DVILUATEX;
279 if (conv.latex_flavor() == "pdflatex")
280 return OutputParams::PDFLATEX;
283 return OutputParams::XML;
285 return buffer ? buffer->params().getOutputFlavor()
286 : OutputParams::LATEX;
290 string Converters::getHyperrefDriver(Graph::EdgePath const & path)
292 for (Graph::EdgePath::const_iterator cit = path.begin();
293 cit != path.end(); ++cit) {
294 Converter const & conv = converterlist_[*cit];
295 if (!conv.hyperref_driver().empty())
296 return conv.hyperref_driver();
302 bool Converters::checkAuth(Converter const & conv, string const & doc_fname,
303 bool use_shell_escape)
305 string conv_command = conv.command();
306 bool const has_shell_escape = contains(conv_command, "-shell-escape")
307 || contains(conv_command, "-enable-write18");
308 if (conv.latex() && has_shell_escape && !use_shell_escape) {
309 docstring const shellescape_warning =
310 bformat(_("<p>The following LaTeX backend has been "
311 "configured to allow execution of external programs "
312 "for any document:</p>"
313 "<center><p><tt>%1$s</tt></p></center>"
314 "<p>This is a dangerous configuration. Please, "
315 "consider using the support offered by LyX for "
316 "allowing this privilege only to documents that "
317 "actually need it, instead.</p>"),
318 from_utf8(conv_command));
319 frontend::Alert::error(_("Security Warning"),
320 shellescape_warning , false);
321 } else if (!conv.latex())
322 use_shell_escape = false;
323 if (!conv.need_auth() && !use_shell_escape)
325 size_t const token_pos = conv_command.find("$$");
326 bool const has_token = token_pos != string::npos;
327 string const command = use_shell_escape && !has_shell_escape
328 ? (has_token ? conv_command.insert(token_pos, "-shell-escape ")
329 : conv_command.append(" -shell-escape"))
331 docstring const security_warning = (use_shell_escape
332 ? bformat(_("<p>The following LaTeX backend has been requested "
333 "to allow execution of external programs:</p>"
334 "<center><p><tt>%1$s</tt></p></center>"
335 "<p>The external programs can execute arbitrary commands on "
336 "your system, including dangerous ones, if instructed to do "
337 "so by a maliciously crafted LyX document.</p>"),
339 : bformat(_("<p>The requested operation requires the use of a "
340 "converter from %2$s to %3$s:</p>"
341 "<blockquote><p><tt>%1$s</tt></p></blockquote>"
342 "<p>This external program can execute arbitrary commands on "
343 "your system, including dangerous ones, if instructed to do "
344 "so by a maliciously crafted LyX document.</p>"),
345 from_utf8(command), from_utf8(conv.from()),
346 from_utf8(conv.to())));
347 if (lyxrc.use_converter_needauth_forbidden && !use_shell_escape) {
348 frontend::Alert::error(
349 _("An external converter is disabled for security reasons"),
350 security_warning + _(
351 "<p><b>Your current preference settings forbid its execution.</b></p>"
352 "<p>(To change this setting, go to <i>Preferences ▹ File "
353 "Handling ▹ Converters</i> and uncheck <i>Security ▹ "
354 "Forbid needauth converters</i>.)"), false);
357 if (!lyxrc.use_converter_needauth && !use_shell_escape)
359 docstring const security_title = use_shell_escape
360 ? _("A LaTeX backend requires your authorization")
361 : _("An external converter requires your authorization");
363 docstring const security_warning2 = security_warning + (use_shell_escape
364 ? _("<p>Should LaTeX backends be allowed to run external "
365 "programs?</p><p><b>Allow them only if you trust the "
366 "origin/sender of the LyX document!</b></p>")
367 : _("<p>Would you like to run this converter?</p>"
368 "<p><b>Only run if you trust the origin/sender of the LyX "
369 "document!</b></p>"));
370 docstring const no = use_shell_escape
371 ? _("Do ¬ allow") : _("Do ¬ run");
372 docstring const yes = use_shell_escape ? _("A&llow") : _("&Run");
373 docstring const always = use_shell_escape
374 ? _("&Always allow for this document")
375 : _("&Always run for this document");
376 if (!doc_fname.empty()) {
377 LYXERR(Debug::FILES, "looking up: " << doc_fname);
378 bool authorized = use_shell_escape
379 ? theSession().shellescapeFiles().findAuth(doc_fname)
380 : theSession().authFiles().find(doc_fname);
382 choice = frontend::Alert::prompt(security_title,
384 0, 0, no, yes, always);
386 if (use_shell_escape)
387 theSession().shellescapeFiles().insert(doc_fname, true);
389 theSession().authFiles().insert(doc_fname);
395 choice = frontend::Alert::prompt(security_title,
403 Converters::RetVal Converters::convert(Buffer const * buffer,
404 FileName const & from_file, FileName const & to_file,
405 FileName const & orig_from,
406 string const & from_format, string const & to_format,
407 ErrorList & errorList, int conversionflags)
409 if (from_format == to_format)
410 return move(from_format, from_file, to_file, false) ?
413 if ((conversionflags & try_cache) &&
414 ConverterCache::get().inCache(orig_from, to_format))
415 return ConverterCache::get().copy(orig_from, to_format, to_file) ?
418 Graph::EdgePath edgepath = getPath(from_format, to_format);
419 if (edgepath.empty()) {
420 if (conversionflags & try_default) {
421 // if no special converter defined, then we take the
422 // default one from ImageMagic.
423 string const from_ext = from_format.empty() ?
424 getExtension(from_file.absFileName()) :
425 theFormats().extension(from_format);
426 string const to_ext = theFormats().extension(to_format);
427 string const command =
429 quoteName(libFileSearch("scripts", "convertDefault.py").toFilesystemEncoding()) +
430 ' ' + from_ext + ' ' +
431 quoteName(from_file.toFilesystemEncoding()) +
433 quoteName(to_file.toFilesystemEncoding());
434 LYXERR(Debug::FILES, "No converter defined! "
435 "I use convertDefault.py:\n\t" << command);
437 Systemcall::Starttype starttype =
438 (buffer && buffer->isClone()) ?
439 Systemcall::WaitLoop : Systemcall::Wait;
440 int const exitval = one.startscript(starttype, command,
441 buffer ? buffer->filePath() : string(),
442 buffer ? buffer->layoutPos() : string());
443 if (exitval == Systemcall::KILLED) {
444 frontend::Alert::warning(
445 _("Converter killed"),
446 bformat(_("The following converter was killed by the user.\n %1$s\n"),
447 from_utf8(command)));
450 if (to_file.isReadableFile()) {
451 if (conversionflags & try_cache)
452 ConverterCache::get().add(orig_from,
458 // only warn once per session and per file type
459 static std::map<string, string> warned;
460 if (warned.find(from_format) != warned.end() && warned.find(from_format)->second == to_format) {
463 warned.insert(make_pair(from_format, to_format));
465 Alert::error(_("Cannot convert file"),
466 bformat(_("No information for converting %1$s "
467 "format files to %2$s.\n"
468 "Define a converter in the preferences."),
469 from_ascii(from_format), from_ascii(to_format)));
473 // buffer is only invalid for importing, and then runparams is not
475 OutputParams runparams(buffer ? &buffer->params().encoding() : 0);
476 runparams.flavor = getFlavor(edgepath, buffer);
479 runparams.use_japanese =
480 (buffer->params().bufferFormat() == "latex"
481 || suffixIs(buffer->params().bufferFormat(), "-ja"))
482 && buffer->params().encoding().package() == Encoding::japanese;
483 runparams.use_indices = buffer->params().use_indices;
484 runparams.bibtex_command = buffer->params().bibtexCommand();
485 runparams.index_command = (buffer->params().index_command == "default") ?
486 string() : buffer->params().index_command;
487 runparams.document_language = buffer->params().language->babel();
488 runparams.main_fontenc = buffer->params().main_font_encoding();
489 runparams.only_childbibs = !buffer->params().useBiblatex()
490 && !buffer->params().useBibtopic()
491 && buffer->params().multibib == "child";
494 // Some converters (e.g. lilypond) can only output files to the
495 // current directory, so we need to change the current directory.
496 // This has the added benefit that all other files that may be
497 // generated by the converter are deleted when LyX closes and do not
498 // clutter the real working directory.
499 // FIXME: This does not work if path is an UNC path on windows
501 string const path(onlyPath(from_file.absFileName()));
502 // Prevent the compiler from optimizing away p
506 // empty the error list before any new conversion takes place.
509 bool run_latex = false;
510 string from_base = changeExtension(from_file.absFileName(), "");
511 string to_base = changeExtension(to_file.absFileName(), "");
513 FileName outfile = from_file;
514 for (Graph::EdgePath::const_iterator cit = edgepath.begin();
515 cit != edgepath.end(); ++cit) {
516 Converter const & conv = converterlist_[*cit];
517 bool dummy = conv.To()->dummy() && conv.to() != "program";
519 LYXERR(Debug::FILES, "Converting from "
520 << conv.from() << " to " << conv.to());
523 outfile = FileName(conv.result_file().empty()
524 ? changeExtension(from_file.absFileName(), conv.To()->extension())
525 : addName(subst(conv.result_dir(),
526 token_base, from_base),
527 subst(conv.result_file(),
528 token_base, onlyFileName(from_base))));
530 // if input and output files are equal, we use a
531 // temporary file as intermediary (JMarc)
532 FileName real_outfile;
533 if (!conv.result_file().empty())
534 real_outfile = FileName(changeExtension(from_file.absFileName(),
535 conv.To()->extension()));
536 if (outfile == infile) {
537 real_outfile = infile;
538 // when importing, a buffer does not necessarily exist
540 outfile = FileName(addName(buffer->temppath(), "tmpfile.out"));
542 outfile = FileName(addName(package().temp_dir().absFileName(),
546 if (buffer && buffer->params().use_minted
547 && lyxrc.pygmentize_command.empty() && conv.latex()) {
549 // Warn only if listings insets are actually used
550 for (Paragraph const & par : buffer->paragraphs()) {
551 InsetList const & insets = par.insetList();
552 pos_type lstpos = insets.find(LISTINGS_CODE, 0);
553 pos_type incpos = insets.find(INCLUDE_CODE, 0);
555 InsetInclude const * include =
556 static_cast<InsetInclude *>
557 (insets.get(incpos));
558 if (include->params().getCmdName() !=
563 if (lstpos >= 0 || incpos >= 0) {
569 Alert::warning(_("Pygments driver command not found!"),
570 _("The driver command necessary to use the minted package\n"
571 "(pygmentize) has not been found. Make sure you have\n"
572 "the python-pygments module installed or, if the driver\n"
573 "is named differently, to add the following line to the\n"
574 "document preamble:\n\n"
575 "\\AtBeginDocument{\\renewcommand{\\MintedPygmentize}{driver}}\n\n"
576 "where 'driver' is name of the driver command."));
580 if (!checkAuth(conv, buffer ? buffer->absFileName() : string(),
581 buffer && buffer->params().shell_escape))
585 // We are not importing, we have a buffer
588 string command = conv.command();
589 command = subst(command, token_from, "");
590 command = subst(command, token_latex_encoding,
591 buffer->params().encoding().latexName());
592 if (buffer->params().shell_escape
593 && !contains(command, "-shell-escape"))
594 command += " -shell-escape ";
595 LYXERR(Debug::FILES, "Running " << command);
597 // Check changed return value here.
598 RetVal const retval = runLaTeX(*buffer, command, runparams, errorList);
599 if (retval != SUCCESS)
602 if (conv.need_aux() && !run_latex) {
603 // We are not importing, we have a buffer
606 switch (runparams.flavor) {
607 case OutputParams::DVILUATEX:
608 command = dvilualatex_command_;
610 case OutputParams::LUATEX:
611 command = lualatex_command_;
613 case OutputParams::PDFLATEX:
614 command = pdflatex_command_;
616 case OutputParams::XETEX:
617 command = xelatex_command_;
620 command = latex_command_;
623 if (!command.empty()) {
624 LYXERR(Debug::FILES, "Running "
626 << " to update aux file");
628 // Check changed return value here.
629 RetVal const retval = runLaTeX(*buffer, command, runparams, errorList);
630 if (retval != SUCCESS)
636 string const infile2 =
637 to_utf8(makeRelPath(from_utf8(infile.absFileName()), from_utf8(path)));
638 string const outfile2 =
639 to_utf8(makeRelPath(from_utf8(outfile.absFileName()), from_utf8(path)));
641 string command = conv.command();
642 command = subst(command, token_from, quoteName(infile2));
643 command = subst(command, token_base, quoteName(from_base));
644 command = subst(command, token_to, quoteName(outfile2));
645 command = subst(command, token_path, quoteName(onlyPath(infile.absFileName())));
646 command = subst(command, token_orig_path, quoteName(onlyPath(orig_from.absFileName())));
647 command = subst(command, token_orig_from, quoteName(onlyFileName(orig_from.absFileName())));
648 command = subst(command, token_encoding, buffer ? buffer->params().encoding().iconvName() : string());
650 if (!conv.parselog().empty())
651 command += " 2> " + quoteName(infile2 + ".out");
653 // it is not actually not necessary to test for buffer here,
654 // but it pleases coverity.
655 if (buffer && conv.from() == "dvi" && conv.to() == "ps")
656 command = add_options(command,
657 buffer->params().dvips_options());
658 else if (buffer && conv.from() == "dvi" && prefixIs(conv.to(), "pdf"))
659 command = add_options(command,
660 dvipdfm_options(buffer->params()));
662 LYXERR(Debug::FILES, "Calling " << command);
664 buffer->message(_("Executing command: ")
665 + from_utf8(command));
670 res = one.startscript(Systemcall::DontWait,
671 to_filesystem8bit(from_utf8(command)),
672 buffer ? buffer->filePath() : string(),
673 buffer ? buffer->layoutPos() : string());
674 // We're not waiting for the result, so we can't do anything
677 Systemcall::Starttype starttype =
678 (buffer && buffer->isClone()) ?
679 Systemcall::WaitLoop : Systemcall::Wait;
680 res = one.startscript(starttype,
681 to_filesystem8bit(from_utf8(command)),
682 buffer ? buffer->filePath()
684 buffer ? buffer->layoutPos()
686 if (res == Systemcall::KILLED) {
687 frontend::Alert::warning(
688 _("Converter killed"),
689 bformat(_("The following converter was killed by the user.\n %1$s\n"),
690 from_utf8(command)));
694 if (!real_outfile.empty()) {
695 Mover const & mover = getMover(conv.to());
696 if (!mover.rename(outfile, real_outfile))
699 LYXERR(Debug::FILES, "renaming file " << outfile
700 << " to " << real_outfile);
701 // Finally, don't forget to tell any future
702 // converters to use the renamed file...
703 outfile = real_outfile;
706 if (!conv.parselog().empty()) {
707 string const logfile = infile2 + ".log";
708 string const command2 = conv.parselog() +
709 " < " + quoteName(infile2 + ".out") +
710 " > " + quoteName(logfile);
711 res = one.startscript(starttype,
712 to_filesystem8bit(from_utf8(command2)),
714 buffer->layoutPos());
715 if (res == Systemcall::KILLED) {
716 frontend::Alert::warning(
717 _("Converter killed"),
718 bformat(_("The following converter was killed by the user.\n %1$s\n"),
719 from_utf8(command)));
722 if (!scanLog(*buffer, command, makeAbsPath(logfile, path), errorList))
728 if (res == Systemcall::KILLED) {
729 Alert::information(_("Process Killed"),
730 bformat(_("The conversion process was killed while running:\n%1$s"),
731 wrapParas(from_utf8(command))));
734 if (res == Systemcall::TIMEOUT) {
735 Alert::information(_("Process Timed Out"),
736 bformat(_("The conversion process:\n%1$s\ntimed out before completing."),
737 wrapParas(from_utf8(command))));
740 if (conv.to() == "program") {
741 Alert::error(_("Build errors"),
742 _("There were errors during the build process."));
744 // FIXME: this should go out of here. For example, here we cannot say if
745 // it is a document (.lyx) or something else. Same goes for elsewhere.
746 Alert::error(_("Cannot convert file"),
747 bformat(_("An error occurred while running:\n%1$s"),
748 wrapParas(from_utf8(command))));
755 Converter const & conv = converterlist_[edgepath.back()];
756 if (conv.To()->dummy())
759 if (!conv.result_dir().empty()) {
760 // The converter has put the file(s) in a directory.
761 // In this case we ignore the given to_file.
762 if (from_base != to_base) {
763 string const from = subst(conv.result_dir(),
764 token_base, from_base);
765 string const to = subst(conv.result_dir(),
766 token_base, to_base);
767 Mover const & mover = getMover(conv.from());
768 if (!mover.rename(FileName(from), FileName(to))) {
769 Alert::error(_("Cannot convert file"),
770 bformat(_("Could not move a temporary directory from %1$s to %2$s."),
771 from_utf8(from), from_utf8(to)));
777 if (conversionflags & try_cache)
778 ConverterCache::get().add(orig_from, to_format, outfile);
779 return move(conv.to(), outfile, to_file, conv.latex()) ? SUCCESS : FAILURE;
784 bool Converters::move(string const & fmt,
785 FileName const & from, FileName const & to, bool copy)
790 bool no_errors = true;
791 string const path = onlyPath(from.absFileName());
792 string const base = onlyFileName(removeExtension(from.absFileName()));
793 string const to_base = removeExtension(to.absFileName());
794 string const to_extension = getExtension(to.absFileName());
796 support::FileNameList const files = FileName(path).dirList(getExtension(from.absFileName()));
797 for (support::FileNameList::const_iterator it = files.begin();
798 it != files.end(); ++it) {
799 string const from2 = it->absFileName();
800 string const file2 = onlyFileName(from2);
801 if (prefixIs(file2, base)) {
802 string const to2 = changeExtension(
803 to_base + file2.substr(base.length()),
805 LYXERR(Debug::FILES, "moving " << from2 << " to " << to2);
807 Mover const & mover = getMover(fmt);
808 bool const moved = copy
809 ? mover.copy(*it, FileName(to2))
810 : mover.rename(*it, FileName(to2));
811 if (!moved && no_errors) {
812 Alert::error(_("Cannot convert file"),
814 _("Could not copy a temporary file from %1$s to %2$s.") :
815 _("Could not move a temporary file from %1$s to %2$s."),
816 from_utf8(from2), from_utf8(to2)));
825 bool Converters::formatIsUsed(string const & format)
827 ConverterList::const_iterator cit = converterlist_.begin();
828 ConverterList::const_iterator end = converterlist_.end();
829 for (; cit != end; ++cit) {
830 if (cit->from() == format || cit->to() == format)
837 bool Converters::scanLog(Buffer const & buffer, string const & /*command*/,
838 FileName const & filename, ErrorList & errorList)
840 OutputParams runparams(0);
841 runparams.flavor = OutputParams::LATEX;
842 LaTeX latex("", runparams, filename);
844 int const result = latex.scanLogFile(terr);
846 if (result & LaTeX::ERRORS)
847 buffer.bufferErrors(terr, errorList);
853 Converters::RetVal Converters::runLaTeX(Buffer const & buffer, string const & command,
854 OutputParams const & runparams, ErrorList & errorList)
856 buffer.setBusy(true);
857 buffer.message(_("Running LaTeX..."));
859 // do the LaTeX run(s)
860 string const name = buffer.latexName();
861 LaTeX latex(command, runparams, FileName(makeAbsPath(name)),
862 buffer.filePath(), buffer.layoutPos(),
863 buffer.isClone(), buffer.lastPreviewError());
865 // The connection closes itself at the end of the scope when latex is
866 // destroyed. One cannot close (and destroy) buffer while the converter is
868 latex.message.connect([&buffer](docstring const & msg){
871 int const result = latex.run(terr);
873 if (result == Systemcall::KILLED) {
874 Alert::error(_("Export canceled"),
875 _("The export process was terminated by the user."));
879 if (result & LaTeX::ERRORS)
880 buffer.bufferErrors(terr, errorList);
882 if (!errorList.empty()) {
883 // We will show the LaTeX Errors GUI later which contains
884 // specific error messages so it would be repetitive to give
885 // e.g. the "finished with an error" dialog in addition.
887 else if (result & LaTeX::NO_LOGFILE) {
888 docstring const str =
889 bformat(_("LaTeX did not run successfully. "
890 "Additionally, LyX could not locate "
891 "the LaTeX log %1$s."), from_utf8(name));
892 Alert::error(_("LaTeX failed"), str);
893 } else if (result & LaTeX::NONZERO_ERROR) {
894 docstring const str =
895 bformat(_( "The external program\n%1$s\n"
896 "finished with an error. "
897 "It is recommended you fix the cause of the external "
898 "program's error (check the logs). "), from_utf8(command));
899 Alert::error(_("LaTeX failed"), str);
900 } else if (result & LaTeX::NO_OUTPUT) {
901 Alert::warning(_("Output is empty"),
902 _("No output file was generated."));
905 buffer.setBusy(false);
907 int const ERROR_MASK =
912 return (result & ERROR_MASK) == 0 ? SUCCESS : FAILURE;
917 void Converters::buildGraph()
919 // clear graph's data structures
920 G_.init(theFormats().size());
921 // each of the converters knows how to convert one format to another
922 // so, for each of them, we create an arrow on the graph, going from
923 // the one to the other
924 ConverterList::iterator it = converterlist_.begin();
925 ConverterList::iterator const end = converterlist_.end();
926 for (; it != end ; ++it) {
927 int const from = theFormats().getNumber(it->from());
928 int const to = theFormats().getNumber(it->to());
929 LASSERT(from >= 0, continue);
930 LASSERT(to >= 0, continue);
931 G_.addEdge(from, to);
936 FormatList const Converters::intToFormat(vector<int> const & input)
938 FormatList result(input.size());
940 vector<int>::const_iterator it = input.begin();
941 vector<int>::const_iterator const end = input.end();
942 FormatList::iterator rit = result.begin();
943 for ( ; it != end; ++it, ++rit) {
944 *rit = &theFormats().get(*it);
950 FormatList const Converters::getReachableTo(string const & target,
951 bool const clear_visited)
953 vector<int> const & reachablesto =
954 G_.getReachableTo(theFormats().getNumber(target), clear_visited);
956 return intToFormat(reachablesto);
960 FormatList const Converters::getReachable(string const & from,
961 bool const only_viewable, bool const clear_visited,
962 set<string> const & excludes)
964 set<int> excluded_numbers;
966 set<string>::const_iterator sit = excludes.begin();
967 set<string>::const_iterator const end = excludes.end();
968 for (; sit != end; ++sit)
969 excluded_numbers.insert(theFormats().getNumber(*sit));
971 vector<int> const & reachables =
972 G_.getReachable(theFormats().getNumber(from),
977 return intToFormat(reachables);
981 bool Converters::isReachable(string const & from, string const & to)
983 return G_.isReachable(theFormats().getNumber(from),
984 theFormats().getNumber(to));
988 Graph::EdgePath Converters::getPath(string const & from, string const & to)
990 return G_.getPath(theFormats().getNumber(from),
991 theFormats().getNumber(to));
995 FormatList Converters::importableFormats()
997 vector<string> l = loaders();
998 FormatList result = getReachableTo(l[0], true);
999 vector<string>::const_iterator it = l.begin() + 1;
1000 vector<string>::const_iterator en = l.end();
1001 for (; it != en; ++it) {
1002 FormatList r = getReachableTo(*it, false);
1003 result.insert(result.end(), r.begin(), r.end());
1009 FormatList Converters::exportableFormats(bool only_viewable)
1011 vector<string> s = savers();
1012 FormatList result = getReachable(s[0], only_viewable, true);
1013 vector<string>::const_iterator it = s.begin() + 1;
1014 vector<string>::const_iterator en = s.end();
1015 for (; it != en; ++it) {
1016 FormatList r = getReachable(*it, only_viewable, false);
1017 result.insert(result.end(), r.begin(), r.end());
1023 vector<string> Converters::loaders() const
1027 v.push_back("text");
1028 v.push_back("textparagraph");
1033 vector<string> Converters::savers() const
1036 v.push_back("docbook");
1037 v.push_back("latex");
1038 v.push_back("literate");
1039 v.push_back("luatex");
1040 v.push_back("dviluatex");
1042 v.push_back("xhtml");
1043 v.push_back("pdflatex");
1044 v.push_back("platex");
1045 v.push_back("text");
1046 v.push_back("xetex");