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