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 string paper_size = converters.papersize(buffer);
177 if (paper_size == "letter")
179 command += " " + paper_size;
180 if (buffer->params.orientation
181 == BufferParams::ORIENTATION_LANDSCAPE)
185 command += " " + QuoteName(OnlyFilename((filename)));
187 lyxerr << "Executing command: " << command << endl;
188 ShowMessage(buffer, _("Executing command:"), command);
190 Path p(OnlyPath(filename));
192 int const res = one.startscript(Systemcalls::SystemDontWait, command);
195 WriteAlert(_("Can not view file"),
196 _("Error while executing"),
197 command.substr(0, 50));
204 string const Formats::PrettyName(string const & name) const
206 Format const * format = GetFormat(name);
208 return format->prettyname();
214 string const Formats::Extension(string const & name) const
216 Format const * format = GetFormat(name);
218 return format->extension();
223 //////////////////////////////////////////////////////////////////////////////
225 void Converter::ReadFlags()
227 string flag_list(flags);
228 while (!flag_list.empty()) {
229 string flag_name, flag_value;
230 flag_list = split(flag_list, flag_value, ',');
231 flag_value = split(flag_value, flag_name, '=');
232 if (flag_name == "latex")
234 else if (flag_name == "originaldir")
236 else if (flag_name == "needaux")
238 else if (flag_name == "resultdir")
239 result_dir = (flag_value.empty())
240 ? token_base : flag_value;
241 else if (flag_name == "resultfile")
242 result_file = flag_value;
243 else if (flag_name == "parselog")
244 parselog = flag_value;
246 if (!result_dir.empty() && result_file.empty())
247 result_file = "index." + formats.Extension(to);
248 //if (!contains(command, token_from))
253 bool operator<(Converter const & a, Converter const & b)
255 int const i = compare_no_case(a.From->prettyname(),
256 b.From->prettyname());
258 return compare_no_case(a.To->prettyname(), b.To->prettyname())
264 //////////////////////////////////////////////////////////////////////////////
266 class compare_Converter {
268 compare_Converter(string const & f, string const & t)
270 bool operator()(Converter const & c) {
271 return c.from == from && c.to == to;
279 Converter const * Converters::GetConverter(string const & from,
282 ConverterList::const_iterator cit =
283 find_if(converterlist.begin(), converterlist.end(),
284 compare_Converter(from, to));
285 if (cit != converterlist.end())
292 int Converters::GetNumber(string const & from, string const & to)
294 ConverterList::const_iterator cit =
295 find_if(converterlist.begin(), converterlist.end(),
296 compare_Converter(from, to));
297 if (cit != converterlist.end())
298 return cit - converterlist.begin();
304 void Converters::Add(string const & from, string const & to,
305 string const & command, string const & flags)
309 ConverterList::iterator it = find_if(converterlist.begin(),
311 compare_Converter(from, to));
313 Converter converter(from, to, command, flags);
314 if (it != converterlist.end() && !flags.empty() && flags[0] == '*') {
316 converter.command = command;
317 converter.flags = flags;
319 converter.ReadFlags();
321 if (converter.latex && (latex_command.empty() || to == "dvi"))
322 latex_command = subst(command, token_from, "");
323 // If we have both latex & pdflatex, we set latex_command to latex.
324 // The latex_command is used to update the .aux file when running
325 // a converter that uses it.
327 if (it == converterlist.end())
328 converterlist.push_back(converter);
330 converter.From = it->From;
331 converter.To = it->To;
337 void Converters::Delete(string const & from, string const & to)
339 ConverterList::iterator it = find_if(converterlist.begin(),
341 compare_Converter(from, to));
342 if (it != converterlist.end())
343 converterlist.erase(it);
347 // This method updates the pointers From and To in all the converters.
348 // The code is not very efficient, but it doesn't matter as the number
349 // of formats and converters is small.
350 // Furthermore, this method is called only on startup, or after
351 // adding/deleting a format in FormPreferences (the latter calls can be
352 // eliminated if the formats in the Formats class are stored using a map or
353 // a list (instead of a vector), but this will cause other problems).
354 void Converters::Update(Formats const & formats)
356 for (ConverterList::iterator it = converterlist.begin();
357 it != converterlist.end(); ++it) {
358 it->From = formats.GetFormat(it->from);
359 it->To = formats.GetFormat(it->to);
364 // This method updates the pointers From and To in the last converter.
365 // It is called when adding a new converter in FormPreferences
366 void Converters::UpdateLast(Formats const & formats)
368 if (converterlist.begin() != converterlist.end()) {
369 ConverterList::iterator it = converterlist.end()-1;
370 it->From = formats.GetFormat(it->from);
371 it->To = formats.GetFormat(it->to);
376 void Converters::Sort()
378 sort(converterlist.begin(), converterlist.end());
382 int Converters::BFS_init(string const & start, bool clear_visited)
384 int const s = formats.GetNumber(start);
390 fill(visited.begin(), visited.end(), false);
391 if (visited[s] == false) {
399 vector<Format const *> const
400 Converters::GetReachableTo(string const & target, bool clear_visited)
402 vector<Format const *> result;
403 int const s = BFS_init(target, clear_visited);
408 int const i = Q.front();
410 if (i != s || target != "lyx")
411 result.push_back(&formats.Get(i));
412 for (vector<int>::iterator it = vertices[i].in_vertices.begin();
413 it != vertices[i].in_vertices.end(); ++it)
424 vector<Format const *> const
425 Converters::GetReachable(string const & from, bool only_viewable,
428 vector<Format const *> result;
430 if (BFS_init(from, clear_visited) < 0)
434 int const i = Q.front();
436 Format const & format = formats.Get(i);
437 if (format.name() == "lyx")
439 if (!only_viewable || !format.viewer().empty() ||
440 format.IsChildFormat())
441 result.push_back(&format);
442 for (vector<int>::iterator it = vertices[i].out_vertices.begin();
443 it != vertices[i].out_vertices.end(); ++it)
454 bool Converters::IsReachable(string const & from, string const & to)
459 int const s = BFS_init(from);
460 int const t = formats.GetNumber(to);
465 int const i = Q.front();
469 for (vector<int>::iterator it = vertices[i].out_vertices.begin();
470 it != vertices[i].out_vertices.end(); ++it)
481 Converters::EdgePath const
482 Converters::GetPath(string const & from, string const & to)
488 int const s = BFS_init(from);
489 int t = formats.GetNumber(to);
493 vector<int> prev_edge(formats.size());
494 vector<int> prev_vertex(formats.size());
498 int const i = Q.front();
504 for (vector<int>::iterator it = vertices[i].out_vertices.begin();
505 it != vertices[i].out_vertices.end(); ++it)
510 int const k = it - vertices[i].out_vertices.begin();
511 prev_edge[j] = vertices[i].out_edges[k];
519 path.push_back(prev_edge[t]);
522 reverse(path.begin(), path.end());
527 bool Converters::UsePdflatex(EdgePath const & path)
529 for (EdgePath::const_iterator cit = path.begin();
530 cit != path.end(); ++cit) {
531 Converter const & conv = converterlist[*cit];
533 return contains(conv.to, "pdf");
539 bool Converters::Convert(Buffer const * buffer,
540 string const & from_file, string const & to_file_base,
541 string const & from_format, string const & to_format,
544 to_file = ChangeExtension(to_file_base,
545 formats.Extension(to_format));
547 if (from_format == to_format)
548 return Move(from_file, to_file, false);
550 EdgePath edgepath = GetPath(from_format, to_format);
551 if (edgepath.empty()) {
552 WriteAlert(_("Can not convert file"),
553 _("No information for converting from ")
554 + formats.PrettyName(from_format) + _(" to ")
555 + formats.PrettyName(to_format));
559 string path = OnlyPath(from_file);
562 bool run_latex = false;
563 string from_base = ChangeExtension(from_file, "");
564 string to_base = ChangeExtension(to_file, "");
566 string outfile = from_file;
567 for (EdgePath::const_iterator cit = edgepath.begin();
568 cit != edgepath.end(); ++cit) {
569 Converter const & conv = converterlist[*cit];
570 bool dummy = conv.To->dummy() && conv.to != "program";
572 lyxerr << "Converting from "
573 << conv.from << " to " << conv.to << endl;
575 outfile = conv.result_dir.empty()
576 ? ChangeExtension(from_file, conv.To->extension())
577 : AddName(subst(conv.result_dir,
578 token_base, from_base),
579 subst(conv.result_file,
580 token_base, OnlyFilename(from_base)));
584 string command = subst(conv.command, token_from, "");
585 lyxerr << "Running " << command << endl;
586 if (!runLaTeX(buffer, command))
589 if (conv.need_aux && !run_latex
590 && !latex_command.empty()) {
591 lyxerr << "Running " << latex_command
592 << " to update aux file"<< endl;
593 runLaTeX(buffer, latex_command);
596 string infile2 = (conv.original_dir)
597 ? infile : MakeRelPath(infile, path);
598 string outfile2 = (conv.original_dir)
599 ? outfile : MakeRelPath(outfile, path);
601 string command = conv.command;
602 command = subst(command, token_from, QuoteName(infile2));
603 command = subst(command, token_base, QuoteName(from_base));
604 command = subst(command, token_to, QuoteName(outfile2));
606 if (!conv.parselog.empty())
607 command += " 2> " + QuoteName(infile2 + ".out");
609 if (conv.from == "dvi" && conv.to == "ps")
610 command = add_options(command,
611 dvips_options(buffer));
612 else if (conv.from == "dvi" && prefixIs(conv.to, "pdf"))
613 command = add_options(command,
614 dvipdfm_options(buffer));
616 lyxerr << "Calling " << command << endl;
618 ShowMessage(buffer, _("Executing command:"), command);
620 Systemcalls::Starttype type = (dummy)
621 ? Systemcalls::SystemDontWait : Systemcalls::System;
624 if (conv.original_dir && buffer) {
625 Path p(buffer->filepath);
626 res = one.startscript(type, command);
628 res = one.startscript(type, command);
630 if (!conv.parselog.empty()) {
631 string const logfile = infile2 + ".log";
632 string const command2 = conv.parselog +
633 " < " + QuoteName(infile2 + ".out") +
634 " > " + QuoteName(logfile);
635 one.startscript(Systemcalls::System, command2);
636 if (!scanLog(buffer, command, logfile))
641 if (conv.to == "program")
642 WriteAlert(_("There were errors during the Build process."),
643 _("You should try to fix them."));
645 WriteAlert(_("Can not convert file"),
646 "Error while executing",
647 command.substr(0, 50));
653 Converter const & conv = converterlist[edgepath.back()];
654 if (conv.To->dummy())
658 if (!conv.result_dir.empty()) {
659 to_file = AddName(subst(conv.result_dir, token_base, to_base),
660 subst(conv.result_file,
661 token_base, OnlyFilename(to_base)));
662 if (from_base != to_base) {
663 string from = subst(conv.result_dir,
664 token_base, from_base);
665 string to = subst(conv.result_dir,
666 token_base, to_base);
667 if (!lyx::rename(from, to)) {
668 WriteAlert(_("Error while trying to move directory:"),
675 return Move(outfile, to_file, conv.latex);
678 // If from = /path/file.ext and to = /path2/file2.ext2 then this method
679 // moves each /path/file*.ext file to /path2/file2*.ext2'
680 bool Converters::Move(string const & from, string const & to, bool copy)
685 bool no_errors = true;
686 string const path = OnlyPath(from);
687 string const base = OnlyFilename(ChangeExtension(from, ""));
688 string const to_base = ChangeExtension(to, "");
689 string const to_extension = GetExtension(to);
691 vector<string> files = DirList(OnlyPath(from), GetExtension(from));
692 for (vector<string>::const_iterator it = files.begin();
693 it != files.end(); ++it)
694 if (prefixIs(*it, base)) {
695 string from2 = path + *it;
696 string to2 = to_base + (*it).substr(base.length());
697 to2 = ChangeExtension(to2, to_extension);
698 lyxerr << "moving " << from2 << " to " << to2 << endl;
700 ? lyx::copy(from2, to2)
701 : lyx::rename(from2, to2);
702 if (!moved && no_errors) {
703 WriteAlert(_("Error while trying to move file:"),
704 from2, _("to ") + to2);
711 bool Converters::Convert(Buffer const * buffer,
712 string const & from_file, string const & to_file_base,
713 string const & from_format, string const & to_format)
716 return Convert(buffer, from_file, to_file_base, from_format, to_format,
722 void Converters::BuildGraph()
724 vertices = vector<Vertex>(formats.size());
725 visited.resize(formats.size());
727 for (ConverterList::iterator it = converterlist.begin();
728 it != converterlist.end(); ++it) {
729 int const s = formats.GetNumber(it->from);
730 int const t = formats.GetNumber(it->to);
731 vertices[t].in_vertices.push_back(s);
732 vertices[s].out_vertices.push_back(t);
733 vertices[s].out_edges.push_back(it - converterlist.begin());
738 bool Converters::FormatIsUsed(string const & format)
740 for (ConverterList::const_iterator cit = converterlist.begin();
741 cit != converterlist.end(); ++cit)
742 if (cit->from == format || cit->to == format)
748 bool Converters::scanLog(Buffer const * buffer, string const & command,
749 string const & filename)
754 BufferView * bv = buffer->getUser();
755 bool need_redraw = false;
758 // Remove all error insets
759 need_redraw = bv->removeAutoInsets();
762 LaTeX latex("", filename, "");
764 int result = latex.scanLogFile(terr);
766 if ((result & LaTeX::ERRORS)) {
767 // Insert all errors as errors boxes
768 bv->insertErrors(terr);
773 bv->fitCursor(bv->text);
778 if ((result & LaTeX::ERRORS)) {
779 int num_errors = latex.getNumErrors();
782 if (num_errors == 1) {
783 s = _("One error detected");
784 t = _("You should try to fix it.");
786 s = tostr(num_errors);
787 s += _(" errors detected.");
788 t = _("You should try to fix them.");
791 split(command, head, ' ');
792 WriteAlert(_("There were errors during running of ") + head,
795 } else if (result & LaTeX::NO_OUTPUT) {
796 string const s = _("The operation resulted in");
797 string const t = _("an empty file.");
798 WriteAlert(_("Resulting file is empty"), s, t);
805 bool Converters::runLaTeX(Buffer const * buffer, string const & command)
810 BufferView * bv = buffer->getUser();
811 string name = buffer->getLatexName();
812 bool need_redraw = false;
816 bv->owner()->getMiniBuffer()->Set(_("Running LaTeX..."));
817 // Remove all error insets
818 need_redraw = bv->removeAutoInsets();
822 // do the LaTex run(s)
824 LaTeX latex(command, name, buffer->filepath);
825 int result = latex.run(terr,
826 bv ? bv->owner()->getMiniBuffer() : 0);
830 if ((result & LaTeX::ERRORS)) {
831 // Insert all errors as errors boxes
832 bv->insertErrors(terr);
836 // if we removed error insets before we ran LaTeX or if we inserted
837 // error insets after we ran LaTeX this must be run:
840 bv->fitCursor(bv->text);
844 // check return value from latex.run().
845 if ((result & LaTeX::NO_LOGFILE)) {
846 WriteAlert(_("LaTeX did not work!"),
847 _("Missing log file:"), name);
848 } else if ((result & LaTeX::ERRORS)) {
849 int num_errors = latex.getNumErrors();
852 if (num_errors == 1) {
853 s = _("One error detected");
854 t = _("You should try to fix it.");
856 s = tostr(num_errors);
857 s += _(" errors detected.");
858 t = _("You should try to fix them.");
860 WriteAlert(_("There were errors during the LaTeX run."),
862 } else if (result & LaTeX::NO_OUTPUT) {
863 string const s = _("The operation resulted in");
864 string const t = _("an empty file.");
865 WriteAlert(_("Resulting file is empty"), s, t);
871 int const ERROR_MASK =
876 return (result & ERROR_MASK) == 0;
881 string const Converters::papersize(Buffer const * buffer)
883 char real_papersize = buffer->params.papersize;
884 if (real_papersize == BufferParams::PAPER_DEFAULT)
885 real_papersize = lyxrc.default_papersize;
887 switch (real_papersize) {
888 case BufferParams::PAPER_A3PAPER:
890 case BufferParams::PAPER_A4PAPER:
892 case BufferParams::PAPER_A5PAPER:
894 case BufferParams::PAPER_B5PAPER:
896 case BufferParams::PAPER_EXECUTIVEPAPER:
898 case BufferParams::PAPER_LEGALPAPER:
900 case BufferParams::PAPER_USLETTER:
907 string const Converters::dvips_options(Buffer const * buffer)
913 if (buffer->params.use_geometry
914 && buffer->params.papersize2 == BufferParams::VM_PAPER_CUSTOM
915 && !lyxrc.print_paper_dimension_flag.empty()
916 && !buffer->params.paperwidth.empty()
917 && !buffer->params.paperheight.empty()) {
918 // using a custom papersize
919 result = lyxrc.print_paper_dimension_flag;
920 result += ' ' + buffer->params.paperwidth;
921 result += ',' + buffer->params.paperheight;
923 string paper_option = papersize(buffer);
924 if (paper_option != "letter" ||
925 buffer->params.orientation != BufferParams::ORIENTATION_LANDSCAPE) {
926 // dvips won't accept -t letter -t landscape. In all other
927 // cases, include the paper size explicitly.
928 result = lyxrc.print_paper_flag;
929 result += ' ' + paper_option;
932 if (buffer->params.orientation == BufferParams::ORIENTATION_LANDSCAPE &&
933 buffer->params.papersize2 != BufferParams::VM_PAPER_CUSTOM)
934 result += ' ' + lyxrc.print_landscape_flag;
939 string const Converters::dvipdfm_options(Buffer const * buffer)
945 if (buffer->params.papersize2 != BufferParams::VM_PAPER_CUSTOM) {
946 string paper_size = papersize(buffer);
947 if (paper_size != "b5" && paper_size != "foolscap")
948 result = "-p "+ paper_size;
950 if (buffer->params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
958 vector<Converters::Vertex> Converters::vertices;
961 /// The global instance
963 Converters converters;
965 // The global copy after reading lyxrc.defaults
966 Formats system_formats;
967 Converters system_converters;