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"
25 #include "frontends/Alert.h"
27 #include "support/filetools.h"
28 #include "support/lyxlib.h"
29 #include "support/os.h"
30 #include "support/path.h"
31 #include "support/systemcall.h"
36 using support::addName;
37 using support::bformat;
38 using support::changeExtension;
39 using support::compare_ascii_no_case;
40 using support::contains;
41 using support::dirList;
42 using support::getExtension;
43 using support::isFileReadable;
44 using support::libFileSearch;
45 using support::libScriptSearch;
46 using support::makeRelPath;
47 using support::onlyFilename;
48 using support::onlyPath;
50 using support::prefixIs;
51 using support::quoteName;
54 using support::Systemcall;
62 namespace Alert = lyx::frontend::Alert;
67 string const token_from("$$i");
68 string const token_base("$$b");
69 string const token_to("$$o");
70 string const token_path("$$p");
74 string const add_options(string const & command, string const & options)
77 string const tail = split(command, head, ' ');
78 return head + ' ' + options + ' ' + tail;
82 string const dvipdfm_options(BufferParams const & bp)
86 if (bp.papersize != PAPER_CUSTOM) {
87 string const paper_size = bp.paperSizeName();
88 if (paper_size != "b5" && paper_size != "foolscap")
89 result = "-p "+ paper_size;
91 if (bp.orientation == ORIENTATION_LANDSCAPE)
99 class ConverterEqual : public std::binary_function<string, string, bool> {
101 ConverterEqual(string const & from, string const & to)
102 : from_(from), to_(to) {}
103 bool operator()(Converter const & c) const {
104 return c.from == from_ && c.to == to_;
114 Converter::Converter(string const & f, string const & t,
115 string const & c, string const & l)
116 : from(f), to(t), command(c), flags(l),
117 From(0), To(0), latex(false), xml(false),
118 original_dir(false), need_aux(false)
122 void Converter::readFlags()
124 string flag_list(flags);
125 while (!flag_list.empty()) {
126 string flag_name, flag_value;
127 flag_list = split(flag_list, flag_value, ',');
128 flag_value = split(flag_value, flag_name, '=');
129 if (flag_name == "latex")
131 else if (flag_name == "xml")
133 else if (flag_name == "originaldir")
135 else if (flag_name == "needaux")
137 else if (flag_name == "resultdir")
138 result_dir = (flag_value.empty())
139 ? token_base : flag_value;
140 else if (flag_name == "resultfile")
141 result_file = flag_value;
142 else if (flag_name == "parselog")
143 parselog = flag_value;
145 if (!result_dir.empty() && result_file.empty())
146 result_file = "index." + formats.extension(to);
147 //if (!contains(command, token_from))
152 bool operator<(Converter const & a, Converter const & b)
154 // use the compare_ascii_no_case instead of compare_no_case,
155 // because in turkish, 'i' is not the lowercase version of 'I',
156 // and thus turkish locale breaks parsing of tags.
157 int const i = compare_ascii_no_case(a.From->prettyname(),
158 b.From->prettyname());
160 return compare_ascii_no_case(a.To->prettyname(),
161 b.To->prettyname()) < 0;
167 Converter const * Converters::getConverter(string const & from,
168 string const & to) const
170 ConverterList::const_iterator const cit =
171 find_if(converterlist_.begin(), converterlist_.end(),
172 ConverterEqual(from, to));
173 if (cit != converterlist_.end())
180 int Converters::getNumber(string const & from, string const & to) const
182 ConverterList::const_iterator const cit =
183 find_if(converterlist_.begin(), converterlist_.end(),
184 ConverterEqual(from, to));
185 if (cit != converterlist_.end())
186 return distance(converterlist_.begin(), cit);
192 void Converters::add(string const & from, string const & to,
193 string const & command, string const & flags)
197 ConverterList::iterator it = find_if(converterlist_.begin(),
198 converterlist_.end(),
199 ConverterEqual(from , to));
201 Converter converter(from, to, command, flags);
202 if (it != converterlist_.end() && !flags.empty() && flags[0] == '*') {
204 converter.command = command;
205 converter.flags = flags;
207 converter.readFlags();
209 if (converter.latex && (latex_command_.empty() || to == "dvi"))
210 latex_command_ = subst(command, token_from, "");
211 // If we have both latex & pdflatex, we set latex_command to latex.
212 // The latex_command is used to update the .aux file when running
213 // a converter that uses it.
215 if (it == converterlist_.end()) {
216 converterlist_.push_back(converter);
218 converter.From = it->From;
219 converter.To = it->To;
225 void Converters::erase(string const & from, string const & to)
227 ConverterList::iterator const it =
228 find_if(converterlist_.begin(),
229 converterlist_.end(),
230 ConverterEqual(from, to));
231 if (it != converterlist_.end())
232 converterlist_.erase(it);
236 // This method updates the pointers From and To in all the converters.
237 // The code is not very efficient, but it doesn't matter as the number
238 // of formats and converters is small.
239 // Furthermore, this method is called only on startup, or after
240 // adding/deleting a format in FormPreferences (the latter calls can be
241 // eliminated if the formats in the Formats class are stored using a map or
242 // a list (instead of a vector), but this will cause other problems).
243 void Converters::update(Formats const & formats)
245 ConverterList::iterator it = converterlist_.begin();
246 ConverterList::iterator end = converterlist_.end();
247 for (; it != end; ++it) {
248 it->From = formats.getFormat(it->from);
249 it->To = formats.getFormat(it->to);
254 // This method updates the pointers From and To in the last converter.
255 // It is called when adding a new converter in FormPreferences
256 void Converters::updateLast(Formats const & formats)
258 if (converterlist_.begin() != converterlist_.end()) {
259 ConverterList::iterator it = converterlist_.end() - 1;
260 it->From = formats.getFormat(it->from);
261 it->To = formats.getFormat(it->to);
266 void Converters::sort()
268 std::sort(converterlist_.begin(), converterlist_.end());
272 OutputParams::FLAVOR Converters::getFlavor(Graph::EdgePath const & path)
274 for (Graph::EdgePath::const_iterator cit = path.begin();
275 cit != path.end(); ++cit) {
276 Converter const & conv = converterlist_[*cit];
278 if (contains(conv.to, "pdf"))
279 return OutputParams::PDFLATEX;
281 return OutputParams::XML;
283 return OutputParams::LATEX;
287 bool Converters::convert(Buffer const * buffer,
288 string const & from_file, string const & to_file_base,
289 string const & from_format, string const & to_format,
290 string & to_file, ErrorList & errorList, bool try_default)
292 string const to_ext = formats.extension(to_format);
293 to_file = changeExtension(to_file_base, to_ext);
295 if (from_format == to_format)
296 return move(from_format, from_file, to_file, false);
298 Graph::EdgePath edgepath = getPath(from_format, to_format);
299 if (edgepath.empty()) {
301 // if no special converter defined, then we take the
302 // default one from ImageMagic.
303 string const from_ext = from_format.empty() ?
304 getExtension(from_file) :
305 formats.extension(from_format);
306 string const command =
307 support::os::python() + ' ' +
308 quoteName(libFileSearch("scripts", "convertDefault.py")) +
310 quoteName(from_ext + ':' + from_file) +
312 quoteName(to_ext + ':' + to_file);
314 << "No converter defined! "
315 "I use convertDefault.py:\n\t"
318 one.startscript(Systemcall::Wait, command);
319 if (isFileReadable(to_file)) {
323 Alert::error(_("Cannot convert file"),
324 bformat(_("No information for converting %1$s "
325 "format files to %2$s.\n"
326 "Define a converter in the preferences."),
327 from_ascii(from_format), from_ascii(to_format)));
330 OutputParams runparams;
331 runparams.flavor = getFlavor(edgepath);
333 // Some converters (e.g. lilypond) can only output files to the
334 // current directory, so we need to change the current directory.
335 // This has the added benefit that all other files that may be
336 // generated by the converter are deleted when LyX closes and do not
337 // clutter the real working directory.
338 string path = onlyPath(from_file);
341 // empty the error list before any new conversion takes place.
344 bool run_latex = false;
345 string from_base = changeExtension(from_file, "");
346 string to_base = changeExtension(to_file, "");
348 string outfile = from_file;
349 for (Graph::EdgePath::const_iterator cit = edgepath.begin();
350 cit != edgepath.end(); ++cit) {
351 Converter const & conv = converterlist_[*cit];
352 bool dummy = conv.To->dummy() && conv.to != "program";
354 lyxerr[Debug::FILES] << "Converting from "
355 << conv.from << " to " << conv.to << endl;
357 outfile = conv.result_dir.empty()
358 ? changeExtension(from_file, conv.To->extension())
359 : addName(subst(conv.result_dir,
360 token_base, from_base),
361 subst(conv.result_file,
362 token_base, onlyFilename(from_base)));
364 // if input and output files are equal, we use a
365 // temporary file as intermediary (JMarc)
367 if (outfile == infile) {
368 real_outfile = infile;
369 outfile = addName(buffer->temppath(), "tmpfile.out");
374 string const command = subst(conv.command, token_from, "");
375 lyxerr[Debug::FILES] << "Running " << command << endl;
376 if (!runLaTeX(*buffer, command, runparams, errorList))
379 if (conv.need_aux && !run_latex
380 && !latex_command_.empty()) {
382 << "Running " << latex_command_
383 << " to update aux file"<< endl;
384 runLaTeX(*buffer, latex_command_, runparams, errorList);
387 string const infile2 = (conv.original_dir)
388 ? infile : makeRelPath(infile, path);
389 string const outfile2 = (conv.original_dir)
390 ? outfile : makeRelPath(outfile, path);
392 string command = conv.command;
393 command = subst(command, token_from, quoteName(infile2));
394 command = subst(command, token_base, quoteName(from_base));
395 command = subst(command, token_to, quoteName(outfile2));
396 command = libScriptSearch(command);
398 if (!conv.parselog.empty())
399 command += " 2> " + quoteName(infile2 + ".out");
401 if (conv.from == "dvi" && conv.to == "ps")
402 command = add_options(command,
403 buffer->params().dvips_options());
404 else if (conv.from == "dvi" && prefixIs(conv.to, "pdf"))
405 command = add_options(command,
406 dvipdfm_options(buffer->params()));
408 lyxerr[Debug::FILES] << "Calling " << command << endl;
410 buffer->message(_("Executing command: ")
411 + from_utf8(command));
413 Systemcall::Starttype const type = (dummy)
414 ? Systemcall::DontWait : Systemcall::Wait;
417 if (conv.original_dir) {
418 Path p(buffer->filePath());
419 res = one.startscript(type, command);
421 res = one.startscript(type, command);
423 if (!real_outfile.empty()) {
424 Mover const & mover = movers(conv.to);
425 if (!mover.rename(outfile, real_outfile))
429 << "renaming file " << outfile
430 << " to " << real_outfile
432 // Finally, don't forget to tell any future
433 // converters to use the renamed file...
434 outfile = real_outfile;
437 if (!conv.parselog.empty()) {
438 string const logfile = infile2 + ".log";
439 string const script = libScriptSearch(conv.parselog);
440 string const command2 = script +
441 " < " + quoteName(infile2 + ".out") +
442 " > " + quoteName(logfile);
443 one.startscript(Systemcall::Wait, command2);
444 if (!scanLog(*buffer, command, logfile, errorList))
449 if (conv.to == "program") {
450 Alert::error(_("Build errors"),
451 _("There were errors during the build process."));
453 // FIXME: this should go out of here. For example, here we cannot say if
454 // it is a document (.lyx) or something else. Same goes for elsewhere.
455 Alert::error(_("Cannot convert file"),
456 bformat(_("An error occurred whilst running %1$s"),
457 from_ascii(command.substr(0, 50))));
464 Converter const & conv = converterlist_[edgepath.back()];
465 if (conv.To->dummy())
468 if (!conv.result_dir.empty()) {
469 to_file = addName(subst(conv.result_dir, token_base, to_base),
470 subst(conv.result_file,
471 token_base, onlyFilename(to_base)));
472 if (from_base != to_base) {
473 string const from = subst(conv.result_dir,
474 token_base, from_base);
475 string const to = subst(conv.result_dir,
476 token_base, to_base);
477 Mover const & mover = movers(conv.from);
478 if (!mover.rename(from, to)) {
479 Alert::error(_("Cannot convert file"),
480 bformat(_("Could not move a temporary file from %1$s to %2$s."),
481 from_ascii(from), from_ascii(to)));
487 return move(conv.to, outfile, to_file, conv.latex);
491 bool Converters::move(string const & fmt,
492 string const & from, string const & to, bool copy)
497 bool no_errors = true;
498 string const path = onlyPath(from);
499 string const base = onlyFilename(changeExtension(from, ""));
500 string const to_base = changeExtension(to, "");
501 string const to_extension = getExtension(to);
503 vector<string> files = dirList(onlyPath(from), getExtension(from));
504 for (vector<string>::const_iterator it = files.begin();
505 it != files.end(); ++it)
506 if (prefixIs(*it, base)) {
507 string const from2 = path + *it;
508 string to2 = to_base + it->substr(base.length());
509 to2 = changeExtension(to2, to_extension);
510 lyxerr[Debug::FILES] << "moving " << from2
511 << " to " << to2 << endl;
513 Mover const & mover = movers(fmt);
514 bool const moved = copy
515 ? mover.copy(from2, to2)
516 : mover.rename(from2, to2);
517 if (!moved && no_errors) {
518 Alert::error(_("Cannot convert file"),
520 _("Could not copy a temporary file from %1$s to %2$s.") :
521 _("Could not move a temporary file from %1$s to %2$s."),
522 from_ascii(from2), from_ascii(to2)));
530 bool Converters::convert(Buffer const * buffer,
531 string const & from_file, string const & to_file_base,
532 string const & from_format, string const & to_format,
533 ErrorList & errorList, bool try_default)
536 return convert(buffer, from_file, to_file_base, from_format, to_format,
537 to_file, errorList, try_default);
541 bool Converters::formatIsUsed(string const & format)
543 ConverterList::const_iterator cit = converterlist_.begin();
544 ConverterList::const_iterator end = converterlist_.end();
545 for (; cit != end; ++cit) {
546 if (cit->from == format || cit->to == format)
553 bool Converters::scanLog(Buffer const & buffer, string const & /*command*/,
554 string const & filename, ErrorList & errorList)
556 OutputParams runparams;
557 runparams.flavor = OutputParams::LATEX;
558 LaTeX latex("", runparams, filename, "");
560 int const result = latex.scanLogFile(terr);
562 if (result & LaTeX::ERRORS)
563 bufferErrors(buffer, terr, errorList);
571 class showMessage : public std::unary_function<docstring, void>, public boost::signals::trackable {
573 showMessage(Buffer const & b) : buffer_(b) {};
574 void operator()(docstring const & m) const
579 Buffer const & buffer_;
585 bool Converters::runLaTeX(Buffer const & buffer, string const & command,
586 OutputParams const & runparams, ErrorList & errorList)
589 buffer.message(_("Running LaTeX..."));
591 runparams.document_language = buffer.params().language->babel();
593 // do the LaTeX run(s)
594 string const name = buffer.getLatexName();
595 LaTeX latex(command, runparams, name, buffer.filePath());
597 showMessage show(buffer);
598 latex.message.connect(show);
599 int const result = latex.run(terr);
601 if (result & LaTeX::ERRORS)
602 bufferErrors(buffer, terr, errorList);
604 // check return value from latex.run().
605 if ((result & LaTeX::NO_LOGFILE)) {
606 docstring const str =
607 bformat(_("LaTeX did not run successfully. "
608 "Additionally, LyX could not locate "
609 "the LaTeX log %1$s."), from_utf8(name));
610 Alert::error(_("LaTeX failed"), str);
611 } else if (result & LaTeX::NO_OUTPUT) {
612 Alert::warning(_("Output is empty"),
613 _("An empty output file was generated."));
619 int const ERROR_MASK =
624 return (result & ERROR_MASK) == 0;
630 void Converters::buildGraph()
632 G_.init(formats.size());
633 ConverterList::iterator beg = converterlist_.begin();
634 ConverterList::iterator const end = converterlist_.end();
635 for (ConverterList::iterator it = beg; it != end ; ++it) {
636 int const s = formats.getNumber(it->from);
637 int const t = formats.getNumber(it->to);
643 std::vector<Format const *> const
644 Converters::intToFormat(std::vector<int> const & input)
646 vector<Format const *> result(input.size());
648 vector<int>::const_iterator it = input.begin();
649 vector<int>::const_iterator const end = input.end();
650 vector<Format const *>::iterator rit = result.begin();
651 for ( ; it != end; ++it, ++rit) {
652 *rit = &formats.get(*it);
658 vector<Format const *> const
659 Converters::getReachableTo(string const & target, bool const clear_visited)
661 vector<int> const & reachablesto =
662 G_.getReachableTo(formats.getNumber(target), clear_visited);
664 return intToFormat(reachablesto);
668 vector<Format const *> const
669 Converters::getReachable(string const & from, bool const only_viewable,
670 bool const clear_visited)
672 vector<int> const & reachables =
673 G_.getReachable(formats.getNumber(from),
677 return intToFormat(reachables);
681 bool Converters::isReachable(string const & from, string const & to)
683 return G_.isReachable(formats.getNumber(from),
684 formats.getNumber(to));
688 Graph::EdgePath const
689 Converters::getPath(string const & from, string const & to)
691 return G_.getPath(formats.getNumber(from),
692 formats.getNumber(to));
696 /// The global instance
697 Converters converters;
699 // The global copy after reading lyxrc.defaults
700 Converters system_converters;