]> git.lyx.org Git - lyx.git/blob - src/converter.C
Document pasteParagraphList as hinted by Jean-Marc
[lyx.git] / src / converter.C
1 /**
2  * \file converter.C
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Dekel Tsur
7  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 #include <config.h>
12
13 #include "converter.h"
14
15 #include "ConverterCache.h"
16 #include "buffer.h"
17 #include "buffer_funcs.h"
18 #include "bufferparams.h"
19 #include "debug.h"
20 #include "format.h"
21 #include "gettext.h"
22 #include "language.h"
23 #include "LaTeX.h"
24 #include "mover.h"
25
26 #include "frontends/Alert.h"
27
28 #include "support/filetools.h"
29 #include "support/lyxlib.h"
30 #include "support/os.h"
31 #include "support/path.h"
32 #include "support/systemcall.h"
33
34
35 namespace lyx {
36
37 using support::absolutePath;
38 using support::addName;
39 using support::bformat;
40 using support::changeExtension;
41 using support::compare_ascii_no_case;
42 using support::contains;
43 using support::dirList;
44 using support::getExtension;
45 using support::isFileReadable;
46 using support::libFileSearch;
47 using support::libScriptSearch;
48 using support::makeRelPath;
49 using support::onlyFilename;
50 using support::onlyPath;
51 using support::Path;
52 using support::prefixIs;
53 using support::quoteName;
54 using support::split;
55 using support::subst;
56 using support::Systemcall;
57
58 using std::endl;
59 using std::find_if;
60 using std::string;
61 using std::vector;
62 using std::distance;
63
64 namespace Alert = lyx::frontend::Alert;
65
66
67 namespace {
68
69 string const token_from("$$i");
70 string const token_base("$$b");
71 string const token_to("$$o");
72 string const token_path("$$p");
73
74
75
76 string const add_options(string const & command, string const & options)
77 {
78         string head;
79         string const tail = split(command, head, ' ');
80         return head + ' ' + options + ' ' + tail;
81 }
82
83
84 string const dvipdfm_options(BufferParams const & bp)
85 {
86         string result;
87
88         if (bp.papersize != PAPER_CUSTOM) {
89                 string const paper_size = bp.paperSizeName();
90                 if (paper_size != "b5" && paper_size != "foolscap")
91                         result = "-p "+ paper_size;
92
93                 if (bp.orientation == ORIENTATION_LANDSCAPE)
94                         result += " -l";
95         }
96
97         return result;
98 }
99
100
101 class ConverterEqual : public std::binary_function<string, string, bool> {
102 public:
103         ConverterEqual(string const & from, string const & to)
104                 : from_(from), to_(to) {}
105         bool operator()(Converter const & c) const {
106                 return c.from == from_ && c.to == to_;
107         }
108 private:
109         string const from_;
110         string const to_;
111 };
112
113 } // namespace anon
114
115
116 Converter::Converter(string const & f, string const & t,
117                      string const & c, string const & l)
118         : from(f), to(t), command(c), flags(l),
119           From(0), To(0), latex(false), xml(false),
120           original_dir(false), need_aux(false)
121 {}
122
123
124 void Converter::readFlags()
125 {
126         string flag_list(flags);
127         while (!flag_list.empty()) {
128                 string flag_name, flag_value;
129                 flag_list = split(flag_list, flag_value, ',');
130                 flag_value = split(flag_value, flag_name, '=');
131                 if (flag_name == "latex")
132                         latex = true;
133                 else if (flag_name == "xml")
134                         xml = true;
135                 else if (flag_name == "originaldir")
136                         original_dir = true;
137                 else if (flag_name == "needaux")
138                         need_aux = true;
139                 else if (flag_name == "resultdir")
140                         result_dir = (flag_value.empty())
141                                 ? token_base : flag_value;
142                 else if (flag_name == "resultfile")
143                         result_file = flag_value;
144                 else if (flag_name == "parselog")
145                         parselog = flag_value;
146         }
147         if (!result_dir.empty() && result_file.empty())
148                 result_file = "index." + formats.extension(to);
149         //if (!contains(command, token_from))
150         //      latex = true;
151 }
152
153
154 bool operator<(Converter const & a, Converter const & b)
155 {
156         // use the compare_ascii_no_case instead of compare_no_case,
157         // because in turkish, 'i' is not the lowercase version of 'I',
158         // and thus turkish locale breaks parsing of tags.
159         int const i = compare_ascii_no_case(a.From->prettyname(),
160                                             b.From->prettyname());
161         if (i == 0)
162                 return compare_ascii_no_case(a.To->prettyname(),
163                                              b.To->prettyname()) < 0;
164         else
165                 return i < 0;
166 }
167
168
169 Converter const * Converters::getConverter(string const & from,
170                                             string const & to) const
171 {
172         ConverterList::const_iterator const cit =
173                 find_if(converterlist_.begin(), converterlist_.end(),
174                         ConverterEqual(from, to));
175         if (cit != converterlist_.end())
176                 return &(*cit);
177         else
178                 return 0;
179 }
180
181
182 int Converters::getNumber(string const & from, string const & to) const
183 {
184         ConverterList::const_iterator const cit =
185                 find_if(converterlist_.begin(), converterlist_.end(),
186                         ConverterEqual(from, to));
187         if (cit != converterlist_.end())
188                 return distance(converterlist_.begin(), cit);
189         else
190                 return -1;
191 }
192
193
194 void Converters::add(string const & from, string const & to,
195                      string const & command, string const & flags)
196 {
197         formats.add(from);
198         formats.add(to);
199         ConverterList::iterator it = find_if(converterlist_.begin(),
200                                              converterlist_.end(),
201                                              ConverterEqual(from , to));
202
203         Converter converter(from, to, command, flags);
204         if (it != converterlist_.end() && !flags.empty() && flags[0] == '*') {
205                 converter = *it;
206                 converter.command = command;
207                 converter.flags = flags;
208         }
209         converter.readFlags();
210
211         if (converter.latex && (latex_command_.empty() || to == "dvi"))
212                 latex_command_ = subst(command, token_from, "");
213         // If we have both latex & pdflatex, we set latex_command to latex.
214         // The latex_command is used to update the .aux file when running
215         // a converter that uses it.
216
217         if (it == converterlist_.end()) {
218                 converterlist_.push_back(converter);
219         } else {
220                 converter.From = it->From;
221                 converter.To = it->To;
222                 *it = converter;
223         }
224 }
225
226
227 void Converters::erase(string const & from, string const & to)
228 {
229         ConverterList::iterator const it =
230                 find_if(converterlist_.begin(),
231                         converterlist_.end(),
232                         ConverterEqual(from, to));
233         if (it != converterlist_.end())
234                 converterlist_.erase(it);
235 }
236
237
238 // This method updates the pointers From and To in all the converters.
239 // The code is not very efficient, but it doesn't matter as the number
240 // of formats and converters is small.
241 // Furthermore, this method is called only on startup, or after
242 // adding/deleting a format in FormPreferences (the latter calls can be
243 // eliminated if the formats in the Formats class are stored using a map or
244 // a list (instead of a vector), but this will cause other problems).
245 void Converters::update(Formats const & formats)
246 {
247         ConverterList::iterator it = converterlist_.begin();
248         ConverterList::iterator end = converterlist_.end();
249         for (; it != end; ++it) {
250                 it->From = formats.getFormat(it->from);
251                 it->To = formats.getFormat(it->to);
252         }
253 }
254
255
256 // This method updates the pointers From and To in the last converter.
257 // It is called when adding a new converter in FormPreferences
258 void Converters::updateLast(Formats const & formats)
259 {
260         if (converterlist_.begin() != converterlist_.end()) {
261                 ConverterList::iterator it = converterlist_.end() - 1;
262                 it->From = formats.getFormat(it->from);
263                 it->To = formats.getFormat(it->to);
264         }
265 }
266
267
268 void Converters::sort()
269 {
270         std::sort(converterlist_.begin(), converterlist_.end());
271 }
272
273
274 OutputParams::FLAVOR Converters::getFlavor(Graph::EdgePath const & path)
275 {
276         for (Graph::EdgePath::const_iterator cit = path.begin();
277              cit != path.end(); ++cit) {
278                 Converter const & conv = converterlist_[*cit];
279                 if (conv.latex)
280                         if (contains(conv.to, "pdf"))
281                                 return OutputParams::PDFLATEX;
282                 if (conv.xml)
283                         return OutputParams::XML;
284         }
285         return OutputParams::LATEX;
286 }
287
288
289 bool Converters::convert(Buffer const * buffer,
290                          string const & from_file, string const & to_file,
291                          string const & orig_from,
292                          string const & from_format, string const & to_format,
293                          ErrorList & errorList, int conversionflags)
294 {
295         BOOST_ASSERT(absolutePath(from_file));
296         BOOST_ASSERT(absolutePath(to_file));
297         BOOST_ASSERT(absolutePath(orig_from));
298
299         if (from_format == to_format)
300                 return move(from_format, from_file, to_file, false);
301
302         if ((conversionflags & try_cache) &&
303             ConverterCache::get().inCache(orig_from, to_format))
304                 return ConverterCache::get().copy(orig_from, to_format, to_file);
305
306         Graph::EdgePath edgepath = getPath(from_format, to_format);
307         if (edgepath.empty()) {
308                 if (conversionflags & try_default) {
309                         // if no special converter defined, then we take the
310                         // default one from ImageMagic.
311                         string const from_ext = from_format.empty() ?
312                                 getExtension(from_file) :
313                                 formats.extension(from_format);
314                         string const to_ext = formats.extension(to_format);
315                         string const command =
316                                 support::os::python() + ' ' +
317                                 quoteName(libFileSearch("scripts", "convertDefault.py")) +
318                                 ' ' +
319                                 quoteName(from_ext + ':' + from_file) +
320                                 ' ' +
321                                 quoteName(to_ext + ':' + to_file);
322                         lyxerr[Debug::FILES]
323                                 << "No converter defined! "
324                                    "I use convertDefault.py:\n\t"
325                                 << command << endl;
326                         Systemcall one;
327                         one.startscript(Systemcall::Wait, command);
328                         if (isFileReadable(to_file)) {
329                                 if (conversionflags & try_cache)
330                                         ConverterCache::get().add(orig_from,
331                                                         to_format, to_file);
332                                 return true;
333                         }
334                 }
335                 Alert::error(_("Cannot convert file"),
336                              bformat(_("No information for converting %1$s "
337                                                     "format files to %2$s.\n"
338                                                     "Define a converter in the preferences."),
339                                                         from_ascii(from_format), from_ascii(to_format)));
340                 return false;
341         }
342         OutputParams runparams;
343         runparams.flavor = getFlavor(edgepath);
344
345         // Some converters (e.g. lilypond) can only output files to the
346         // current directory, so we need to change the current directory.
347         // This has the added benefit that all other files that may be
348         // generated by the converter are deleted when LyX closes and do not
349         // clutter the real working directory.
350         string path = onlyPath(from_file);
351         Path p(path);
352
353         // empty the error list before any new conversion takes place.
354         errorList.clear();
355
356         bool run_latex = false;
357         string from_base = changeExtension(from_file, "");
358         string to_base = changeExtension(to_file, "");
359         string infile;
360         string outfile = from_file;
361         for (Graph::EdgePath::const_iterator cit = edgepath.begin();
362              cit != edgepath.end(); ++cit) {
363                 Converter const & conv = converterlist_[*cit];
364                 bool dummy = conv.To->dummy() && conv.to != "program";
365                 if (!dummy)
366                         lyxerr[Debug::FILES] << "Converting from  "
367                                << conv.from << " to " << conv.to << endl;
368                 infile = outfile;
369                 outfile = conv.result_dir.empty()
370                         ? changeExtension(from_file, conv.To->extension())
371                         : addName(subst(conv.result_dir,
372                                         token_base, from_base),
373                                   subst(conv.result_file,
374                                         token_base, onlyFilename(from_base)));
375
376                 // if input and output files are equal, we use a
377                 // temporary file as intermediary (JMarc)
378                 string real_outfile;
379                 if (outfile == infile) {
380                         real_outfile = infile;
381                         outfile = addName(buffer->temppath(), "tmpfile.out");
382                 }
383
384                 if (conv.latex) {
385                         run_latex = true;
386                         string const command = subst(conv.command, token_from, "");
387                         lyxerr[Debug::FILES] << "Running " << command << endl;
388                         if (!runLaTeX(*buffer, command, runparams, errorList))
389                                 return false;
390                 } else {
391                         if (conv.need_aux && !run_latex
392                             && !latex_command_.empty()) {
393                                 lyxerr[Debug::FILES]
394                                         << "Running " << latex_command_
395                                         << " to update aux file"<<  endl;
396                                 runLaTeX(*buffer, latex_command_, runparams, errorList);
397                         }
398
399                         string const infile2 = (conv.original_dir)
400                                 ? infile : makeRelPath(infile, path);
401                         string const outfile2 = (conv.original_dir)
402                                 ? outfile : makeRelPath(outfile, path);
403
404                         string command = conv.command;
405                         command = subst(command, token_from, quoteName(infile2));
406                         command = subst(command, token_base, quoteName(from_base));
407                         command = subst(command, token_to, quoteName(outfile2));
408                         command = libScriptSearch(command);
409
410                         if (!conv.parselog.empty())
411                                 command += " 2> " + quoteName(infile2 + ".out");
412
413                         if (conv.from == "dvi" && conv.to == "ps")
414                                 command = add_options(command,
415                                                       buffer->params().dvips_options());
416                         else if (conv.from == "dvi" && prefixIs(conv.to, "pdf"))
417                                 command = add_options(command,
418                                                       dvipdfm_options(buffer->params()));
419
420                         lyxerr[Debug::FILES] << "Calling " << command << endl;
421                         if (buffer)
422                                 buffer->message(_("Executing command: ")
423                                 + from_utf8(command));
424
425                         Systemcall::Starttype const type = (dummy)
426                                 ? Systemcall::DontWait : Systemcall::Wait;
427                         Systemcall one;
428                         int res;
429                         if (conv.original_dir) {
430                                 Path p(buffer->filePath());
431                                 res = one.startscript(type, command);
432                         } else
433                                 res = one.startscript(type, command);
434
435                         if (!real_outfile.empty()) {
436                                 Mover const & mover = movers(conv.to);
437                                 if (!mover.rename(outfile, real_outfile))
438                                         res = -1;
439                                 else
440                                         lyxerr[Debug::FILES]
441                                                 << "renaming file " << outfile
442                                                 << " to " << real_outfile
443                                                 << endl;
444                                 // Finally, don't forget to tell any future
445                                 // converters to use the renamed file...
446                                 outfile = real_outfile;
447                         }
448
449                         if (!conv.parselog.empty()) {
450                                 string const logfile =  infile2 + ".log";
451                                 string const script = libScriptSearch(conv.parselog);
452                                 string const command2 = script +
453                                         " < " + quoteName(infile2 + ".out") +
454                                         " > " + quoteName(logfile);
455                                 one.startscript(Systemcall::Wait, command2);
456                                 if (!scanLog(*buffer, command, logfile, errorList))
457                                         return false;
458                         }
459
460                         if (res) {
461                                 if (conv.to == "program") {
462                                         Alert::error(_("Build errors"),
463                                                 _("There were errors during the build process."));
464                                 } else {
465 // FIXME: this should go out of here. For example, here we cannot say if
466 // it is a document (.lyx) or something else. Same goes for elsewhere.
467                                         Alert::error(_("Cannot convert file"),
468                                                 bformat(_("An error occurred whilst running %1$s"),
469                                                 from_ascii(command.substr(0, 50))));
470                                 }
471                                 return false;
472                         }
473                 }
474         }
475
476         Converter const & conv = converterlist_[edgepath.back()];
477         if (conv.To->dummy())
478                 return true;
479
480         if (!conv.result_dir.empty()) {
481                 // The converter has put the file(s) in a directory.
482                 // In this case we ignore the given to_file.
483                 if (from_base != to_base) {
484                         string const from = subst(conv.result_dir,
485                                             token_base, from_base);
486                         string const to = subst(conv.result_dir,
487                                           token_base, to_base);
488                         Mover const & mover = movers(conv.from);
489                         if (!mover.rename(from, to)) {
490                                 Alert::error(_("Cannot convert file"),
491                                         bformat(_("Could not move a temporary directory from %1$s to %2$s."),
492                                                 from_ascii(from), from_ascii(to)));
493                                 return false;
494                         }
495                 }
496                 return true;
497         } else {
498                 if (conversionflags & try_cache)
499                         ConverterCache::get().add(orig_from, to_format, outfile);
500                 return move(conv.to, outfile, to_file, conv.latex);
501         }
502 }
503
504
505 bool Converters::move(string const & fmt,
506                       string const & from, string const & to, bool copy)
507 {
508         if (from == to)
509                 return true;
510
511         bool no_errors = true;
512         string const path = onlyPath(from);
513         string const base = onlyFilename(changeExtension(from, ""));
514         string const to_base = changeExtension(to, "");
515         string const to_extension = getExtension(to);
516
517         vector<string> files = dirList(onlyPath(from), getExtension(from));
518         for (vector<string>::const_iterator it = files.begin();
519              it != files.end(); ++it)
520                 if (prefixIs(*it, base)) {
521                         string const from2 = path + *it;
522                         string to2 = to_base + it->substr(base.length());
523                         to2 = changeExtension(to2, to_extension);
524                         lyxerr[Debug::FILES] << "moving " << from2
525                                              << " to " << to2 << endl;
526
527                         Mover const & mover = movers(fmt);
528                         bool const moved = copy
529                                 ? mover.copy(from2, to2)
530                                 : mover.rename(from2, to2);
531                         if (!moved && no_errors) {
532                                 Alert::error(_("Cannot convert file"),
533                                         bformat(copy ?
534                                                 _("Could not copy a temporary file from %1$s to %2$s.") :
535                                                 _("Could not move a temporary file from %1$s to %2$s."),
536                                                 from_ascii(from2), from_ascii(to2)));
537                                 no_errors = false;
538                         }
539                 }
540         return no_errors;
541 }
542
543
544 bool Converters::formatIsUsed(string const & format)
545 {
546         ConverterList::const_iterator cit = converterlist_.begin();
547         ConverterList::const_iterator end = converterlist_.end();
548         for (; cit != end; ++cit) {
549                 if (cit->from == format || cit->to == format)
550                         return true;
551         }
552         return false;
553 }
554
555
556 bool Converters::scanLog(Buffer const & buffer, string const & /*command*/,
557                          string const & filename, ErrorList & errorList)
558 {
559         OutputParams runparams;
560         runparams.flavor = OutputParams::LATEX;
561         LaTeX latex("", runparams, filename, "");
562         TeXErrors terr;
563         int const result = latex.scanLogFile(terr);
564
565         if (result & LaTeX::ERRORS)
566                 bufferErrors(buffer, terr, errorList);
567
568         return true;
569 }
570
571
572 namespace {
573
574 class showMessage : public std::unary_function<docstring, void>, public boost::signals::trackable {
575 public:
576         showMessage(Buffer const & b) : buffer_(b) {};
577         void operator()(docstring const & m) const
578         {
579                 buffer_.message(m);
580         }
581 private:
582         Buffer const & buffer_;
583 };
584
585 }
586
587
588 bool Converters::runLaTeX(Buffer const & buffer, string const & command,
589                           OutputParams const & runparams, ErrorList & errorList)
590 {
591         buffer.busy(true);
592         buffer.message(_("Running LaTeX..."));
593
594         runparams.document_language = buffer.params().language->babel();
595
596         // do the LaTeX run(s)
597         string const name = buffer.getLatexName();
598         LaTeX latex(command, runparams, name, buffer.filePath());
599         TeXErrors terr;
600         showMessage show(buffer);
601         latex.message.connect(show);
602         int const result = latex.run(terr);
603
604         if (result & LaTeX::ERRORS)
605                 bufferErrors(buffer, terr, errorList);
606
607         // check return value from latex.run().
608         if ((result & LaTeX::NO_LOGFILE)) {
609                 docstring const str =
610                         bformat(_("LaTeX did not run successfully. "
611                                                "Additionally, LyX could not locate "
612                                                "the LaTeX log %1$s."), from_utf8(name));
613                 Alert::error(_("LaTeX failed"), str);
614         } else if (result & LaTeX::NO_OUTPUT) {
615                 Alert::warning(_("Output is empty"),
616                                _("An empty output file was generated."));
617         }
618
619
620         buffer.busy(false);
621
622         int const ERROR_MASK =
623                         LaTeX::NO_LOGFILE |
624                         LaTeX::ERRORS |
625                         LaTeX::NO_OUTPUT;
626
627         return (result & ERROR_MASK) == 0;
628
629 }
630
631
632
633 void Converters::buildGraph()
634 {
635         G_.init(formats.size());
636         ConverterList::iterator beg = converterlist_.begin();
637         ConverterList::iterator const end = converterlist_.end();
638         for (ConverterList::iterator it = beg; it != end ; ++it) {
639                 int const s = formats.getNumber(it->from);
640                 int const t = formats.getNumber(it->to);
641                 G_.addEdge(s,t);
642         }
643 }
644
645
646 std::vector<Format const *> const
647 Converters::intToFormat(std::vector<int> const & input)
648 {
649         vector<Format const *> result(input.size());
650
651         vector<int>::const_iterator it = input.begin();
652         vector<int>::const_iterator const end = input.end();
653         vector<Format const *>::iterator rit = result.begin();
654         for ( ; it != end; ++it, ++rit) {
655                 *rit = &formats.get(*it);
656         }
657         return result;
658 }
659
660
661 vector<Format const *> const
662 Converters::getReachableTo(string const & target, bool const clear_visited)
663 {
664         vector<int> const & reachablesto =
665                 G_.getReachableTo(formats.getNumber(target), clear_visited);
666
667         return intToFormat(reachablesto);
668 }
669
670
671 vector<Format const *> const
672 Converters::getReachable(string const & from, bool const only_viewable,
673                          bool const clear_visited)
674 {
675         vector<int> const & reachables =
676                 G_.getReachable(formats.getNumber(from),
677                                 only_viewable,
678                                 clear_visited);
679
680         return intToFormat(reachables);
681 }
682
683
684 bool Converters::isReachable(string const & from, string const & to)
685 {
686         return G_.isReachable(formats.getNumber(from),
687                               formats.getNumber(to));
688 }
689
690
691 Graph::EdgePath const
692 Converters::getPath(string const & from, string const & to)
693 {
694         return G_.getPath(formats.getNumber(from),
695                           formats.getNumber(to));
696 }
697
698
699 /// The global instance
700 Converters converters;
701
702 // The global copy after reading lyxrc.defaults
703 Converters system_converters;
704
705
706 } // namespace lyx