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"
26 #include "frontends/alert.h"
28 #include "support/debug.h"
29 #include "support/FileNameList.h"
30 #include "support/filetools.h"
31 #include "support/gettext.h"
32 #include "support/lstrings.h"
33 #include "support/os.h"
34 #include "support/Package.h"
35 #include "support/Path.h"
36 #include "support/Systemcall.h"
39 using namespace lyx::support;
43 namespace Alert = lyx::frontend::Alert;
48 string const token_from("$$i");
49 string const token_base("$$b");
50 string const token_to("$$o");
51 string const token_path("$$p");
52 string const token_orig_path("$$r");
53 string const token_orig_from("$$f");
54 string const token_encoding("$$e");
55 string const token_latex_encoding("$$E");
58 string const add_options(string const & command, string const & options)
61 string const tail = split(command, head, ' ');
62 return head + ' ' + options + ' ' + tail;
66 string const dvipdfm_options(BufferParams const & bp)
70 if (bp.papersize != PAPER_CUSTOM) {
71 string const paper_size = bp.paperSizeName(BufferParams::DVIPDFM);
72 if (!paper_size.empty())
73 result = "-p "+ paper_size;
75 if (bp.orientation == ORIENTATION_LANDSCAPE)
83 class ConverterEqual {
85 ConverterEqual(string const & from, string const & to)
86 : from_(from), to_(to) {}
87 bool operator()(Converter const & c) const {
88 return c.from == from_ && c.to == to_;
98 Converter::Converter(string const & f, string const & t,
99 string const & c, string const & l)
100 : from(f), to(t), command(c), flags(l),
101 From(0), To(0), latex(false), xml(false),
106 void Converter::readFlags()
108 string flag_list(flags);
109 while (!flag_list.empty()) {
110 string flag_name, flag_value;
111 flag_list = split(flag_list, flag_value, ',');
112 flag_value = split(flag_value, flag_name, '=');
113 if (flag_name == "latex") {
115 latex_flavor = flag_value.empty() ?
116 "latex" : flag_value;
117 } else if (flag_name == "xml")
119 else if (flag_name == "needaux")
121 else if (flag_name == "resultdir")
122 result_dir = (flag_value.empty())
123 ? token_base : flag_value;
124 else if (flag_name == "resultfile")
125 result_file = flag_value;
126 else if (flag_name == "parselog")
127 parselog = flag_value;
129 if (!result_dir.empty() && result_file.empty())
130 result_file = "index." + formats.extension(to);
131 //if (!contains(command, token_from))
136 Converter const * Converters::getConverter(string const & from,
137 string const & to) const
139 ConverterList::const_iterator const cit =
140 find_if(converterlist_.begin(), converterlist_.end(),
141 ConverterEqual(from, to));
142 if (cit != converterlist_.end())
149 int Converters::getNumber(string const & from, string const & to) const
151 ConverterList::const_iterator const cit =
152 find_if(converterlist_.begin(), converterlist_.end(),
153 ConverterEqual(from, to));
154 if (cit != converterlist_.end())
155 return distance(converterlist_.begin(), cit);
161 void Converters::add(string const & from, string const & to,
162 string const & command, string const & flags)
166 ConverterList::iterator it = find_if(converterlist_.begin(),
167 converterlist_.end(),
168 ConverterEqual(from , to));
170 Converter converter(from, to, command, flags);
171 if (it != converterlist_.end() && !flags.empty() && flags[0] == '*') {
173 converter.command = command;
174 converter.flags = flags;
176 converter.readFlags();
178 // The latex_command is used to update the .aux file when running
179 // a converter that uses it.
180 if (converter.latex) {
181 if (latex_command_.empty() ||
182 converter.latex_flavor == "latex")
183 latex_command_ = subst(command, token_from, "");
184 if (dvilualatex_command_.empty() ||
185 converter.latex_flavor == "dvilualatex")
186 dvilualatex_command_ = subst(command, token_from, "");
187 if (lualatex_command_.empty() ||
188 converter.latex_flavor == "lualatex")
189 lualatex_command_ = subst(command, token_from, "");
190 if (pdflatex_command_.empty() ||
191 converter.latex_flavor == "pdflatex")
192 pdflatex_command_ = subst(command, token_from, "");
193 if (xelatex_command_.empty() ||
194 converter.latex_flavor == "xelatex")
195 xelatex_command_ = subst(command, token_from, "");
198 if (it == converterlist_.end()) {
199 converterlist_.push_back(converter);
201 converter.From = it->From;
202 converter.To = it->To;
208 void Converters::erase(string const & from, string const & to)
210 ConverterList::iterator const it =
211 find_if(converterlist_.begin(),
212 converterlist_.end(),
213 ConverterEqual(from, to));
214 if (it != converterlist_.end())
215 converterlist_.erase(it);
219 // This method updates the pointers From and To in all the converters.
220 // The code is not very efficient, but it doesn't matter as the number
221 // of formats and converters is small.
222 // Furthermore, this method is called only on startup, or after
223 // adding/deleting a format in FormPreferences (the latter calls can be
224 // eliminated if the formats in the Formats class are stored using a map or
225 // a list (instead of a vector), but this will cause other problems).
226 void Converters::update(Formats const & formats)
228 ConverterList::iterator it = converterlist_.begin();
229 ConverterList::iterator end = converterlist_.end();
230 for (; it != end; ++it) {
231 it->From = formats.getFormat(it->from);
232 it->To = formats.getFormat(it->to);
237 // This method updates the pointers From and To in the last converter.
238 // It is called when adding a new converter in FormPreferences
239 void Converters::updateLast(Formats const & formats)
241 if (converterlist_.begin() != converterlist_.end()) {
242 ConverterList::iterator it = converterlist_.end() - 1;
243 it->From = formats.getFormat(it->from);
244 it->To = formats.getFormat(it->to);
249 OutputParams::FLAVOR Converters::getFlavor(Graph::EdgePath const & path,
250 Buffer const * buffer)
252 for (Graph::EdgePath::const_iterator cit = path.begin();
253 cit != path.end(); ++cit) {
254 Converter const & conv = converterlist_[*cit];
256 if (conv.latex_flavor == "xelatex")
257 return OutputParams::XETEX;
258 if (conv.latex_flavor == "lualatex")
259 return OutputParams::LUATEX;
260 if (conv.latex_flavor == "dvilualatex")
261 return OutputParams::DVILUATEX;
262 if (conv.latex_flavor == "pdflatex")
263 return OutputParams::PDFLATEX;
265 return OutputParams::XML;
267 return buffer ? buffer->params().getOutputFlavor()
268 : OutputParams::LATEX;
272 bool Converters::convert(Buffer const * buffer,
273 FileName const & from_file, FileName const & to_file,
274 FileName const & orig_from,
275 string const & from_format, string const & to_format,
276 ErrorList & errorList, int conversionflags)
278 if (from_format == to_format)
279 return move(from_format, from_file, to_file, false);
281 if ((conversionflags & try_cache) &&
282 ConverterCache::get().inCache(orig_from, to_format))
283 return ConverterCache::get().copy(orig_from, to_format, to_file);
285 Graph::EdgePath edgepath = getPath(from_format, to_format);
286 if (edgepath.empty()) {
287 if (conversionflags & try_default) {
288 // if no special converter defined, then we take the
289 // default one from ImageMagic.
290 string const from_ext = from_format.empty() ?
291 getExtension(from_file.absFileName()) :
292 formats.extension(from_format);
293 string const to_ext = formats.extension(to_format);
294 string const command =
296 quoteName(libFileSearch("scripts", "convertDefault.py").toFilesystemEncoding()) +
298 quoteName(from_ext + ':' + from_file.toFilesystemEncoding()) +
300 quoteName(to_ext + ':' + to_file.toFilesystemEncoding());
301 LYXERR(Debug::FILES, "No converter defined! "
302 "I use convertDefault.py:\n\t" << command);
304 one.startscript(Systemcall::Wait, command, buffer ?
305 buffer->filePath() : string());
306 if (to_file.isReadableFile()) {
307 if (conversionflags & try_cache)
308 ConverterCache::get().add(orig_from,
314 // only warn once per session and per file type
315 static std::map<string, string> warned;
316 if (warned.find(from_format) != warned.end() && warned.find(from_format)->second == to_format) {
319 warned.insert(make_pair(from_format, to_format));
321 Alert::error(_("Cannot convert file"),
322 bformat(_("No information for converting %1$s "
323 "format files to %2$s.\n"
324 "Define a converter in the preferences."),
325 from_ascii(from_format), from_ascii(to_format)));
329 // buffer is only invalid for importing, and then runparams is not
331 OutputParams runparams(buffer ? &buffer->params().encoding() : 0);
332 runparams.flavor = getFlavor(edgepath, buffer);
335 runparams.use_japanese = buffer->params().bufferFormat() == "platex";
336 runparams.use_indices = buffer->params().use_indices;
337 runparams.bibtex_command = (buffer->params().bibtex_command == "default") ?
338 string() : buffer->params().bibtex_command;
339 runparams.index_command = (buffer->params().index_command == "default") ?
340 string() : buffer->params().index_command;
343 // Some converters (e.g. lilypond) can only output files to the
344 // current directory, so we need to change the current directory.
345 // This has the added benefit that all other files that may be
346 // generated by the converter are deleted when LyX closes and do not
347 // clutter the real working directory.
348 // FIXME: This does not work if path is an UNC path on windows
350 string const path(onlyPath(from_file.absFileName()));
351 // Prevent the compiler from optimizing away p
355 // empty the error list before any new conversion takes place.
358 bool run_latex = false;
359 string from_base = changeExtension(from_file.absFileName(), "");
360 string to_base = changeExtension(to_file.absFileName(), "");
362 FileName outfile = from_file;
363 for (Graph::EdgePath::const_iterator cit = edgepath.begin();
364 cit != edgepath.end(); ++cit) {
365 Converter const & conv = converterlist_[*cit];
366 bool dummy = conv.To->dummy() && conv.to != "program";
368 LYXERR(Debug::FILES, "Converting from "
369 << conv.from << " to " << conv.to);
372 outfile = FileName(conv.result_file.empty()
373 ? changeExtension(from_file.absFileName(), conv.To->extension())
374 : addName(subst(conv.result_dir,
375 token_base, from_base),
376 subst(conv.result_file,
377 token_base, onlyFileName(from_base))));
379 // if input and output files are equal, we use a
380 // temporary file as intermediary (JMarc)
381 FileName real_outfile;
382 if (!conv.result_file.empty())
383 real_outfile = FileName(changeExtension(from_file.absFileName(),
384 conv.To->extension()));
385 if (outfile == infile) {
386 real_outfile = infile;
387 // when importing, a buffer does not necessarily exist
389 outfile = FileName(addName(buffer->temppath(), "tmpfile.out"));
391 outfile = FileName(addName(package().temp_dir().absFileName(),
397 string command = conv.command;
398 command = subst(command, token_from, "");
399 command = subst(command, token_latex_encoding, buffer ?
400 buffer->params().encoding().latexName() : string());
401 LYXERR(Debug::FILES, "Running " << command);
402 if (!runLaTeX(*buffer, command, runparams, errorList))
405 if (conv.need_aux && !run_latex) {
407 switch (runparams.flavor) {
408 case OutputParams::DVILUATEX:
409 command = dvilualatex_command_;
411 case OutputParams::LUATEX:
412 command = lualatex_command_;
414 case OutputParams::PDFLATEX:
415 command = pdflatex_command_;
417 case OutputParams::XETEX:
418 command = xelatex_command_;
421 command = latex_command_;
424 if (!command.empty()) {
425 LYXERR(Debug::FILES, "Running "
427 << " to update aux file");
428 if (!runLaTeX(*buffer, command,
429 runparams, errorList))
435 string const infile2 =
436 to_utf8(makeRelPath(from_utf8(infile.absFileName()), from_utf8(path)));
437 string const outfile2 =
438 to_utf8(makeRelPath(from_utf8(outfile.absFileName()), from_utf8(path)));
440 string command = conv.command;
441 command = subst(command, token_from, quoteName(infile2));
442 command = subst(command, token_base, quoteName(from_base));
443 command = subst(command, token_to, quoteName(outfile2));
444 command = subst(command, token_path, quoteName(onlyPath(infile.absFileName())));
445 command = subst(command, token_orig_path, quoteName(onlyPath(orig_from.absFileName())));
446 command = subst(command, token_orig_from, quoteName(onlyFileName(orig_from.absFileName())));
447 command = subst(command, token_encoding, buffer ? buffer->params().encoding().iconvName() : string());
448 command = libScriptSearch(command);
450 if (!conv.parselog.empty())
451 command += " 2> " + quoteName(infile2 + ".out");
453 if (conv.from == "dvi" && conv.to == "ps")
454 command = add_options(command,
455 buffer->params().dvips_options());
456 else if (conv.from == "dvi" && prefixIs(conv.to, "pdf"))
457 command = add_options(command,
458 dvipdfm_options(buffer->params()));
460 LYXERR(Debug::FILES, "Calling " << command);
462 buffer->message(_("Executing command: ")
463 + from_utf8(command));
468 res = one.startscript(Systemcall::DontWait,
469 to_filesystem8bit(from_utf8(command)),
470 buffer ? buffer->filePath() : string());
471 // We're not waiting for the result, so we can't do anything
474 res = one.startscript(Systemcall::Wait,
475 to_filesystem8bit(from_utf8(command)),
476 buffer ? buffer->filePath()
478 if (!real_outfile.empty()) {
479 Mover const & mover = getMover(conv.to);
480 if (!mover.rename(outfile, real_outfile))
483 LYXERR(Debug::FILES, "renaming file " << outfile
484 << " to " << real_outfile);
485 // Finally, don't forget to tell any future
486 // converters to use the renamed file...
487 outfile = real_outfile;
490 if (!conv.parselog.empty()) {
491 string const logfile = infile2 + ".log";
492 string const script = libScriptSearch(conv.parselog);
493 string const command2 = script +
494 " < " + quoteName(infile2 + ".out") +
495 " > " + quoteName(logfile);
496 one.startscript(Systemcall::Wait,
497 to_filesystem8bit(from_utf8(command2)),
499 if (!scanLog(*buffer, command, makeAbsPath(logfile, path), errorList))
505 if (conv.to == "program") {
506 Alert::error(_("Build errors"),
507 _("There were errors during the build process."));
509 // FIXME: this should go out of here. For example, here we cannot say if
510 // it is a document (.lyx) or something else. Same goes for elsewhere.
511 Alert::error(_("Cannot convert file"),
512 bformat(_("An error occurred while running:\n%1$s"),
513 wrapParas(from_utf8(command))));
520 Converter const & conv = converterlist_[edgepath.back()];
521 if (conv.To->dummy())
524 if (!conv.result_dir.empty()) {
525 // The converter has put the file(s) in a directory.
526 // In this case we ignore the given to_file.
527 if (from_base != to_base) {
528 string const from = subst(conv.result_dir,
529 token_base, from_base);
530 string const to = subst(conv.result_dir,
531 token_base, to_base);
532 Mover const & mover = getMover(conv.from);
533 if (!mover.rename(FileName(from), FileName(to))) {
534 Alert::error(_("Cannot convert file"),
535 bformat(_("Could not move a temporary directory from %1$s to %2$s."),
536 from_utf8(from), from_utf8(to)));
542 if (conversionflags & try_cache)
543 ConverterCache::get().add(orig_from, to_format, outfile);
544 return move(conv.to, outfile, to_file, conv.latex);
549 bool Converters::move(string const & fmt,
550 FileName const & from, FileName const & to, bool copy)
555 bool no_errors = true;
556 string const path = onlyPath(from.absFileName());
557 string const base = onlyFileName(removeExtension(from.absFileName()));
558 string const to_base = removeExtension(to.absFileName());
559 string const to_extension = getExtension(to.absFileName());
561 support::FileNameList const files = FileName(path).dirList(getExtension(from.absFileName()));
562 for (support::FileNameList::const_iterator it = files.begin();
563 it != files.end(); ++it) {
564 string const from2 = it->absFileName();
565 string const file2 = onlyFileName(from2);
566 if (prefixIs(file2, base)) {
567 string const to2 = changeExtension(
568 to_base + file2.substr(base.length()),
570 LYXERR(Debug::FILES, "moving " << from2 << " to " << to2);
572 Mover const & mover = getMover(fmt);
573 bool const moved = copy
574 ? mover.copy(*it, FileName(to2))
575 : mover.rename(*it, FileName(to2));
576 if (!moved && no_errors) {
577 Alert::error(_("Cannot convert file"),
579 _("Could not copy a temporary file from %1$s to %2$s.") :
580 _("Could not move a temporary file from %1$s to %2$s."),
581 from_utf8(from2), from_utf8(to2)));
590 bool Converters::formatIsUsed(string const & format)
592 ConverterList::const_iterator cit = converterlist_.begin();
593 ConverterList::const_iterator end = converterlist_.end();
594 for (; cit != end; ++cit) {
595 if (cit->from == format || cit->to == format)
602 bool Converters::scanLog(Buffer const & buffer, string const & /*command*/,
603 FileName const & filename, ErrorList & errorList)
605 OutputParams runparams(0);
606 runparams.flavor = OutputParams::LATEX;
607 LaTeX latex("", runparams, filename);
609 int const result = latex.scanLogFile(terr);
611 if (result & LaTeX::ERRORS)
612 buffer.bufferErrors(terr, errorList);
621 : public boost::signals::trackable {
623 ShowMessage(Buffer const & b) : buffer_(b) {}
624 void operator()(docstring const & msg) const { buffer_.message(msg); }
626 Buffer const & buffer_;
632 bool Converters::runLaTeX(Buffer const & buffer, string const & command,
633 OutputParams const & runparams, ErrorList & errorList)
635 buffer.setBusy(true);
636 buffer.message(_("Running LaTeX..."));
638 runparams.document_language = buffer.params().language->babel();
640 // do the LaTeX run(s)
641 string const name = buffer.latexName();
642 LaTeX latex(command, runparams, FileName(makeAbsPath(name)),
645 ShowMessage show(buffer);
646 latex.message.connect(show);
647 int const result = latex.run(terr);
649 if (result & LaTeX::ERRORS)
650 buffer.bufferErrors(terr, errorList);
652 // check return value from latex.run().
653 if ((result & LaTeX::NO_LOGFILE) && !buffer.isClone()) {
654 docstring const str =
655 bformat(_("LaTeX did not run successfully. "
656 "Additionally, LyX could not locate "
657 "the LaTeX log %1$s."), from_utf8(name));
658 Alert::error(_("LaTeX failed"), str);
659 } else if ((result & LaTeX::NO_OUTPUT) && !buffer.isClone()) {
660 Alert::warning(_("Output is empty"),
661 _("An empty output file was generated."));
665 buffer.setBusy(false);
667 int const ERROR_MASK =
672 return (result & ERROR_MASK) == 0;
678 void Converters::buildGraph()
680 // clear graph's data structures
681 G_.init(formats.size());
682 // each of the converters knows how to convert one format to another
683 // so, for each of them, we create an arrow on the graph, going from
684 // the one to the other
685 ConverterList::iterator it = converterlist_.begin();
686 ConverterList::iterator const end = converterlist_.end();
687 for (; it != end ; ++it) {
688 int const from = formats.getNumber(it->from);
689 int const to = formats.getNumber(it->to);
690 G_.addEdge(from, to);
695 vector<Format const *> const
696 Converters::intToFormat(vector<int> const & input)
698 vector<Format const *> result(input.size());
700 vector<int>::const_iterator it = input.begin();
701 vector<int>::const_iterator const end = input.end();
702 vector<Format const *>::iterator rit = result.begin();
703 for ( ; it != end; ++it, ++rit) {
704 *rit = &formats.get(*it);
710 vector<Format const *> const
711 Converters::getReachableTo(string const & target, bool const clear_visited)
713 vector<int> const & reachablesto =
714 G_.getReachableTo(formats.getNumber(target), clear_visited);
716 return intToFormat(reachablesto);
720 vector<Format const *> const
721 Converters::getReachable(string const & from, bool const only_viewable,
722 bool const clear_visited, set<string> const & excludes)
724 set<int> excluded_numbers;;
726 set<string>::const_iterator sit = excludes.begin();
727 set<string>::const_iterator const end = excludes.end();
728 for (; sit != end; ++sit)
729 excluded_numbers.insert(formats.getNumber(*sit));
731 vector<int> const & reachables =
732 G_.getReachable(formats.getNumber(from),
737 return intToFormat(reachables);
741 bool Converters::isReachable(string const & from, string const & to)
743 return G_.isReachable(formats.getNumber(from),
744 formats.getNumber(to));
748 Graph::EdgePath Converters::getPath(string const & from, string const & to)
750 return G_.getPath(formats.getNumber(from),
751 formats.getNumber(to));
755 vector<Format const *> Converters::importableFormats()
757 vector<string> l = loaders();
758 vector<Format const *> result = getReachableTo(l[0], true);
759 vector<string>::const_iterator it = l.begin() + 1;
760 vector<string>::const_iterator en = l.end();
761 for (; it != en; ++it) {
762 vector<Format const *> r = getReachableTo(*it, false);
763 result.insert(result.end(), r.begin(), r.end());
769 vector<Format const *> Converters::exportableFormats(bool only_viewable)
771 vector<string> s = savers();
772 vector<Format const *> result = getReachable(s[0], only_viewable, true);
773 vector<string>::const_iterator it = s.begin() + 1;
774 vector<string>::const_iterator en = s.end();
775 for (; it != en; ++it) {
776 vector<Format const *> r =
777 getReachable(*it, only_viewable, false);
778 result.insert(result.end(), r.begin(), r.end());
784 vector<string> Converters::loaders() const
789 v.push_back("textparagraph");
794 vector<string> Converters::savers() const
797 v.push_back("docbook");
798 v.push_back("latex");
799 v.push_back("literate");
800 v.push_back("luatex");
801 v.push_back("dviluatex");
803 v.push_back("xhtml");
804 v.push_back("pdflatex");
805 v.push_back("platex");
807 v.push_back("xetex");