1 /* This file is part of
2 * ======================================================
4 * LyX, The Document Processor
6 * Copyright 1995 Matthias Ettrich
7 * Copyright 1995-2000 The LyX Team.
9 * ====================================================== */
14 #pragma implementation
19 #include "converter.h"
21 #include "support/syscall.h"
22 #include "support/path.h"
23 #include "support/filetools.h"
25 #include "bufferview_funcs.h"
28 #include "minibuffer.h"
29 #include "lyx_gui_misc.h"
30 #include "lyx_cb.h" // ShowMessage()
31 #include "support/lyxfunctional.h"
41 static string const token_from("$$i");
42 static string const token_base("$$b");
43 static string const token_to("$$o");
45 //////////////////////////////////////////////////////////////////////////////
48 string const add_options(string const & command, string const & options)
51 string const tail = split(command, head, ' ');
52 return head + ' ' + options + ' ' + tail;
55 //////////////////////////////////////////////////////////////////////////////
57 bool Format::dummy() const
59 return extension().empty();
63 bool Format::IsChildFormat() const
67 return isdigit(name_[name_.length() - 1]);
71 string const Format::ParentFormat() const
73 return name_.substr(0, name_.length() - 1);
76 //////////////////////////////////////////////////////////////////////////////
78 // This method should return a reference, and throw an exception
79 // if the format named name cannot be found (Lgb)
80 Format const * Formats::GetFormat(string const & name) const
82 FormatList::const_iterator cit =
83 find_if(formatlist.begin(), formatlist.end(),
84 compare_memfun(&Format::name, name));
85 if (cit != formatlist.end())
92 int Formats::GetNumber(string const & name) const
94 FormatList::const_iterator cit =
95 find_if(formatlist.begin(), formatlist.end(),
96 compare_memfun(&Format::name, name));
97 if (cit != formatlist.end())
98 return cit - formatlist.begin();
104 void Formats::Add(string const & name)
106 if (!GetFormat(name))
107 Add(name, name, name, string());
111 void Formats::Add(string const & name, string const & extension,
112 string const & prettyname, string const & shortcut)
114 FormatList::iterator it =
115 find_if(formatlist.begin(), formatlist.end(),
116 compare_memfun(&Format::name, name));
117 if (it == formatlist.end())
118 formatlist.push_back(Format(name, extension, prettyname,
121 string viewer = it->viewer();
122 *it = Format(name, extension, prettyname, shortcut, viewer);
127 void Formats::Delete(string const & name)
129 FormatList::iterator it =
130 find_if(formatlist.begin(), formatlist.end(),
131 compare_memfun(&Format::name, name));
132 if (it != formatlist.end())
133 formatlist.erase(it);
139 sort(formatlist.begin(), formatlist.end());
143 void Formats::SetViewer(string const & name, string const & command)
146 FormatList::iterator it =
147 find_if(formatlist.begin(), formatlist.end(),
148 compare_memfun(&Format::name, name));
149 if (it != formatlist.end())
150 it->setViewer(command);
154 bool Formats::View(Buffer const * buffer, string const & filename,
155 string const & format_name) const
157 if (filename.empty())
160 Format const * format = GetFormat(format_name);
161 if (format && format->viewer().empty() &&
162 format->IsChildFormat())
163 format = GetFormat(format->ParentFormat());
164 if (!format || format->viewer().empty()) {
165 WriteAlert(_("Can not view file"),
166 _("No information for viewing ")
167 + PrettyName(format_name));
171 string command = format->viewer();
173 if (format_name == "dvi" &&
174 !lyxrc.view_dvi_paper_option.empty()) {
175 command += " " + lyxrc.view_dvi_paper_option;
176 command += " " + converters.dvi_papersize(buffer);
177 if (buffer->params.orientation
178 == BufferParams::ORIENTATION_LANDSCAPE)
182 command += " " + QuoteName(OnlyFilename((filename)));
184 lyxerr << "Executing command: " << command << endl;
185 ShowMessage(buffer, _("Executing command:"), command);
187 Path p(OnlyPath(filename));
189 int const res = one.startscript(Systemcalls::SystemDontWait, command);
192 WriteAlert(_("Can not view file"),
193 _("Error while executing"),
194 command.substr(0, 50));
201 string const Formats::PrettyName(string const & name) const
203 Format const * format = GetFormat(name);
205 return format->prettyname();
211 string const Formats::Extension(string const & name) const
213 Format const * format = GetFormat(name);
215 return format->extension();
220 //////////////////////////////////////////////////////////////////////////////
222 void Converter::ReadFlags()
224 string flag_list(flags);
225 while (!flag_list.empty()) {
226 string flag_name, flag_value;
227 flag_list = split(flag_list, flag_value, ',');
228 flag_value = split(flag_value, flag_name, '=');
229 if (flag_name == "latex")
231 else if (flag_name == "originaldir")
233 else if (flag_name == "needaux")
235 else if (flag_name == "resultdir")
236 result_dir = (flag_value.empty())
237 ? token_base : flag_value;
238 else if (flag_name == "resultfile")
239 result_file = flag_value;
240 else if (flag_name == "parselog")
241 parselog = flag_value;
243 if (!result_dir.empty() && result_file.empty())
244 result_file = "index." + formats.Extension(to);
245 //if (!contains(command, token_from))
250 bool operator<(Converter const & a, Converter const & b)
252 int const i = compare_no_case(a.From->prettyname(),
253 b.From->prettyname());
255 return compare_no_case(a.To->prettyname(), b.To->prettyname())
261 //////////////////////////////////////////////////////////////////////////////
263 class compare_Converter {
265 compare_Converter(string const & f, string const & t)
267 bool operator()(Converter const & c) {
268 return c.from == from && c.to == to;
276 Converter const * Converters::GetConverter(string const & from,
279 ConverterList::const_iterator cit =
280 find_if(converterlist.begin(), converterlist.end(),
281 compare_Converter(from, to));
282 if (cit != converterlist.end())
289 int Converters::GetNumber(string const & from, string const & to)
291 ConverterList::const_iterator cit =
292 find_if(converterlist.begin(), converterlist.end(),
293 compare_Converter(from, to));
294 if (cit != converterlist.end())
295 return cit - converterlist.begin();
301 void Converters::Add(string const & from, string const & to,
302 string const & command, string const & flags)
306 ConverterList::iterator it = find_if(converterlist.begin(),
308 compare_Converter(from, to));
310 Converter converter(from, to, command, flags);
311 if (it != converterlist.end() && !flags.empty() && flags[0] == '*') {
313 converter.command = command;
314 converter.flags = flags;
316 converter.ReadFlags();
318 if (converter.latex && (latex_command.empty() || to == "dvi"))
319 latex_command = subst(command, token_from, "");
320 // If we have both latex & pdflatex, we set latex_command to latex.
321 // The latex_command is used to update the .aux file when running
322 // a converter that uses it.
324 if (it == converterlist.end())
325 converterlist.push_back(converter);
327 converter.From = it->From;
328 converter.To = it->To;
334 void Converters::Delete(string const & from, string const & to)
336 ConverterList::iterator it = find_if(converterlist.begin(),
338 compare_Converter(from, to));
339 if (it != converterlist.end())
340 converterlist.erase(it);
344 // This method updates the pointers From and To in all the converters.
345 // The code is not very efficient, but it doesn't matter as the number
346 // of formats and converters is small.
347 // Furthermore, this method is called only on startup, or after
348 // adding/deleting a format in FormPreferences (the latter calls can be
349 // eliminated if the formats in the Formats class are stored using a map or
350 // a list (instead of a vector), but this will cause other problems).
351 void Converters::Update(Formats const & formats)
353 for (ConverterList::iterator it = converterlist.begin();
354 it != converterlist.end(); ++it) {
355 it->From = formats.GetFormat(it->from);
356 it->To = formats.GetFormat(it->to);
361 // This method updates the pointers From and To in the last converter.
362 // It is called when adding a new converter in FormPreferences
363 void Converters::UpdateLast(Formats const & formats)
365 if (converterlist.begin() != converterlist.end()) {
366 ConverterList::iterator it = converterlist.end()-1;
367 it->From = formats.GetFormat(it->from);
368 it->To = formats.GetFormat(it->to);
373 void Converters::Sort()
375 sort(converterlist.begin(), converterlist.end());
379 int Converters::BFS_init(string const & start, bool clear_visited)
381 int const s = formats.GetNumber(start);
387 fill(visited.begin(), visited.end(), false);
388 if (visited[s] == false) {
396 vector<Format const *> const
397 Converters::GetReachableTo(string const & target, bool clear_visited)
399 vector<Format const *> result;
400 int const s = BFS_init(target, clear_visited);
405 int const i = Q.front();
407 if (i != s || target != "lyx")
408 result.push_back(&formats.Get(i));
409 for (vector<int>::iterator it = vertices[i].in_vertices.begin();
410 it != vertices[i].in_vertices.end(); ++it)
421 vector<Format const *> const
422 Converters::GetReachable(string const & from, bool only_viewable,
425 vector<Format const *> result;
427 if (BFS_init(from, clear_visited) < 0)
431 int const i = Q.front();
433 Format const & format = formats.Get(i);
434 if (format.name() == "lyx")
436 if (!only_viewable || !format.viewer().empty() ||
437 format.IsChildFormat())
438 result.push_back(&format);
439 for (vector<int>::iterator it = vertices[i].out_vertices.begin();
440 it != vertices[i].out_vertices.end(); ++it)
451 bool Converters::IsReachable(string const & from, string const & to)
456 int const s = BFS_init(from);
457 int const t = formats.GetNumber(to);
462 int const i = Q.front();
466 for (vector<int>::iterator it = vertices[i].out_vertices.begin();
467 it != vertices[i].out_vertices.end(); ++it)
478 Converters::EdgePath const
479 Converters::GetPath(string const & from, string const & to)
485 int const s = BFS_init(from);
486 int t = formats.GetNumber(to);
490 vector<int> prev_edge(formats.size());
491 vector<int> prev_vertex(formats.size());
495 int const i = Q.front();
501 for (vector<int>::iterator it = vertices[i].out_vertices.begin();
502 it != vertices[i].out_vertices.end(); ++it)
507 int const k = it - vertices[i].out_vertices.begin();
508 prev_edge[j] = vertices[i].out_edges[k];
516 path.push_back(prev_edge[t]);
519 reverse(path.begin(), path.end());
524 bool Converters::UsePdflatex(EdgePath const & path)
526 for (EdgePath::const_iterator cit = path.begin();
527 cit != path.end(); ++cit) {
528 Converter const & conv = converterlist[*cit];
530 return contains(conv.to, "pdf");
536 bool Converters::Convert(Buffer const * buffer,
537 string const & from_file, string const & to_file_base,
538 string const & from_format, string const & to_format,
541 to_file = ChangeExtension(to_file_base,
542 formats.Extension(to_format));
544 if (from_format == to_format)
545 return Move(from_file, to_file, false);
547 EdgePath edgepath = GetPath(from_format, to_format);
548 if (edgepath.empty()) {
549 WriteAlert(_("Can not convert file"),
550 _("No information for converting from ")
551 + formats.PrettyName(from_format) + _(" to ")
552 + formats.PrettyName(to_format));
556 string path = OnlyPath(from_file);
559 bool run_latex = false;
560 string from_base = ChangeExtension(from_file, "");
561 string to_base = ChangeExtension(to_file, "");
563 string outfile = from_file;
564 for (EdgePath::const_iterator cit = edgepath.begin();
565 cit != edgepath.end(); ++cit) {
566 Converter const & conv = converterlist[*cit];
567 bool dummy = conv.To->dummy() && conv.to != "program";
569 lyxerr << "Converting from "
570 << conv.from << " to " << conv.to << endl;
572 outfile = conv.result_dir.empty()
573 ? ChangeExtension(from_file, conv.To->extension())
574 : AddName(subst(conv.result_dir,
575 token_base, from_base),
576 subst(conv.result_file,
577 token_base, OnlyFilename(from_base)));
581 string command = subst(conv.command, token_from, "");
582 lyxerr << "Running " << command << endl;
583 if (!runLaTeX(buffer, command))
586 if (conv.need_aux && !run_latex
587 && !latex_command.empty()) {
588 lyxerr << "Running " << latex_command
589 << " to update aux file"<< endl;
590 runLaTeX(buffer, latex_command);
593 string infile2 = (conv.original_dir)
594 ? infile : MakeRelPath(infile, path);
595 string outfile2 = (conv.original_dir)
596 ? outfile : MakeRelPath(outfile, path);
598 string command = conv.command;
599 command = subst(command, token_from, QuoteName(infile2));
600 command = subst(command, token_base, QuoteName(from_base));
601 command = subst(command, token_to, QuoteName(outfile2));
603 if (!conv.parselog.empty())
604 command += " 2> " + QuoteName(infile2 + ".out");
606 if (conv.from == "dvi" && conv.to == "ps")
607 command = add_options(command,
608 dvips_options(buffer));
610 lyxerr << "Calling " << command << endl;
612 ShowMessage(buffer, _("Executing command:"), command);
614 Systemcalls::Starttype type = (dummy)
615 ? Systemcalls::SystemDontWait : Systemcalls::System;
618 if (conv.original_dir && buffer) {
619 Path p(buffer->filepath);
620 res = one.startscript(type, command);
622 res = one.startscript(type, command);
624 if (!conv.parselog.empty()) {
625 string const logfile = infile2 + ".log";
626 string const command2 = conv.parselog +
627 " < " + QuoteName(infile2 + ".out") +
628 " > " + QuoteName(logfile);
629 one.startscript(Systemcalls::System, command2);
630 if (!scanLog(buffer, command, logfile))
635 if (conv.to == "program")
636 WriteAlert(_("There were errors during the Build process."),
637 _("You should try to fix them."));
639 WriteAlert(_("Can not convert file"),
640 "Error while executing",
641 command.substr(0, 50));
647 Converter const & conv = converterlist[edgepath.back()];
648 if (conv.To->dummy())
652 if (!conv.result_dir.empty()) {
653 to_file = AddName(subst(conv.result_dir, token_base, to_base),
654 subst(conv.result_file,
655 token_base, OnlyFilename(to_base)));
656 if (from_base != to_base) {
657 string from = subst(conv.result_dir,
658 token_base, from_base);
659 string to = subst(conv.result_dir,
660 token_base, to_base);
661 if (!lyx::rename(from, to)) {
662 WriteAlert(_("Error while trying to move directory:"),
669 return Move(outfile, to_file, conv.latex);
672 // If from = /path/file.ext and to = /path2/file2.ext2 then this method
673 // moves each /path/file*.ext file to /path2/file2*.ext2'
674 bool Converters::Move(string const & from, string const & to, bool copy)
679 bool no_errors = true;
680 string const path = OnlyPath(from);
681 string const base = OnlyFilename(ChangeExtension(from, ""));
682 string const to_base = ChangeExtension(to, "");
683 string const to_extension = GetExtension(to);
685 vector<string> files = DirList(OnlyPath(from), GetExtension(from));
686 for (vector<string>::const_iterator it = files.begin();
687 it != files.end(); ++it)
688 if (prefixIs(*it, base)) {
689 string from2 = path + *it;
690 string to2 = to_base + (*it).substr(base.length());
691 to2 = ChangeExtension(to2, to_extension);
692 lyxerr << "moving " << from2 << " to " << to2 << endl;
694 ? lyx::copy(from2, to2)
695 : lyx::rename(from2, to2);
696 if (!moved && no_errors) {
697 WriteAlert(_("Error while trying to move file:"),
698 from2, _("to ") + to2);
705 bool Converters::Convert(Buffer const * buffer,
706 string const & from_file, string const & to_file_base,
707 string const & from_format, string const & to_format)
710 return Convert(buffer, from_file, to_file_base, from_format, to_format,
716 void Converters::BuildGraph()
718 vertices = vector<Vertex>(formats.size());
719 visited.resize(formats.size());
721 for (ConverterList::iterator it = converterlist.begin();
722 it != converterlist.end(); ++it) {
723 int const s = formats.GetNumber(it->from);
724 int const t = formats.GetNumber(it->to);
725 vertices[t].in_vertices.push_back(s);
726 vertices[s].out_vertices.push_back(t);
727 vertices[s].out_edges.push_back(it - converterlist.begin());
732 bool Converters::FormatIsUsed(string const & format)
734 for (ConverterList::const_iterator cit = converterlist.begin();
735 cit != converterlist.end(); ++cit)
736 if (cit->from == format || cit->to == format)
742 bool Converters::scanLog(Buffer const * buffer, string const & command,
743 string const & filename)
748 BufferView * bv = buffer->getUser();
749 bool need_redraw = false;
752 // Remove all error insets
753 need_redraw = bv->removeAutoInsets();
756 LaTeX latex("", filename, "");
758 int result = latex.scanLogFile(terr);
760 if ((result & LaTeX::ERRORS)) {
761 // Insert all errors as errors boxes
762 bv->insertErrors(terr);
767 bv->fitCursor(bv->text);
772 if ((result & LaTeX::ERRORS)) {
773 int num_errors = latex.getNumErrors();
776 if (num_errors == 1) {
777 s = _("One error detected");
778 t = _("You should try to fix it.");
780 s = tostr(num_errors);
781 s += _(" errors detected.");
782 t = _("You should try to fix them.");
785 split(command, head, ' ');
786 WriteAlert(_("There were errors during running of ") + head,
789 } else if (result & LaTeX::NO_OUTPUT) {
790 string const s = _("The operation resulted in");
791 string const t = _("an empty file.");
792 WriteAlert(_("Resulting file is empty"), s, t);
799 bool Converters::runLaTeX(Buffer const * buffer, string const & command)
804 BufferView * bv = buffer->getUser();
805 string name = buffer->getLatexName();
806 bool need_redraw = false;
810 bv->owner()->getMiniBuffer()->Set(_("Running LaTeX..."));
811 // Remove all error insets
812 need_redraw = bv->removeAutoInsets();
816 // do the LaTex run(s)
818 LaTeX latex(command, name, buffer->filepath);
819 int result = latex.run(terr,
820 bv ? bv->owner()->getMiniBuffer() : 0);
824 if ((result & LaTeX::ERRORS)) {
825 // Insert all errors as errors boxes
826 bv->insertErrors(terr);
830 // if we removed error insets before we ran LaTeX or if we inserted
831 // error insets after we ran LaTeX this must be run:
834 bv->fitCursor(bv->text);
838 // check return value from latex.run().
839 if ((result & LaTeX::NO_LOGFILE)) {
840 WriteAlert(_("LaTeX did not work!"),
841 _("Missing log file:"), name);
842 } else if ((result & LaTeX::ERRORS)) {
843 int num_errors = latex.getNumErrors();
846 if (num_errors == 1) {
847 s = _("One error detected");
848 t = _("You should try to fix it.");
850 s = tostr(num_errors);
851 s += _(" errors detected.");
852 t = _("You should try to fix them.");
854 WriteAlert(_("There were errors during the LaTeX run."),
856 } else if (result & LaTeX::NO_OUTPUT) {
857 string const s = _("The operation resulted in");
858 string const t = _("an empty file.");
859 WriteAlert(_("Resulting file is empty"), s, t);
865 int const ERROR_MASK =
870 return (result & ERROR_MASK) == 0;
875 string const Converters::dvi_papersize(Buffer const * buffer)
877 char real_papersize = buffer->params.papersize;
878 if (real_papersize == BufferParams::PAPER_DEFAULT)
879 real_papersize = lyxrc.default_papersize;
881 switch (real_papersize) {
882 case BufferParams::PAPER_A3PAPER:
884 case BufferParams::PAPER_A4PAPER:
886 case BufferParams::PAPER_A5PAPER:
888 case BufferParams::PAPER_B5PAPER:
890 case BufferParams::PAPER_EXECUTIVEPAPER:
892 case BufferParams::PAPER_LEGALPAPER:
894 case BufferParams::PAPER_USLETTER:
901 string const Converters::dvips_options(Buffer const * buffer)
907 if (buffer->params.use_geometry
908 && buffer->params.papersize2 == BufferParams::VM_PAPER_CUSTOM
909 && !lyxrc.print_paper_dimension_flag.empty()
910 && !buffer->params.paperwidth.empty()
911 && !buffer->params.paperheight.empty()) {
912 // using a custom papersize
913 result = lyxrc.print_paper_dimension_flag;
914 result += ' ' + buffer->params.paperwidth;
915 result += ',' + buffer->params.paperheight;
917 string paper_option = dvi_papersize(buffer);
918 if (paper_option == "us")
919 paper_option = "letter";
920 if (paper_option != "letter" ||
921 buffer->params.orientation != BufferParams::ORIENTATION_LANDSCAPE) {
922 // dvips won't accept -t letter -t landscape. In all other
923 // cases, include the paper size explicitly.
924 result = lyxrc.print_paper_flag;
925 result += ' ' + paper_option;
928 if (buffer->params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
929 result += ' ' + lyxrc.print_landscape_flag;
933 vector<Converters::Vertex> Converters::vertices;
936 /// The global instance
938 Converters converters;
940 // The global copy after reading lyxrc.defaults
941 Formats system_formats;
942 Converters system_converters;