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 BufferParams const & bp = buffer->params();
480 runparams.use_japanese =
481 (bp.bufferFormat() == "latex"
482 || suffixIs(bp.bufferFormat(), "-ja"))
483 && bp.encoding().package() == Encoding::japanese;
484 runparams.use_indices = bp.use_indices;
485 runparams.bibtex_command = bp.bibtexCommand();
486 runparams.index_command = (bp.index_command == "default") ?
487 string() : bp.index_command;
488 runparams.document_language = bp.language->babel();
489 // Some macros rely on font encoding
490 runparams.main_fontenc = bp.main_font_encoding();
491 runparams.only_childbibs = !bp.useBiblatex()
493 && bp.multibib == "child";
496 // Some converters (e.g. lilypond) can only output files to the
497 // current directory, so we need to change the current directory.
498 // This has the added benefit that all other files that may be
499 // generated by the converter are deleted when LyX closes and do not
500 // clutter the real working directory.
501 // FIXME: This does not work if path is an UNC path on windows
503 string const path(onlyPath(from_file.absFileName()));
504 // Prevent the compiler from optimizing away p
508 // empty the error list before any new conversion takes place.
511 bool run_latex = false;
512 string from_base = changeExtension(from_file.absFileName(), "");
513 string to_base = changeExtension(to_file.absFileName(), "");
515 FileName outfile = from_file;
516 for (Graph::EdgePath::const_iterator cit = edgepath.begin();
517 cit != edgepath.end(); ++cit) {
518 Converter const & conv = converterlist_[*cit];
519 bool dummy = conv.To()->dummy() && conv.to() != "program";
521 LYXERR(Debug::FILES, "Converting from "
522 << conv.from() << " to " << conv.to());
525 outfile = FileName(conv.result_file().empty()
526 ? changeExtension(from_file.absFileName(), conv.To()->extension())
527 : addName(subst(conv.result_dir(),
528 token_base, from_base),
529 subst(conv.result_file(),
530 token_base, onlyFileName(from_base))));
532 // if input and output files are equal, we use a
533 // temporary file as intermediary (JMarc)
534 FileName real_outfile;
535 if (!conv.result_file().empty())
536 real_outfile = FileName(changeExtension(from_file.absFileName(),
537 conv.To()->extension()));
538 if (outfile == infile) {
539 real_outfile = infile;
540 // when importing, a buffer does not necessarily exist
542 outfile = FileName(addName(buffer->temppath(), "tmpfile.out"));
544 outfile = FileName(addName(package().temp_dir().absFileName(),
548 if (buffer && buffer->params().use_minted
549 && lyxrc.pygmentize_command.empty() && conv.latex()) {
551 // Warn only if listings insets are actually used
552 for (Paragraph const & par : buffer->paragraphs()) {
553 InsetList const & insets = par.insetList();
554 pos_type lstpos = insets.find(LISTINGS_CODE, 0);
555 pos_type incpos = insets.find(INCLUDE_CODE, 0);
557 InsetInclude const * include =
558 static_cast<InsetInclude *>
559 (insets.get(incpos));
560 if (include->params().getCmdName() !=
565 if (lstpos >= 0 || incpos >= 0) {
571 Alert::warning(_("Pygments driver command not found!"),
572 _("The driver command necessary to use the minted package\n"
573 "(pygmentize) has not been found. Make sure you have\n"
574 "the python-pygments module installed or, if the driver\n"
575 "is named differently, to add the following line to the\n"
576 "document preamble:\n\n"
577 "\\AtBeginDocument{\\renewcommand{\\MintedPygmentize}{driver}}\n\n"
578 "where 'driver' is name of the driver command."));
582 if (!checkAuth(conv, buffer ? buffer->absFileName() : string(),
583 buffer && buffer->params().shell_escape))
587 // We are not importing, we have a buffer
590 string command = conv.command();
591 command = subst(command, token_from, "");
592 command = subst(command, token_latex_encoding,
593 buffer->params().encoding().latexName());
594 if (buffer->params().shell_escape
595 && !contains(command, "-shell-escape"))
596 command += " -shell-escape ";
597 LYXERR(Debug::FILES, "Running " << command);
599 // Check changed return value here.
600 RetVal const retval = runLaTeX(*buffer, command, runparams, errorList);
601 if (retval != SUCCESS)
604 if (conv.need_aux() && !run_latex) {
605 // We are not importing, we have a buffer
608 switch (runparams.flavor) {
609 case OutputParams::DVILUATEX:
610 command = dvilualatex_command_;
612 case OutputParams::LUATEX:
613 command = lualatex_command_;
615 case OutputParams::PDFLATEX:
616 command = pdflatex_command_;
618 case OutputParams::XETEX:
619 command = xelatex_command_;
622 command = latex_command_;
625 if (!command.empty()) {
626 LYXERR(Debug::FILES, "Running "
628 << " to update aux file");
630 // Check changed return value here.
631 RetVal const retval = runLaTeX(*buffer, command, runparams, errorList);
632 if (retval != SUCCESS)
638 string const infile2 =
639 to_utf8(makeRelPath(from_utf8(infile.absFileName()), from_utf8(path)));
640 string const outfile2 =
641 to_utf8(makeRelPath(from_utf8(outfile.absFileName()), from_utf8(path)));
643 string command = conv.command();
644 command = subst(command, token_from, quoteName(infile2));
645 command = subst(command, token_base, quoteName(from_base));
646 command = subst(command, token_to, quoteName(outfile2));
647 command = subst(command, token_path, quoteName(onlyPath(infile.absFileName())));
648 command = subst(command, token_orig_path, quoteName(onlyPath(orig_from.absFileName())));
649 command = subst(command, token_orig_from, quoteName(onlyFileName(orig_from.absFileName())));
650 command = subst(command, token_encoding, buffer ? buffer->params().encoding().iconvName() : string());
652 if (!conv.parselog().empty())
653 command += " 2> " + quoteName(infile2 + ".out");
655 // it is not actually not necessary to test for buffer here,
656 // but it pleases coverity.
657 if (buffer && conv.from() == "dvi" && conv.to() == "ps")
658 command = add_options(command,
659 buffer->params().dvips_options());
660 else if (buffer && conv.from() == "dvi" && prefixIs(conv.to(), "pdf"))
661 command = add_options(command,
662 dvipdfm_options(buffer->params()));
664 LYXERR(Debug::FILES, "Calling " << command);
666 buffer->message(_("Executing command: ")
667 + from_utf8(command));
672 res = one.startscript(Systemcall::DontWait,
673 to_filesystem8bit(from_utf8(command)),
674 buffer ? buffer->filePath() : string(),
675 buffer ? buffer->layoutPos() : string());
676 // We're not waiting for the result, so we can't do anything
679 Systemcall::Starttype starttype =
680 (buffer && buffer->isClone()) ?
681 Systemcall::WaitLoop : Systemcall::Wait;
682 res = one.startscript(starttype,
683 to_filesystem8bit(from_utf8(command)),
684 buffer ? buffer->filePath()
686 buffer ? buffer->layoutPos()
688 if (res == Systemcall::KILLED) {
689 frontend::Alert::warning(
690 _("Converter killed"),
691 bformat(_("The following converter was killed by the user.\n %1$s\n"),
692 from_utf8(command)));
696 if (!real_outfile.empty()) {
697 Mover const & mover = getMover(conv.to());
698 if (!mover.rename(outfile, real_outfile))
701 LYXERR(Debug::FILES, "renaming file " << outfile
702 << " to " << real_outfile);
703 // Finally, don't forget to tell any future
704 // converters to use the renamed file...
705 outfile = real_outfile;
708 if (!conv.parselog().empty()) {
709 string const logfile = infile2 + ".log";
710 string const command2 = conv.parselog() +
711 " < " + quoteName(infile2 + ".out") +
712 " > " + quoteName(logfile);
713 res = one.startscript(starttype,
714 to_filesystem8bit(from_utf8(command2)),
716 buffer->layoutPos());
717 if (res == Systemcall::KILLED) {
718 frontend::Alert::warning(
719 _("Converter killed"),
720 bformat(_("The following converter was killed by the user.\n %1$s\n"),
721 from_utf8(command)));
724 if (!scanLog(*buffer, command, makeAbsPath(logfile, path), errorList))
730 if (res == Systemcall::KILLED) {
731 Alert::information(_("Process Killed"),
732 bformat(_("The conversion process was killed while running:\n%1$s"),
733 wrapParas(from_utf8(command))));
736 if (res == Systemcall::TIMEOUT) {
737 Alert::information(_("Process Timed Out"),
738 bformat(_("The conversion process:\n%1$s\ntimed out before completing."),
739 wrapParas(from_utf8(command))));
742 if (conv.to() == "program") {
743 Alert::error(_("Build errors"),
744 _("There were errors during the build process."));
746 // FIXME: this should go out of here. For example, here we cannot say if
747 // it is a document (.lyx) or something else. Same goes for elsewhere.
748 Alert::error(_("Cannot convert file"),
749 bformat(_("An error occurred while running:\n%1$s"),
750 wrapParas(from_utf8(command))));
757 Converter const & conv = converterlist_[edgepath.back()];
758 if (conv.To()->dummy())
761 if (!conv.result_dir().empty()) {
762 // The converter has put the file(s) in a directory.
763 // In this case we ignore the given to_file.
764 if (from_base != to_base) {
765 string const from = subst(conv.result_dir(),
766 token_base, from_base);
767 string const to = subst(conv.result_dir(),
768 token_base, to_base);
769 Mover const & mover = getMover(conv.from());
770 if (!mover.rename(FileName(from), FileName(to))) {
771 Alert::error(_("Cannot convert file"),
772 bformat(_("Could not move a temporary directory from %1$s to %2$s."),
773 from_utf8(from), from_utf8(to)));
779 if (conversionflags & try_cache)
780 ConverterCache::get().add(orig_from, to_format, outfile);
781 return move(conv.to(), outfile, to_file, conv.latex()) ? SUCCESS : FAILURE;
786 bool Converters::move(string const & fmt,
787 FileName const & from, FileName const & to, bool copy)
792 bool no_errors = true;
793 string const path = onlyPath(from.absFileName());
794 string const base = onlyFileName(removeExtension(from.absFileName()));
795 string const to_base = removeExtension(to.absFileName());
796 string const to_extension = getExtension(to.absFileName());
798 support::FileNameList const files = FileName(path).dirList(getExtension(from.absFileName()));
799 for (support::FileNameList::const_iterator it = files.begin();
800 it != files.end(); ++it) {
801 string const from2 = it->absFileName();
802 string const file2 = onlyFileName(from2);
803 if (prefixIs(file2, base)) {
804 string const to2 = changeExtension(
805 to_base + file2.substr(base.length()),
807 LYXERR(Debug::FILES, "moving " << from2 << " to " << to2);
809 Mover const & mover = getMover(fmt);
810 bool const moved = copy
811 ? mover.copy(*it, FileName(to2))
812 : mover.rename(*it, FileName(to2));
813 if (!moved && no_errors) {
814 Alert::error(_("Cannot convert file"),
816 _("Could not copy a temporary file from %1$s to %2$s.") :
817 _("Could not move a temporary file from %1$s to %2$s."),
818 from_utf8(from2), from_utf8(to2)));
827 bool Converters::formatIsUsed(string const & format)
829 ConverterList::const_iterator cit = converterlist_.begin();
830 ConverterList::const_iterator end = converterlist_.end();
831 for (; cit != end; ++cit) {
832 if (cit->from() == format || cit->to() == format)
839 bool Converters::scanLog(Buffer const & buffer, string const & /*command*/,
840 FileName const & filename, ErrorList & errorList)
842 OutputParams runparams(0);
843 runparams.flavor = OutputParams::LATEX;
844 LaTeX latex("", runparams, filename);
846 int const result = latex.scanLogFile(terr);
848 if (result & LaTeX::ERRORS)
849 buffer.bufferErrors(terr, errorList);
855 Converters::RetVal Converters::runLaTeX(Buffer const & buffer, string const & command,
856 OutputParams const & runparams, ErrorList & errorList)
858 buffer.setBusy(true);
859 buffer.message(_("Running LaTeX..."));
861 // do the LaTeX run(s)
862 string const name = buffer.latexName();
863 LaTeX latex(command, runparams, FileName(makeAbsPath(name)),
864 buffer.filePath(), buffer.layoutPos(),
865 buffer.isClone(), buffer.lastPreviewError());
867 // The connection closes itself at the end of the scope when latex is
868 // destroyed. One cannot close (and destroy) buffer while the converter is
870 latex.message.connect([&buffer](docstring const & msg){
873 int const result = latex.run(terr);
875 if (result == Systemcall::KILLED) {
876 Alert::error(_("Export canceled"),
877 _("The export process was terminated by the user."));
881 if (result & LaTeX::ERRORS)
882 buffer.bufferErrors(terr, errorList);
884 if ((result & LaTeX::UNDEF_CIT) || (result & LaTeX::UNDEF_REF)) {
885 buffer.bufferRefs(terr, errorList);
886 if (errorList.empty())
887 errorList.push_back(ErrorItem(_("Undefined reference"),
888 _("Undefined reference or citation was found during the build, please check the Log."),
892 if (!errorList.empty()) {
893 // We will show the LaTeX Errors GUI later which contains
894 // specific error messages so it would be repetitive to give
895 // e.g. the "finished with an error" dialog in addition.
897 else if (result & LaTeX::NO_LOGFILE) {
898 docstring const str =
899 bformat(_("LaTeX did not run successfully. "
900 "Additionally, LyX could not locate "
901 "the LaTeX log %1$s."), from_utf8(name));
902 Alert::error(_("LaTeX failed"), str);
903 } else if (result & LaTeX::NONZERO_ERROR) {
904 docstring const str =
905 bformat(_( "The external program\n%1$s\n"
906 "finished with an error. "
907 "It is recommended you fix the cause of the external "
908 "program's error (check the logs). "), from_utf8(command));
909 Alert::error(_("LaTeX failed"), str);
910 } else if (result & LaTeX::NO_OUTPUT) {
911 Alert::warning(_("Output is empty"),
912 _("No output file was generated."));
915 buffer.setBusy(false);
917 int const ERROR_MASK =
924 return (result & ERROR_MASK) == 0 ? SUCCESS : FAILURE;
929 void Converters::buildGraph()
931 // clear graph's data structures
932 G_.init(theFormats().size());
933 // each of the converters knows how to convert one format to another
934 // so, for each of them, we create an arrow on the graph, going from
935 // the one to the other
936 ConverterList::iterator it = converterlist_.begin();
937 ConverterList::iterator const end = converterlist_.end();
938 for (; it != end ; ++it) {
939 int const from = theFormats().getNumber(it->from());
940 int const to = theFormats().getNumber(it->to());
941 LASSERT(from >= 0, continue);
942 LASSERT(to >= 0, continue);
943 G_.addEdge(from, to);
948 FormatList const Converters::intToFormat(vector<int> const & input)
950 FormatList result(input.size());
952 vector<int>::const_iterator it = input.begin();
953 vector<int>::const_iterator const end = input.end();
954 FormatList::iterator rit = result.begin();
955 for ( ; it != end; ++it, ++rit) {
956 *rit = &theFormats().get(*it);
962 FormatList const Converters::getReachableTo(string const & target,
963 bool const clear_visited)
965 vector<int> const & reachablesto =
966 G_.getReachableTo(theFormats().getNumber(target), clear_visited);
968 return intToFormat(reachablesto);
972 FormatList const Converters::getReachable(string const & from,
973 bool const only_viewable, bool const clear_visited,
974 set<string> const & excludes)
976 set<int> excluded_numbers;
978 set<string>::const_iterator sit = excludes.begin();
979 set<string>::const_iterator const end = excludes.end();
980 for (; sit != end; ++sit)
981 excluded_numbers.insert(theFormats().getNumber(*sit));
983 vector<int> const & reachables =
984 G_.getReachable(theFormats().getNumber(from),
989 return intToFormat(reachables);
993 bool Converters::isReachable(string const & from, string const & to)
995 return G_.isReachable(theFormats().getNumber(from),
996 theFormats().getNumber(to));
1000 Graph::EdgePath Converters::getPath(string const & from, string const & to)
1002 return G_.getPath(theFormats().getNumber(from),
1003 theFormats().getNumber(to));
1007 FormatList Converters::importableFormats()
1009 vector<string> l = loaders();
1010 FormatList result = getReachableTo(l[0], true);
1011 vector<string>::const_iterator it = l.begin() + 1;
1012 vector<string>::const_iterator en = l.end();
1013 for (; it != en; ++it) {
1014 FormatList r = getReachableTo(*it, false);
1015 result.insert(result.end(), r.begin(), r.end());
1021 FormatList Converters::exportableFormats(bool only_viewable)
1023 vector<string> s = savers();
1024 FormatList result = getReachable(s[0], only_viewable, true);
1025 vector<string>::const_iterator it = s.begin() + 1;
1026 vector<string>::const_iterator en = s.end();
1027 for (; it != en; ++it) {
1028 FormatList r = getReachable(*it, only_viewable, false);
1029 result.insert(result.end(), r.begin(), r.end());
1035 vector<string> Converters::loaders() const
1039 v.push_back("text");
1040 v.push_back("textparagraph");
1045 vector<string> Converters::savers() const
1048 v.push_back("docbook");
1049 v.push_back("latex");
1050 v.push_back("literate");
1051 v.push_back("luatex");
1052 v.push_back("dviluatex");
1054 v.push_back("xhtml");
1055 v.push_back("pdflatex");
1056 v.push_back("platex");
1057 v.push_back("text");
1058 v.push_back("xetex");