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