1 /* This file is part of
2 * ======================================================
4 * LyX, The Document Processor
6 * Copyright 1995 Matthias Ettrich
7 * Copyright 1995-2001 The LyX Team.
9 * This file is Copyright 1996-2001
12 * ======================================================
26 #include <sys/types.h>
36 #pragma implementation
40 #include "bufferlist.h"
42 #include "lyx_gui_misc.h"
43 #include "LyXAction.h"
46 #include "tex-strings.h"
48 #include "bufferview_funcs.h"
51 #include "mathed/formulamacro.h"
52 #include "mathed/formula.h"
53 #include "insets/inset.h"
54 #include "insets/inseterror.h"
55 #include "insets/insetlabel.h"
56 #include "insets/insetref.h"
57 #include "insets/inseturl.h"
58 #include "insets/insetinfo.h"
59 #include "insets/insetquotes.h"
60 #include "insets/insetlatexaccent.h"
61 #include "insets/insetbib.h"
62 #include "insets/insetcite.h"
63 #include "insets/insetexternal.h"
64 #include "insets/insetindex.h"
65 #include "insets/insetinclude.h"
66 #include "insets/insettoc.h"
67 #include "insets/insetparent.h"
68 #include "insets/insetspecialchar.h"
69 #include "insets/figinset.h"
70 #include "insets/insettext.h"
71 #include "insets/insetert.h"
72 #include "insets/insetgraphics.h"
73 #include "insets/insetfoot.h"
74 #include "insets/insetmarginal.h"
75 #include "insets/insetminipage.h"
76 #include "insets/insetfloat.h"
77 #include "insets/insetlist.h"
78 #include "insets/insettabular.h"
79 #include "insets/insettheorem.h"
80 #include "insets/insetcaption.h"
81 #include "insets/insetfloatlist.h"
82 #include "support/filetools.h"
83 #include "support/path.h"
84 #include "support/os.h"
89 #include "LaTeXFeatures.h"
90 #include "support/syscall.h"
91 #include "support/lyxlib.h"
92 #include "support/FileInfo.h"
93 #include "support/lyxmanip.h"
97 #include "lyx_gui_misc.h" // WarnReadonly()
98 #include "frontends/Dialogs.h"
100 #include "exporter.h"
101 #include "Lsstream.h"
102 #include "converter.h"
103 #include "BufferView.h"
104 #include "ParagraphParameters.h"
106 using std::stringstream;
115 using std::make_pair;
123 // all these externs should eventually be removed.
124 extern BufferList bufferlist;
126 extern LyXAction lyxaction;
130 const int LYX_FORMAT = 220;
134 extern int tex_code_break_column;
137 Buffer::Buffer(string const & file, bool ronly)
139 lyxerr[Debug::INFO] << "Buffer::Buffer()" << endl;
141 filepath = OnlyPath(file);
150 if (read_only || (lyxrc.use_tempdir)) {
151 tmppath = CreateBufferTmpDir();
152 } else tmppath.erase();
158 lyxerr[Debug::INFO] << "Buffer::~Buffer()" << endl;
159 // here the buffer should take care that it is
160 // saved properly, before it goes into the void.
162 // make sure that views using this buffer
167 if (!tmppath.empty()) {
168 DestroyBufferTmpDir(tmppath);
171 Paragraph * par = paragraph;
174 tmppar = par->next();
182 string const Buffer::getLatexName(bool no_path) const
184 string name = ChangeExtension(MakeLatexName(filename), ".tex");
186 return OnlyFilename(name);
192 pair<Buffer::LogType, string> const Buffer::getLogName(void) const
194 string const filename = getLatexName(false);
196 if (filename.empty())
197 return make_pair(Buffer::latexlog, string());
199 string path = OnlyPath(filename);
201 if (lyxrc.use_tempdir || (IsDirWriteable(path) < 1))
204 string const fname = AddName(path,
205 OnlyFilename(ChangeExtension(filename,
208 AddName(path, OnlyFilename(
209 ChangeExtension(filename,
210 formats.Extension("literate") + ".out")));
212 // If no Latex log or Build log is newer, show Build log
214 FileInfo const f_fi(fname);
215 FileInfo const b_fi(bname);
218 (!f_fi.exist() || f_fi.getModificationTime() < b_fi.getModificationTime())) {
219 lyxerr[Debug::FILES] << "Log name calculated as : " << bname << endl;
220 return make_pair(Buffer::buildlog, bname);
222 lyxerr[Debug::FILES] << "Log name calculated as : " << fname << endl;
223 return make_pair(Buffer::latexlog, fname);
227 void Buffer::setReadonly(bool flag)
229 if (read_only != flag) {
232 users->owner()->getDialogs()->updateBufferDependent(false);
235 WarnReadonly(filename);
240 bool Buffer::saveParamsAsDefaults() // const
242 string const fname = AddName(AddPath(user_lyxdir, "templates/"),
244 Buffer defaults = Buffer(fname);
246 // Use the current buffer's parameters as default
247 defaults.params = params;
249 // add an empty paragraph. Is this enough?
250 defaults.paragraph = new Paragraph;
252 return defaults.writeFile(defaults.filename, false);
256 /// Update window titles of all users
257 // Should work on a list
258 void Buffer::updateTitles() const
260 if (users) users->owner()->updateWindowTitle();
264 /// Reset autosave timer of all users
265 // Should work on a list
266 void Buffer::resetAutosaveTimers() const
268 if (users) users->owner()->resetAutosaveTimer();
272 void Buffer::setFileName(string const & newfile)
274 filename = MakeAbsPath(newfile);
275 filepath = OnlyPath(filename);
276 setReadonly(IsFileWriteable(filename) == 0);
281 // We'll remove this later. (Lgb)
284 string last_inset_read;
285 string inset_ert_contents;
286 bool ert_active = false;
287 bool in_tabular = false;
293 // candidate for move to BufferView
294 // (at least some parts in the beginning of the func)
297 // changed to be public and have one parameter
298 // if par = 0 normal behavior
299 // else insert behavior
300 // Returns false if "\the_end" is not read for formats >= 2.13. (Asger)
301 bool Buffer::readLyXformat2(LyXLex & lex, Paragraph * par)
304 inset_ert_contents.erase();
310 Paragraph::depth_type depth = 0;
311 bool the_end_read = false;
313 Paragraph * first_par = 0;
314 LyXFont font(LyXFont::ALL_INHERIT, params.language);
315 if (file_format < 216 && params.language->lang() == "hebrew")
316 font.setLanguage(default_language);
321 // We are inserting into an existing document
322 users->text->breakParagraph(users);
323 first_par = users->text->firstParagraph();
326 // We don't want to adopt the parameters from the
327 // document we insert, so we skip until the text begins:
330 string const pretoken = lex.GetString();
331 if (pretoken == "\\layout") {
332 lex.pushToken(pretoken);
340 string const token = lex.GetString();
342 if (token.empty()) continue;
344 lyxerr[Debug::PARSER] << "Handling token: `"
345 << token << "'" << endl;
348 parseSingleLyXformat2Token(lex, par, first_par,
356 paragraph = first_par;
362 void Buffer::insertErtContents(Paragraph * par, int & pos,
363 LyXFont const & font, bool set_inactive)
365 if (!inset_ert_contents.empty()) {
366 lyxerr[Debug::INSETS] << "ERT contents:\n"
367 << inset_ert_contents << endl;
368 Inset * inset = new InsetERT(inset_ert_contents);
369 par->insertInset(pos++, inset, font);
370 inset_ert_contents.erase();
379 Buffer::parseSingleLyXformat2Token(LyXLex & lex, Paragraph *& par,
380 Paragraph *& first_par,
381 string const & token, int & pos,
382 Paragraph::depth_type & depth,
386 bool the_end_read = false;
387 #ifndef NO_PEXTRA_REALLY
388 // This is super temporary but is needed to get the compability
389 // mode for minipages work correctly together with new tabulars.
390 static int call_depth;
392 bool checkminipage = false;
393 static Paragraph * minipar;
394 static Paragraph * parBeforeMinipage;
397 if (token[0] != '\\') {
400 inset_ert_contents += token;
403 for (string::const_iterator cit = token.begin();
404 cit != token.end(); ++cit) {
405 par->insertChar(pos, (*cit), font);
408 checkminipage = true;
412 } else if (token == "\\i") {
413 Inset * inset = new InsetLatexAccent;
414 inset->read(this, lex);
415 par->insertInset(pos, inset, font);
417 } else if (token == "\\layout") {
421 insertErtContents(par, pos, font);
424 string const layoutname = lex.GetString();
425 pair<bool, LyXTextClass::LayoutList::size_type> pp
426 = textclasslist.NumberOfLayout(params.textclass,
430 if (compare_no_case(layoutname, "latex") == 0) {
435 // The is the compability reading of layout caption.
436 // It can be removed in LyX version 1.3.0. (Lgb)
437 if (compare_no_case(layoutname, "caption") == 0) {
438 // We expect that the par we are now working on is
439 // really inside a InsetText inside a InsetFloat.
440 // We also know that captions can only be
441 // one paragraph. (Lgb)
443 // We should now read until the next "\layout"
445 // This is probably not good enough, what if the
446 // caption is the last par in the document (Lgb)
447 istream & ist = lex.getStream();
453 if (prefixIs(line, "\\layout")) {
457 if (prefixIs(line, "\\begin_inset"))
459 if (prefixIs(line, "\\end_inset")) {
470 // Now we should have the whole layout in ss
471 // we should now be able to give this to the
473 ss << "\\end_inset\n";
475 // This seems like a bug in stringstream.
476 // We really should be able to use ss
478 istringstream is(ss.str());
480 tmplex.setStream(is);
481 Inset * inset = new InsetCaption;
482 inset->Read(this, tmplex);
483 par->InsertInset(pos, inset, font);
490 par = new Paragraph(par);
494 par->layout = pp.second;
497 // use default layout "Standard" (0)
500 // Test whether the layout is obsolete.
501 LyXLayout const & layout =
502 textclasslist.Style(params.textclass,
504 if (!layout.obsoleted_by().empty())
505 par->layout = textclasslist
506 .NumberOfLayout(params.textclass,
507 layout.obsoleted_by())
509 par->params().depth(depth);
510 font = LyXFont(LyXFont::ALL_INHERIT, params.language);
511 if (file_format < 216
512 && params.language->lang() == "hebrew")
513 font.setLanguage(default_language);
518 } else if (token == "\\begin_float") {
519 // This is the compability reader. It can be removed in
520 // LyX version 1.3.0. (Lgb)
522 string const tmptok = lex.GetString();
523 //lyxerr << "old float: " << tmptok << endl;
526 stringstream old_float;
528 if (tmptok == "footnote") {
529 inset = new InsetFoot;
530 } else if (tmptok == "margin") {
531 inset = new InsetMarginal;
532 } else if (tmptok == "fig") {
533 inset = new InsetFloat("figure");
534 old_float << "placement htbp\n"
536 } else if (tmptok == "tab") {
537 inset = new InsetFloat("table");
538 old_float << "placement htbp\n"
540 } else if (tmptok == "alg") {
541 inset = new InsetFloat("algorithm");
542 old_float << "placement htbp\n"
544 } else if (tmptok == "wide-fig") {
545 inset = new InsetFloat("figure");
546 //InsetFloat * tmp = new InsetFloat("figure");
549 old_float << "placement htbp\n"
551 } else if (tmptok == "wide-tab") {
552 inset = new InsetFloat("table");
553 //InsetFloat * tmp = new InsetFloat("table");
556 old_float << "placement htbp\n"
562 return false; // no end read yet
565 old_float << "collapsed true\n";
567 // Here we need to check for \end_deeper and handle that
568 // before we do the footnote parsing.
569 // This _is_ a hack! (Lgb)
572 string const tmp = lex.GetString();
573 if (tmp == "\\end_deeper") {
574 //lyxerr << "\\end_deeper caught!" << endl;
576 lex.printError("\\end_deeper: "
577 "depth is already null");
582 old_float << tmp << ' ';
587 old_float << lex.getLongString("\\end_float")
588 << "\n\\end_inset\n";
589 //lyxerr << "Float Body:\n" << old_float.str() << endl;
590 // That this does not work seems like a bug
591 // in stringstream. (Lgb)
592 istringstream istr(old_float.str());
594 nylex.setStream(istr);
595 inset->read(this, nylex);
596 par->insertInset(pos, inset, font);
598 } else if (token == "\\begin_deeper") {
600 } else if (token == "\\end_deeper") {
602 lex.printError("\\end_deeper: "
603 "depth is already null");
607 } else if (token == "\\begin_preamble") {
608 params.readPreamble(lex);
609 } else if (token == "\\textclass") {
611 pair<bool, LyXTextClassList::size_type> pp =
612 textclasslist.NumberOfClass(lex.GetString());
614 params.textclass = pp.second;
616 WriteAlert(string(_("Textclass error")),
617 string(_("The document uses an unknown textclass \"")) +
618 lex.GetString() + string("\"."),
619 string(_("LyX will not be able to produce output correctly.")));
620 params.textclass = 0;
622 if (!textclasslist.Load(params.textclass)) {
623 // if the textclass wasn't loaded properly
624 // we need to either substitute another
625 // or stop loading the file.
626 // I can substitute but I don't see how I can
627 // stop loading... ideas?? ARRae980418
628 WriteAlert(_("Textclass Loading Error!"),
629 string(_("Can't load textclass ")) +
630 textclasslist.NameOfClass(params.textclass),
631 _("-- substituting default"));
632 params.textclass = 0;
634 } else if (token == "\\options") {
636 params.options = lex.GetString();
637 } else if (token == "\\language") {
638 params.readLanguage(lex);
639 } else if (token == "\\fontencoding") {
641 } else if (token == "\\inputencoding") {
643 params.inputenc = lex.GetString();
644 } else if (token == "\\graphics") {
645 params.readGraphicsDriver(lex);
646 } else if (token == "\\fontscheme") {
648 params.fonts = lex.GetString();
649 } else if (token == "\\noindent") {
650 par->params().noindent(true);
651 } else if (token == "\\fill_top") {
652 par->params().spaceTop(VSpace(VSpace::VFILL));
653 } else if (token == "\\fill_bottom") {
654 par->params().spaceBottom(VSpace(VSpace::VFILL));
655 } else if (token == "\\line_top") {
656 par->params().lineTop(true);
657 } else if (token == "\\line_bottom") {
658 par->params().lineBottom(true);
659 } else if (token == "\\pagebreak_top") {
660 par->params().pagebreakTop(true);
661 } else if (token == "\\pagebreak_bottom") {
662 par->params().pagebreakBottom(true);
663 } else if (token == "\\start_of_appendix") {
664 par->params().startOfAppendix(true);
665 } else if (token == "\\paragraph_separation") {
666 int tmpret = lex.FindToken(string_paragraph_separation);
667 if (tmpret == -1) ++tmpret;
668 if (tmpret != LYX_LAYOUT_DEFAULT)
669 params.paragraph_separation =
670 static_cast<BufferParams::PARSEP>(tmpret);
671 } else if (token == "\\defskip") {
673 params.defskip = VSpace(lex.GetString());
674 } else if (token == "\\epsfig") { // obsolete
675 // Indeed it is obsolete, but we HAVE to be backwards
676 // compatible until 0.14, because otherwise all figures
677 // in existing documents are irretrivably lost. (Asger)
678 params.readGraphicsDriver(lex);
679 } else if (token == "\\quotes_language") {
680 int tmpret = lex.FindToken(string_quotes_language);
681 if (tmpret == -1) ++tmpret;
682 if (tmpret != LYX_LAYOUT_DEFAULT) {
683 InsetQuotes::quote_language tmpl =
684 InsetQuotes::EnglishQ;
687 tmpl = InsetQuotes::EnglishQ;
690 tmpl = InsetQuotes::SwedishQ;
693 tmpl = InsetQuotes::GermanQ;
696 tmpl = InsetQuotes::PolishQ;
699 tmpl = InsetQuotes::FrenchQ;
702 tmpl = InsetQuotes::DanishQ;
705 params.quotes_language = tmpl;
707 } else if (token == "\\quotes_times") {
709 switch (lex.GetInteger()) {
711 params.quotes_times = InsetQuotes::SingleQ;
714 params.quotes_times = InsetQuotes::DoubleQ;
717 } else if (token == "\\papersize") {
718 int tmpret = lex.FindToken(string_papersize);
722 params.papersize2 = tmpret;
723 } else if (token == "\\paperpackage") {
724 int tmpret = lex.FindToken(string_paperpackages);
727 params.paperpackage = BufferParams::PACKAGE_NONE;
729 params.paperpackage = tmpret;
730 } else if (token == "\\use_geometry") {
732 params.use_geometry = lex.GetInteger();
733 } else if (token == "\\use_amsmath") {
735 params.use_amsmath = lex.GetInteger();
736 } else if (token == "\\paperorientation") {
737 int tmpret = lex.FindToken(string_orientation);
738 if (tmpret == -1) ++tmpret;
739 if (tmpret != LYX_LAYOUT_DEFAULT)
740 params.orientation = static_cast<BufferParams::PAPER_ORIENTATION>(tmpret);
741 } else if (token == "\\paperwidth") {
743 params.paperwidth = lex.GetString();
744 } else if (token == "\\paperheight") {
746 params.paperheight = lex.GetString();
747 } else if (token == "\\leftmargin") {
749 params.leftmargin = lex.GetString();
750 } else if (token == "\\topmargin") {
752 params.topmargin = lex.GetString();
753 } else if (token == "\\rightmargin") {
755 params.rightmargin = lex.GetString();
756 } else if (token == "\\bottommargin") {
758 params.bottommargin = lex.GetString();
759 } else if (token == "\\headheight") {
761 params.headheight = lex.GetString();
762 } else if (token == "\\headsep") {
764 params.headsep = lex.GetString();
765 } else if (token == "\\footskip") {
767 params.footskip = lex.GetString();
768 } else if (token == "\\paperfontsize") {
770 params.fontsize = strip(lex.GetString());
771 } else if (token == "\\papercolumns") {
773 params.columns = lex.GetInteger();
774 } else if (token == "\\papersides") {
776 switch (lex.GetInteger()) {
778 case 1: params.sides = LyXTextClass::OneSide; break;
779 case 2: params.sides = LyXTextClass::TwoSides; break;
781 } else if (token == "\\paperpagestyle") {
783 params.pagestyle = strip(lex.GetString());
784 } else if (token == "\\bullet") {
786 int const index = lex.GetInteger();
788 int temp_int = lex.GetInteger();
789 params.user_defined_bullets[index].setFont(temp_int);
790 params.temp_bullets[index].setFont(temp_int);
792 temp_int = lex.GetInteger();
793 params.user_defined_bullets[index].setCharacter(temp_int);
794 params.temp_bullets[index].setCharacter(temp_int);
796 temp_int = lex.GetInteger();
797 params.user_defined_bullets[index].setSize(temp_int);
798 params.temp_bullets[index].setSize(temp_int);
800 string const temp_str = lex.GetString();
801 if (temp_str != "\\end_bullet") {
802 // this element isn't really necessary for
803 // parsing but is easier for humans
804 // to understand bullets. Put it back and
805 // set a debug message?
806 lex.printError("\\end_bullet expected, got" + temp_str);
807 //how can I put it back?
809 } else if (token == "\\bulletLaTeX") {
811 int const index = lex.GetInteger();
813 string temp_str = lex.GetString();
815 while (temp_str != "\\end_bullet") {
816 // this loop structure is needed when user
817 // enters an empty string since the first
818 // thing returned will be the \\end_bullet
820 // if the LaTeX entry has spaces. Each element
821 // therefore needs to be read in turn
824 temp_str = lex.GetString();
826 params.user_defined_bullets[index].setText(sum_str);
827 params.temp_bullets[index].setText(sum_str);
828 } else if (token == "\\secnumdepth") {
830 params.secnumdepth = lex.GetInteger();
831 } else if (token == "\\tocdepth") {
833 params.tocdepth = lex.GetInteger();
834 } else if (token == "\\spacing") {
836 string const tmp = strip(lex.GetString());
837 Spacing::Space tmp_space = Spacing::Default;
839 if (tmp == "single") {
840 tmp_space = Spacing::Single;
841 } else if (tmp == "onehalf") {
842 tmp_space = Spacing::Onehalf;
843 } else if (tmp == "double") {
844 tmp_space = Spacing::Double;
845 } else if (tmp == "other") {
847 tmp_space = Spacing::Other;
848 tmp_val = lex.GetFloat();
850 lex.printError("Unknown spacing token: '$$Token'");
852 // Small hack so that files written with klyx will be
855 par->params().spacing(Spacing(tmp_space, tmp_val));
857 params.spacing.set(tmp_space, tmp_val);
859 } else if (token == "\\paragraph_spacing") {
861 string const tmp = strip(lex.GetString());
862 if (tmp == "single") {
863 par->params().spacing(Spacing(Spacing::Single));
864 } else if (tmp == "onehalf") {
865 par->params().spacing(Spacing(Spacing::Onehalf));
866 } else if (tmp == "double") {
867 par->params().spacing(Spacing(Spacing::Double));
868 } else if (tmp == "other") {
870 par->params().spacing(Spacing(Spacing::Other,
873 lex.printError("Unknown spacing token: '$$Token'");
875 } else if (token == "\\float_placement") {
877 params.float_placement = lex.GetString();
878 } else if (token == "\\family") {
880 font.setLyXFamily(lex.GetString());
881 } else if (token == "\\series") {
883 font.setLyXSeries(lex.GetString());
884 } else if (token == "\\shape") {
886 font.setLyXShape(lex.GetString());
887 } else if (token == "\\size") {
889 font.setLyXSize(lex.GetString());
892 #warning compatability hack needed
894 } else if (token == "\\latex") {
896 string const tok = lex.GetString();
897 // This is dirty, but gone with LyX3. (Asger)
898 if (tok == "no_latex")
899 font.setLatex(LyXFont::OFF);
900 else if (tok == "latex")
901 font.setLatex(LyXFont::ON);
902 else if (tok == "default")
903 font.setLatex(LyXFont::INHERIT);
905 lex.printError("Unknown LaTeX font flag "
908 } else if (token == "\\latex") {
910 string const tok = lex.GetString();
911 if (tok == "no_latex") {
913 insertErtContents(par, pos, font);
914 } else if (tok == "latex") {
916 } else if (tok == "default") {
918 insertErtContents(par, pos, font);
920 lex.printError("Unknown LaTeX font flag "
924 } else if (token == "\\lang") {
926 string const tok = lex.GetString();
927 Language const * lang = languages.getLanguage(tok);
929 font.setLanguage(lang);
931 font.setLanguage(params.language);
932 lex.printError("Unknown language `$$Token'");
934 } else if (token == "\\numeric") {
936 font.setNumber(font.setLyXMisc(lex.GetString()));
937 } else if (token == "\\emph") {
939 font.setEmph(font.setLyXMisc(lex.GetString()));
940 } else if (token == "\\bar") {
942 string const tok = lex.GetString();
943 // This is dirty, but gone with LyX3. (Asger)
945 font.setUnderbar(LyXFont::ON);
946 else if (tok == "no")
947 font.setUnderbar(LyXFont::OFF);
948 else if (tok == "default")
949 font.setUnderbar(LyXFont::INHERIT);
951 lex.printError("Unknown bar font flag "
953 } else if (token == "\\noun") {
955 font.setNoun(font.setLyXMisc(lex.GetString()));
956 } else if (token == "\\color") {
958 font.setLyXColor(lex.GetString());
959 } else if (token == "\\align") {
960 int tmpret = lex.FindToken(string_align);
961 if (tmpret == -1) ++tmpret;
962 if (tmpret != LYX_LAYOUT_DEFAULT) { // tmpret != 99 ???
963 int const tmpret2 = int(pow(2.0, tmpret));
964 //lyxerr << "Tmpret2 = " << tmpret2 << endl;
965 par->params().align(LyXAlignment(tmpret2));
967 } else if (token == "\\added_space_top") {
969 par->params().spaceTop(VSpace(lex.GetString()));
970 } else if (token == "\\added_space_bottom") {
972 par->params().spaceBottom(VSpace(lex.GetString()));
973 #ifndef NO_PEXTRA_REALLY
974 } else if (token == "\\pextra_type") {
976 par->params().pextraType(lex.GetInteger());
977 } else if (token == "\\pextra_width") {
979 par->params().pextraWidth(lex.GetString());
980 } else if (token == "\\pextra_widthp") {
982 par->params().pextraWidthp(lex.GetString());
983 } else if (token == "\\pextra_alignment") {
985 par->params().pextraAlignment(lex.GetInteger());
986 } else if (token == "\\pextra_hfill") {
988 par->params().pextraHfill(lex.GetInteger());
989 } else if (token == "\\pextra_start_minipage") {
991 par->params().pextraStartMinipage(lex.GetInteger());
993 } else if (token == "\\labelwidthstring") {
995 par->params().labelWidthString(lex.GetString());
996 // do not delete this token, it is still needed!
997 } else if (token == "\\end_inset") {
998 lyxerr << "Solitary \\end_inset. Missing \\begin_inset?.\n"
999 << "Last inset read was: " << last_inset_read
1001 // Simply ignore this. The insets do not have
1003 // But insets should read it, it is a part of
1004 // the inset isn't it? Lgb.
1005 } else if (token == "\\begin_inset") {
1007 insertErtContents(par, pos, font);
1009 readInset(lex, par, pos, font);
1010 } else if (token == "\\SpecialChar") {
1011 LyXLayout const & layout =
1012 textclasslist.Style(params.textclass,
1015 // Insets don't make sense in a free-spacing context! ---Kayvan
1016 if (layout.free_spacing) {
1019 string next_token = lex.GetString();
1020 if (next_token == "\\-") {
1021 par->insertChar(pos, '-', font);
1022 } else if (next_token == "\\protected_separator"
1023 || next_token == "~") {
1024 par->insertChar(pos, ' ', font);
1026 lex.printError("Token `$$Token' "
1028 "paragraph layout!");
1033 Inset * inset = new InsetSpecialChar;
1034 inset->read(this, lex);
1035 par->insertInset(pos, inset, font);
1038 } else if (token == "\\newline") {
1041 if (!in_tabular && ert_active) {
1042 inset_ert_contents += char(Paragraph::META_NEWLINE);
1044 // Since we cannot know it this is only a regular
1045 // newline or a tabular cell delimter we have to
1046 // handle the ERT here.
1047 insertErtContents(par, pos, font, false);
1049 par->insertChar(pos, Paragraph::META_NEWLINE, font);
1053 par->insertChar(pos, Paragraph::META_NEWLINE, font);
1056 } else if (token == "\\LyXTable") {
1060 Inset * inset = new InsetTabular(*this);
1061 inset->read(this, lex);
1062 par->insertInset(pos, inset, font);
1064 // because of OLD_TABULAR_READ where tabulars have been
1066 checkminipage = true;
1067 } else if (token == "\\hfill") {
1068 par->insertChar(pos, Paragraph::META_HFILL, font);
1070 } else if (token == "\\protected_separator") { // obsolete
1071 // This is a backward compability thingie. (Lgb)
1072 // Remove it later some time...introduced with fileformat
1074 LyXLayout const & layout =
1075 textclasslist.Style(params.textclass,
1078 if (layout.free_spacing) {
1079 par->insertChar(pos, ' ', font);
1081 Inset * inset = new InsetSpecialChar(InsetSpecialChar::PROTECTED_SEPARATOR);
1082 par->insertInset(pos, inset, font);
1085 } else if (token == "\\bibitem") { // ale970302
1087 InsetCommandParams p("bibitem", "dummy");
1088 par->bibkey = new InsetBibKey(p);
1090 par->bibkey->read(this, lex);
1091 } else if (token == "\\backslash") {
1094 inset_ert_contents += "\\";
1097 par->insertChar(pos, '\\', font);
1102 } else if (token == "\\the_end") {
1104 // If we still have some ert active here we have to insert
1105 // it so we don't loose it. (Lgb)
1106 insertErtContents(par, pos, font);
1108 the_end_read = true;
1109 minipar = parBeforeMinipage = 0;
1113 inset_ert_contents += token;
1116 // This should be insurance for the future: (Asger)
1117 lex.printError("Unknown token `$$Token'. "
1118 "Inserting as text.");
1119 string::const_iterator cit = token.begin();
1120 string::const_iterator end = token.end();
1121 for (; cit != end; ++cit) {
1122 par->insertChar(pos, (*cit), font);
1129 #ifndef NO_PEXTRA_REALLY
1130 // now check if we have a minipage paragraph as at this
1131 // point we already read all the necessary data!
1132 // this cannot be done in layout because there we did
1133 // not read yet the paragraph PEXTRA-params (Jug)
1135 // BEGIN pextra_minipage compability
1136 // This should be removed in 1.3.x (Lgb)
1138 // This compability code is not perfect. In a couple
1139 // of rand cases it fails. When the minipage par is
1140 // the first par in the document, and when there are
1141 // none or only one regular paragraphs after the
1142 // minipage. Currently I am not investing any effort
1143 // in fixing those cases.
1145 //lyxerr << "Call depth: " << call_depth << endl;
1146 if (checkminipage && (call_depth == 1)) {
1147 checkminipage = false;
1148 if (minipar && (minipar != par) &&
1149 (par->params().pextraType()==Paragraph::PEXTRA_MINIPAGE))
1151 lyxerr << "minipages in a row" << endl;
1152 if (par->params().pextraStartMinipage()) {
1153 lyxerr << "start new minipage" << endl;
1154 // minipages in a row
1155 par->previous()->next(0);
1158 Paragraph * tmp = minipar;
1160 tmp->params().pextraType(0);
1161 tmp->params().pextraWidth(string());
1162 tmp->params().pextraWidthp(string());
1163 tmp->params().pextraAlignment(0);
1164 tmp->params().pextraHfill(false);
1165 tmp->params().pextraStartMinipage(false);
1168 // create a new paragraph to insert the
1169 // minipages in the following case
1170 if (par->params().pextraStartMinipage() &&
1171 !par->params().pextraHfill())
1173 Paragraph * p = new Paragraph;
1175 p->previous(parBeforeMinipage);
1176 parBeforeMinipage->next(p);
1178 p->params().depth(parBeforeMinipage->params().depth());
1179 parBeforeMinipage = p;
1181 InsetMinipage * mini = new InsetMinipage;
1182 mini->pos(static_cast<InsetMinipage::Position>(par->params().pextraAlignment()));
1183 mini->width(par->params().pextraWidth());
1184 if (!par->params().pextraWidthp().empty()) {
1185 lyxerr << "WP:" << mini->width() << endl;
1186 mini->width(tostr(par->params().pextraWidthp())+"%");
1188 mini->inset.paragraph(par);
1189 // Insert the minipage last in the
1190 // previous paragraph.
1191 if (par->params().pextraHfill()) {
1192 parBeforeMinipage->insertChar
1193 (parBeforeMinipage->size(), Paragraph::META_HFILL);
1195 parBeforeMinipage->insertInset
1196 (parBeforeMinipage->size(), mini);
1200 lyxerr << "new minipage par" << endl;
1201 //nothing to do just continue reading
1204 } else if (minipar && (minipar != par)) {
1205 lyxerr << "last minipage par read" << endl;
1206 // The last paragraph read was not part of a
1207 // minipage but the par linked list is...
1208 // So we need to remove the last par from the
1210 if (par->previous())
1211 par->previous()->next(0);
1212 par->previous(parBeforeMinipage);
1213 parBeforeMinipage->next(par);
1214 Paragraph * tmp = minipar;
1216 tmp->params().pextraType(0);
1217 tmp->params().pextraWidth(string());
1218 tmp->params().pextraWidthp(string());
1219 tmp->params().pextraAlignment(0);
1220 tmp->params().pextraHfill(false);
1221 tmp->params().pextraStartMinipage(false);
1224 depth = parBeforeMinipage->params().depth();
1225 minipar = parBeforeMinipage = 0;
1226 } else if (!minipar &&
1227 (par->params().pextraType() == Paragraph::PEXTRA_MINIPAGE))
1229 // par is the first paragraph in a minipage
1230 lyxerr << "begin minipage" << endl;
1231 // To minimize problems for
1232 // the users we will insert
1233 // the first minipage in
1234 // a sequence of minipages
1235 // in its own paragraph.
1236 Paragraph * p = new Paragraph;
1238 p->previous(par->previous());
1240 p->params().depth(depth);
1241 par->params().depth(0);
1243 if (par->previous())
1244 par->previous()->next(p);
1246 parBeforeMinipage = p;
1248 if (!first_par || (first_par == par))
1251 InsetMinipage * mini = new InsetMinipage;
1252 mini->pos(static_cast<InsetMinipage::Position>(minipar->params().pextraAlignment()));
1253 mini->width(minipar->params().pextraWidth());
1254 if (!par->params().pextraWidthp().empty()) {
1255 lyxerr << "WP:" << mini->width() << endl;
1256 mini->width(tostr(par->params().pextraWidthp())+"%");
1258 mini->inset.paragraph(minipar);
1260 // Insert the minipage last in the
1261 // previous paragraph.
1262 if (minipar->params().pextraHfill()) {
1263 parBeforeMinipage->insertChar
1264 (parBeforeMinipage->size(),Paragraph::META_HFILL);
1266 parBeforeMinipage->insertInset
1267 (parBeforeMinipage->size(), mini);
1270 // End of pextra_minipage compability
1273 return the_end_read;
1277 void Buffer::readInset(LyXLex & lex, Paragraph *& par,
1278 int & pos, LyXFont & font)
1280 // consistency check
1281 if (lex.GetString() != "\\begin_inset") {
1282 lyxerr << "Buffer::readInset: Consistency check failed."
1289 string const tmptok = lex.GetString();
1290 last_inset_read = tmptok;
1292 // test the different insets
1293 if (tmptok == "LatexCommand") {
1294 InsetCommandParams inscmd;
1297 string const cmdName = inscmd.getCmdName();
1299 if (cmdName == "cite") {
1300 inset = new InsetCitation(inscmd);
1301 } else if (cmdName == "bibitem") {
1302 lex.printError("Wrong place for bibitem");
1303 inset = new InsetBibKey(inscmd);
1304 } else if (cmdName == "BibTeX") {
1305 inset = new InsetBibtex(inscmd);
1306 } else if (cmdName == "index") {
1307 inset = new InsetIndex(inscmd);
1308 } else if (cmdName == "include") {
1309 inset = new InsetInclude(inscmd, *this);
1310 } else if (cmdName == "label") {
1311 inset = new InsetLabel(inscmd);
1312 } else if (cmdName == "url"
1313 || cmdName == "htmlurl") {
1314 inset = new InsetUrl(inscmd);
1315 } else if (cmdName == "ref"
1316 || cmdName == "pageref"
1317 || cmdName == "vref"
1318 || cmdName == "vpageref"
1319 || cmdName == "prettyref") {
1320 if (!inscmd.getOptions().empty()
1321 || !inscmd.getContents().empty()) {
1322 inset = new InsetRef(inscmd, *this);
1324 } else if (cmdName == "tableofcontents") {
1325 inset = new InsetTOC(inscmd);
1326 } else if (cmdName == "listofalgorithms") {
1327 inset = new InsetFloatList("algorithm");
1328 } else if (cmdName == "listoffigures") {
1329 inset = new InsetFloatList("figure");
1330 } else if (cmdName == "listoftables") {
1331 inset = new InsetFloatList("table");
1332 } else if (cmdName == "printindex") {
1333 inset = new InsetPrintIndex(inscmd);
1334 } else if (cmdName == "lyxparent") {
1335 inset = new InsetParent(inscmd, *this);
1338 if (tmptok == "Quotes") {
1339 inset = new InsetQuotes;
1340 } else if (tmptok == "External") {
1341 inset = new InsetExternal;
1342 } else if (tmptok == "FormulaMacro") {
1343 inset = new InsetFormulaMacro;
1344 } else if (tmptok == "Formula") {
1345 inset = new InsetFormula;
1346 } else if (tmptok == "Figure") {
1347 inset = new InsetFig(100, 100, *this);
1348 } else if (tmptok == "Info") {
1349 inset = new InsetInfo;
1350 } else if (tmptok == "Include") {
1351 InsetCommandParams p( "Include" );
1352 inset = new InsetInclude(p, *this);
1353 } else if (tmptok == "ERT") {
1354 inset = new InsetERT;
1355 } else if (tmptok == "Tabular") {
1356 inset = new InsetTabular(*this);
1357 } else if (tmptok == "Text") {
1358 inset = new InsetText;
1359 } else if (tmptok == "Foot") {
1360 inset = new InsetFoot;
1361 } else if (tmptok == "Marginal") {
1362 inset = new InsetMarginal;
1363 } else if (tmptok == "Minipage") {
1364 inset = new InsetMinipage;
1365 } else if (tmptok == "Float") {
1367 string tmptok = lex.GetString();
1368 inset = new InsetFloat(tmptok);
1369 } else if (tmptok == "List") {
1370 inset = new InsetList;
1371 } else if (tmptok == "Theorem") {
1372 inset = new InsetList;
1373 } else if (tmptok == "Caption") {
1374 inset = new InsetCaption;
1375 } else if (tmptok == "GRAPHICS") {
1376 inset = new InsetGraphics;
1377 } else if (tmptok == "FloatList") {
1378 inset = new InsetFloatList;
1381 if (inset) inset->read(this, lex);
1385 par->insertInset(pos, inset, font);
1391 bool Buffer::readFile(LyXLex & lex, Paragraph * par)
1395 string const token(lex.GetString());
1396 if (token == "\\lyxformat") { // the first token _must_ be...
1398 string tmp_format = lex.GetString();
1399 //lyxerr << "LyX Format: `" << tmp_format << "'" << endl;
1400 // if present remove ".," from string.
1401 string::size_type dot = tmp_format.find_first_of(".,");
1402 //lyxerr << " dot found at " << dot << endl;
1403 if (dot != string::npos)
1404 tmp_format.erase(dot, 1);
1405 file_format = strToInt(tmp_format);
1406 if (file_format == LYX_FORMAT) {
1408 } else if (file_format > LYX_FORMAT) {
1410 WriteAlert(_("Warning!"),
1411 _("LyX file format is newer that what"),
1412 _("is supported in this LyX version. Expect some problems."));
1414 } else if (file_format < LYX_FORMAT) {
1416 if (file_format < 200) {
1417 WriteAlert(_("ERROR!"),
1418 _("Old LyX file format found. "
1419 "Use LyX 0.10.x to read this!"));
1423 bool the_end = readLyXformat2(lex, par);
1425 // the_end was added in 213
1426 if (file_format < 213)
1430 WriteAlert(_("Warning!"),
1431 _("Reading of document is not complete"),
1432 _("Maybe the document is truncated"));
1434 } else { // "\\lyxformat" not found
1435 WriteAlert(_("ERROR!"), _("Not a LyX file!"));
1438 WriteAlert(_("ERROR!"), _("Unable to read file!"));
1443 // Should probably be moved to somewhere else: BufferView? LyXView?
1444 bool Buffer::save() const
1446 // We don't need autosaves in the immediate future. (Asger)
1447 resetAutosaveTimers();
1451 if (lyxrc.make_backup) {
1452 s = fileName() + '~';
1453 if (!lyxrc.backupdir_path.empty())
1454 s = AddName(lyxrc.backupdir_path,
1455 subst(os::slashify_path(s),'/','!'));
1457 // Rename is the wrong way of making a backup,
1458 // this is the correct way.
1459 /* truss cp fil fil2:
1460 lstat("LyXVC3.lyx", 0xEFFFF898) Err#2 ENOENT
1461 stat("LyXVC.lyx", 0xEFFFF688) = 0
1462 open("LyXVC.lyx", O_RDONLY) = 3
1463 open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
1464 fstat(4, 0xEFFFF508) = 0
1465 fstat(3, 0xEFFFF508) = 0
1466 read(3, " # T h i s f i l e w".., 8192) = 5579
1467 write(4, " # T h i s f i l e w".., 5579) = 5579
1468 read(3, 0xEFFFD4A0, 8192) = 0
1471 chmod("LyXVC3.lyx", 0100644) = 0
1472 lseek(0, 0, SEEK_CUR) = 46440
1476 // Should probably have some more error checking here.
1477 // Should be cleaned up in 0.13, at least a bit.
1478 // Doing it this way, also makes the inodes stay the same.
1479 // This is still not a very good solution, in particular we
1480 // might loose the owner of the backup.
1481 FileInfo finfo(fileName());
1482 if (finfo.exist()) {
1483 mode_t fmode = finfo.getMode();
1484 struct utimbuf times = {
1485 finfo.getAccessTime(),
1486 finfo.getModificationTime() };
1488 ifstream ifs(fileName().c_str());
1489 ofstream ofs(s.c_str(), ios::out|ios::trunc);
1494 ::chmod(s.c_str(), fmode);
1496 if (::utime(s.c_str(), ×)) {
1497 lyxerr << "utime error." << endl;
1500 lyxerr << "LyX was not able to make "
1501 "backup copy. Beware." << endl;
1506 if (writeFile(fileName(), false)) {
1508 removeAutosaveFile(fileName());
1510 // Saving failed, so backup is not backup
1511 if (lyxrc.make_backup) {
1512 lyx::rename(s, fileName());
1520 // Returns false if unsuccesful
1521 bool Buffer::writeFile(string const & fname, bool flag) const
1523 // if flag is false writeFile will not create any GUI
1524 // warnings, only cerr.
1525 // Needed for autosave in background or panic save (Matthias 120496)
1527 if (read_only && (fname == filename)) {
1528 // Here we should come with a question if we should
1529 // perform the write anyway.
1531 lyxerr << _("Error! Document is read-only: ")
1534 WriteAlert(_("Error! Document is read-only: "),
1539 FileInfo finfo(fname);
1540 if (finfo.exist() && !finfo.writable()) {
1541 // Here we should come with a question if we should
1542 // try to do the save anyway. (i.e. do a chmod first)
1544 lyxerr << _("Error! Cannot write file: ")
1547 WriteFSAlert(_("Error! Cannot write file: "),
1552 ofstream ofs(fname.c_str());
1555 lyxerr << _("Error! Cannot open file: ")
1558 WriteFSAlert(_("Error! Cannot open file: "),
1564 // Use the standard "C" locale for file output.
1565 ofs.imbue(std::locale::classic());
1568 // The top of the file should not be written by params.
1570 // write out a comment in the top of the file
1571 ofs << '#' << LYX_DOCVERSION
1572 << " created this file. For more info see http://www.lyx.org/\n"
1573 << "\\lyxformat " << LYX_FORMAT << "\n";
1575 // now write out the buffer paramters.
1576 params.writeFile(ofs);
1578 Paragraph::depth_type depth = 0;
1580 // this will write out all the paragraphs
1581 // using recursive descent.
1582 paragraph->writeFile(this, ofs, params, depth);
1584 // Write marker that shows file is complete
1585 ofs << "\n\\the_end" << endl;
1589 // how to check if close went ok?
1590 // Following is an attempt... (BE 20001011)
1592 // good() returns false if any error occured, including some
1593 // formatting error.
1594 // bad() returns true if something bad happened in the buffer,
1595 // which should include file system full errors.
1602 lyxerr << "Buffer::writeFile: BAD ERROR!" << endl;
1604 lyxerr << "Buffer::writeFile: NOT SO BAD ERROR!"
1614 string const Buffer::asciiParagraph(Paragraph const * par,
1615 unsigned int linelen) const
1617 ostringstream buffer;
1618 Paragraph::depth_type depth = 0;
1620 Paragraph::depth_type ltype_depth = 0;
1621 unsigned int currlinelen = 0;
1622 bool ref_printed = false;
1626 if (!par->previous()) {
1627 // begins or ends a deeper area ?
1628 if (depth != par->params().depth()) {
1629 if (par->params().depth() > depth) {
1630 while (par->params().depth() > depth) {
1634 while (par->params().depth() < depth) {
1640 // First write the layout
1641 string const tmp = textclasslist.NameOfLayout(params.textclass, par->layout);
1642 if (tmp == "Itemize") {
1644 ltype_depth = depth + 1;
1645 } else if (tmp == "Enumerate") {
1647 ltype_depth = depth + 1;
1648 } else if (contains(tmp, "ection")) {
1650 ltype_depth = depth + 1;
1651 } else if (contains(tmp, "aragraph")) {
1653 ltype_depth = depth + 1;
1654 } else if (tmp == "Description") {
1656 ltype_depth = depth + 1;
1657 } else if (tmp == "Abstract") {
1660 } else if (tmp == "Bibliography") {
1668 /* maybe some vertical spaces */
1670 /* the labelwidthstring used in lists */
1674 /* some pagebreaks? */
1678 /* what about the alignment */
1680 lyxerr << "Should this ever happen?" << endl;
1684 LyXFont const font1 = LyXFont(LyXFont::ALL_INHERIT, params.language);
1686 for (Paragraph::size_type i = 0; i < par->size(); ++i) {
1687 if (!i && !noparbreak) {
1690 for (Paragraph::depth_type j = 0; j < depth; ++j)
1692 currlinelen = depth * 2;
1695 case 4: // (Sub)Paragraph
1696 case 5: // Description
1700 buffer << "Abstract\n\n";
1702 buffer << "Abstract: ";
1704 case 7: // Bibliography
1707 buffer << "References\n\n";
1709 buffer << "References: ";
1714 buffer << par->params().labelString() << " ";
1717 if (ltype_depth > depth) {
1718 for (Paragraph::depth_type j = ltype_depth - 1;
1721 currlinelen += (ltype_depth-depth)*2;
1725 LyXFont const font2 = par->getFontSettings(params, i);
1726 if (font1.latex() != font2.latex()) {
1727 if (font2.latex() == LyXFont::OFF)
1736 char c = par->getUChar(params, i);
1740 case Paragraph::META_INSET:
1742 Inset const * inset = par->getInset(i);
1744 if (!inset->ascii(this, buffer)) {
1747 rsplit(buffer.str().c_str(),
1749 currlinelen += s.length();
1751 // to be sure it breaks paragraph
1752 currlinelen += linelen;
1758 case Paragraph::META_NEWLINE:
1761 for (Paragraph::depth_type j = 0;
1765 currlinelen = depth * 2;
1766 if (ltype_depth > depth) {
1767 for (Paragraph::depth_type j = ltype_depth;
1770 currlinelen += (ltype_depth - depth) * 2;
1774 case Paragraph::META_HFILL:
1783 if ((linelen > 0) && (currlinelen > (linelen - 10)) &&
1784 (c == ' ') && ((i + 2) < par->size()))
1787 for (Paragraph::depth_type j = 0;
1790 currlinelen = depth * 2;
1791 if (ltype_depth > depth) {
1792 for (Paragraph::depth_type j = ltype_depth;
1795 currlinelen += (ltype_depth-depth)*2;
1797 } else if (c != '\0')
1800 lyxerr[Debug::INFO] << "writeAsciiFile: NULL char in structure." << endl;
1805 return buffer.str().c_str();
1809 void Buffer::writeFileAscii(string const & fname, int linelen)
1811 ofstream ofs(fname.c_str());
1813 WriteFSAlert(_("Error: Cannot write file:"), fname);
1816 writeFileAscii(ofs, linelen);
1820 void Buffer::writeFileAscii(ostream & ofs, int linelen)
1822 Paragraph * par = paragraph;
1824 ofs << asciiParagraph(par, linelen);
1832 void Buffer::makeLaTeXFile(string const & fname,
1833 string const & original_path,
1834 bool nice, bool only_body)
1836 lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
1838 niceFile = nice; // this will be used by Insetincludes.
1840 tex_code_break_column = lyxrc.ascii_linelen;
1842 LyXTextClass const & tclass =
1843 textclasslist.TextClass(params.textclass);
1845 ofstream ofs(fname.c_str());
1847 WriteFSAlert(_("Error: Cannot open file: "), fname);
1851 // validate the buffer.
1852 lyxerr[Debug::LATEX] << " Validating buffer..." << endl;
1853 LaTeXFeatures features(params, tclass.numLayouts());
1855 lyxerr[Debug::LATEX] << " Buffer validation done." << endl;
1858 // The starting paragraph of the coming rows is the
1859 // first paragraph of the document. (Asger)
1860 texrow.start(paragraph, 0);
1862 if (!only_body && nice) {
1863 ofs << "%% " LYX_DOCVERSION " created this file. "
1864 "For more info, see http://www.lyx.org/.\n"
1865 "%% Do not edit unless you really know what "
1870 lyxerr[Debug::INFO] << "lyx header finished" << endl;
1871 // There are a few differences between nice LaTeX and usual files:
1872 // usual is \batchmode and has a
1873 // special input@path to allow the including of figures
1874 // with either \input or \includegraphics (what figinsets do).
1875 // batchmode is not set if there is a tex_code_break_column.
1876 // In this case somebody is interested in the generated LaTeX,
1877 // so this is OK. input@path is set when the actual parameter
1878 // original_path is set. This is done for usual tex-file, but not
1879 // for nice-latex-file. (Matthias 250696)
1882 // code for usual, NOT nice-latex-file
1883 ofs << "\\batchmode\n"; // changed
1884 // from \nonstopmode
1887 if (!original_path.empty()) {
1888 ofs << "\\makeatletter\n"
1889 << "\\def\\input@path{{"
1890 << os::external_path(original_path) << "/}}\n"
1891 << "\\makeatother\n";
1897 ofs << "\\documentclass";
1899 ostringstream options; // the document class options.
1901 if (tokenPos(tclass.opt_fontsize(),
1902 '|', params.fontsize) >= 0) {
1903 // only write if existing in list (and not default)
1904 options << params.fontsize << "pt,";
1908 if (!params.use_geometry &&
1909 (params.paperpackage == BufferParams::PACKAGE_NONE)) {
1910 switch (params.papersize) {
1911 case BufferParams::PAPER_A4PAPER:
1912 options << "a4paper,";
1914 case BufferParams::PAPER_USLETTER:
1915 options << "letterpaper,";
1917 case BufferParams::PAPER_A5PAPER:
1918 options << "a5paper,";
1920 case BufferParams::PAPER_B5PAPER:
1921 options << "b5paper,";
1923 case BufferParams::PAPER_EXECUTIVEPAPER:
1924 options << "executivepaper,";
1926 case BufferParams::PAPER_LEGALPAPER:
1927 options << "legalpaper,";
1933 if (params.sides != tclass.sides()) {
1934 switch (params.sides) {
1935 case LyXTextClass::OneSide:
1936 options << "oneside,";
1938 case LyXTextClass::TwoSides:
1939 options << "twoside,";
1945 if (params.columns != tclass.columns()) {
1946 if (params.columns == 2)
1947 options << "twocolumn,";
1949 options << "onecolumn,";
1952 if (!params.use_geometry
1953 && params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
1954 options << "landscape,";
1956 // language should be a parameter to \documentclass
1958 ostringstream language_options;
1959 if (params.language->babel() == "hebrew"
1960 && default_language->babel() != "hebrew")
1961 // This seems necessary
1962 features.UsedLanguages.insert(default_language);
1964 if (lyxrc.language_use_babel ||
1965 params.language->lang() != lyxrc.default_language ||
1966 !features.UsedLanguages.empty()) {
1968 for (LaTeXFeatures::LanguageList::const_iterator cit =
1969 features.UsedLanguages.begin();
1970 cit != features.UsedLanguages.end(); ++cit)
1971 language_options << (*cit)->babel() << ',';
1972 language_options << params.language->babel();
1973 if (lyxrc.language_global_options)
1974 options << language_options.str() << ',';
1977 // the user-defined options
1978 if (!params.options.empty()) {
1979 options << params.options << ',';
1982 string strOptions(options.str().c_str());
1983 if (!strOptions.empty()){
1984 strOptions = strip(strOptions, ',');
1985 ofs << '[' << strOptions << ']';
1989 << textclasslist.LatexnameOfClass(params.textclass)
1992 // end of \documentclass defs
1994 // font selection must be done before loading fontenc.sty
1995 // The ae package is not needed when using OT1 font encoding.
1996 if (params.fonts != "default" &&
1997 (params.fonts != "ae" || lyxrc.fontenc != "default")) {
1998 ofs << "\\usepackage{" << params.fonts << "}\n";
2000 if (params.fonts == "ae") {
2001 ofs << "\\usepackage{aecompl}\n";
2005 // this one is not per buffer
2006 if (lyxrc.fontenc != "default") {
2007 ofs << "\\usepackage[" << lyxrc.fontenc
2012 if (params.inputenc == "auto") {
2013 string const doc_encoding =
2014 params.language->encoding()->LatexName();
2016 // Create a list with all the input encodings used
2018 set<string> encodings;
2019 for (LaTeXFeatures::LanguageList::const_iterator it =
2020 features.UsedLanguages.begin();
2021 it != features.UsedLanguages.end(); ++it)
2022 if ((*it)->encoding()->LatexName() != doc_encoding)
2023 encodings.insert((*it)->encoding()->LatexName());
2025 ofs << "\\usepackage[";
2026 std::copy(encodings.begin(), encodings.end(),
2027 std::ostream_iterator<string>(ofs, ","));
2028 ofs << doc_encoding << "]{inputenc}\n";
2030 } else if (params.inputenc != "default") {
2031 ofs << "\\usepackage[" << params.inputenc
2036 // At the very beginning the text parameters.
2037 if (params.paperpackage != BufferParams::PACKAGE_NONE) {
2038 switch (params.paperpackage) {
2039 case BufferParams::PACKAGE_A4:
2040 ofs << "\\usepackage{a4}\n";
2043 case BufferParams::PACKAGE_A4WIDE:
2044 ofs << "\\usepackage{a4wide}\n";
2047 case BufferParams::PACKAGE_WIDEMARGINSA4:
2048 ofs << "\\usepackage[widemargins]{a4}\n";
2053 if (params.use_geometry) {
2054 ofs << "\\usepackage{geometry}\n";
2056 ofs << "\\geometry{verbose";
2057 if (params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
2058 ofs << ",landscape";
2059 switch (params.papersize2) {
2060 case BufferParams::VM_PAPER_CUSTOM:
2061 if (!params.paperwidth.empty())
2062 ofs << ",paperwidth="
2063 << params.paperwidth;
2064 if (!params.paperheight.empty())
2065 ofs << ",paperheight="
2066 << params.paperheight;
2068 case BufferParams::VM_PAPER_USLETTER:
2069 ofs << ",letterpaper";
2071 case BufferParams::VM_PAPER_USLEGAL:
2072 ofs << ",legalpaper";
2074 case BufferParams::VM_PAPER_USEXECUTIVE:
2075 ofs << ",executivepaper";
2077 case BufferParams::VM_PAPER_A3:
2080 case BufferParams::VM_PAPER_A4:
2083 case BufferParams::VM_PAPER_A5:
2086 case BufferParams::VM_PAPER_B3:
2089 case BufferParams::VM_PAPER_B4:
2092 case BufferParams::VM_PAPER_B5:
2096 // default papersize ie BufferParams::VM_PAPER_DEFAULT
2097 switch (lyxrc.default_papersize) {
2098 case BufferParams::PAPER_DEFAULT: // keep compiler happy
2099 case BufferParams::PAPER_USLETTER:
2100 ofs << ",letterpaper";
2102 case BufferParams::PAPER_LEGALPAPER:
2103 ofs << ",legalpaper";
2105 case BufferParams::PAPER_EXECUTIVEPAPER:
2106 ofs << ",executivepaper";
2108 case BufferParams::PAPER_A3PAPER:
2111 case BufferParams::PAPER_A4PAPER:
2114 case BufferParams::PAPER_A5PAPER:
2117 case BufferParams::PAPER_B5PAPER:
2122 if (!params.topmargin.empty())
2123 ofs << ",tmargin=" << params.topmargin;
2124 if (!params.bottommargin.empty())
2125 ofs << ",bmargin=" << params.bottommargin;
2126 if (!params.leftmargin.empty())
2127 ofs << ",lmargin=" << params.leftmargin;
2128 if (!params.rightmargin.empty())
2129 ofs << ",rmargin=" << params.rightmargin;
2130 if (!params.headheight.empty())
2131 ofs << ",headheight=" << params.headheight;
2132 if (!params.headsep.empty())
2133 ofs << ",headsep=" << params.headsep;
2134 if (!params.footskip.empty())
2135 ofs << ",footskip=" << params.footskip;
2139 if (features.amsstyle
2140 && !tclass.provides(LyXTextClass::amsmath)) {
2141 ofs << "\\usepackage{amsmath}\n";
2145 if (tokenPos(tclass.opt_pagestyle(),
2146 '|', params.pagestyle) >= 0) {
2147 if (params.pagestyle == "fancy") {
2148 ofs << "\\usepackage{fancyhdr}\n";
2151 ofs << "\\pagestyle{" << params.pagestyle << "}\n";
2155 // We try to load babel late, in case it interferes
2156 // with other packages.
2158 string tmp = lyxrc.language_package;
2159 if (!lyxrc.language_global_options
2160 && tmp == "\\usepackage{babel}")
2161 tmp = string("\\usepackage[") +
2162 language_options.str().c_str() +
2168 if (params.secnumdepth != tclass.secnumdepth()) {
2169 ofs << "\\setcounter{secnumdepth}{"
2170 << params.secnumdepth
2174 if (params.tocdepth != tclass.tocdepth()) {
2175 ofs << "\\setcounter{tocdepth}{"
2181 if (params.paragraph_separation) {
2182 switch (params.defskip.kind()) {
2183 case VSpace::SMALLSKIP:
2184 ofs << "\\setlength\\parskip{\\smallskipamount}\n";
2186 case VSpace::MEDSKIP:
2187 ofs << "\\setlength\\parskip{\\medskipamount}\n";
2189 case VSpace::BIGSKIP:
2190 ofs << "\\setlength\\parskip{\\bigskipamount}\n";
2192 case VSpace::LENGTH:
2193 ofs << "\\setlength\\parskip{"
2194 << params.defskip.length().asLatexString()
2197 default: // should never happen // Then delete it.
2198 ofs << "\\setlength\\parskip{\\medskipamount}\n";
2203 ofs << "\\setlength\\parindent{0pt}\n";
2207 // Now insert the LyX specific LaTeX commands...
2209 // The optional packages;
2210 string preamble(features.getPackages());
2212 // this might be useful...
2213 preamble += "\n\\makeatletter\n";
2215 // Some macros LyX will need
2216 string tmppreamble(features.getMacros());
2218 if (!tmppreamble.empty()) {
2219 preamble += "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2220 "LyX specific LaTeX commands.\n"
2221 + tmppreamble + '\n';
2224 // the text class specific preamble
2225 tmppreamble = features.getTClassPreamble();
2226 if (!tmppreamble.empty()) {
2227 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2228 "Textclass specific LaTeX commands.\n"
2229 + tmppreamble + '\n';
2232 /* the user-defined preamble */
2233 if (!params.preamble.empty()) {
2234 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2235 "User specified LaTeX commands.\n"
2236 + params.preamble + '\n';
2239 preamble += "\\makeatother\n";
2241 // Itemize bullet settings need to be last in case the user
2242 // defines their own bullets that use a package included
2243 // in the user-defined preamble -- ARRae
2244 // Actually it has to be done much later than that
2245 // since some packages like frenchb make modifications
2246 // at \begin{document} time -- JMarc
2248 for (int i = 0; i < 4; ++i) {
2249 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
2250 if (bullets_def.empty())
2251 bullets_def="\\AtBeginDocument{\n";
2252 bullets_def += " \\renewcommand{\\labelitemi";
2254 // `i' is one less than the item to modify
2261 bullets_def += "ii";
2267 bullets_def += "}{" +
2268 params.user_defined_bullets[i].getText()
2273 if (!bullets_def.empty())
2274 preamble += bullets_def + "}\n\n";
2276 for (int j = countChar(preamble, '\n'); j-- ;) {
2283 ofs << "\\begin{document}\n";
2286 lyxerr[Debug::INFO] << "preamble finished, now the body." << endl;
2288 if (!lyxrc.language_auto_begin) {
2289 ofs << subst(lyxrc.language_command_begin, "$$lang",
2290 params.language->babel())
2295 latexParagraphs(ofs, paragraph, 0, texrow);
2297 // add this just in case after all the paragraphs
2301 if (!lyxrc.language_auto_end) {
2302 ofs << subst(lyxrc.language_command_end, "$$lang",
2303 params.language->babel())
2309 ofs << "\\end{document}\n";
2312 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
2314 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
2318 // Just to be sure. (Asger)
2321 // tex_code_break_column's value is used to decide
2322 // if we are in batchmode or not (within mathed_write()
2323 // in math_write.C) so we must set it to a non-zero
2324 // value when we leave otherwise we save incorrect .lyx files.
2325 tex_code_break_column = lyxrc.ascii_linelen;
2329 lyxerr << "File was not closed properly." << endl;
2332 lyxerr[Debug::INFO] << "Finished making latex file." << endl;
2337 // LaTeX all paragraphs from par to endpar, if endpar == 0 then to the end
2339 void Buffer::latexParagraphs(ostream & ofs, Paragraph * par,
2340 Paragraph * endpar, TexRow & texrow) const
2342 bool was_title = false;
2343 bool already_title = false;
2346 while (par != endpar) {
2347 LyXLayout const & layout =
2348 textclasslist.Style(params.textclass,
2351 if (layout.intitle) {
2352 if (already_title) {
2353 lyxerr <<"Error in latexParagraphs: You"
2354 " should not mix title layouts"
2355 " with normal ones." << endl;
2358 } else if (was_title && !already_title) {
2359 ofs << "\\maketitle\n";
2361 already_title = true;
2365 if (layout.isEnvironment()) {
2366 par = par->TeXEnvironment(this, params, ofs, texrow);
2368 par = par->TeXOnePar(this, params, ofs, texrow, false);
2371 // It might be that we only have a title in this document
2372 if (was_title && !already_title) {
2373 ofs << "\\maketitle\n";
2379 bool Buffer::isLatex() const
2381 return textclasslist.TextClass(params.textclass).outputType() == LATEX;
2385 bool Buffer::isLinuxDoc() const
2387 return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC;
2391 bool Buffer::isLiterate() const
2393 return textclasslist.TextClass(params.textclass).outputType() == LITERATE;
2397 bool Buffer::isDocBook() const
2399 return textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2403 bool Buffer::isSGML() const
2405 return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC ||
2406 textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2410 void Buffer::sgmlOpenTag(ostream & os, Paragraph::depth_type depth,
2411 string const & latexname) const
2413 if (!latexname.empty() && latexname != "!-- --")
2414 os << "<!-- " << depth << " -->" << "<" << latexname << ">";
2415 //os << string(depth, ' ') << "<" << latexname << ">\n";
2419 void Buffer::sgmlCloseTag(ostream & os, Paragraph::depth_type depth,
2420 string const & latexname) const
2422 if (!latexname.empty() && latexname != "!-- --")
2423 os << "<!-- " << depth << " -->" << "</" << latexname << ">\n";
2424 //os << string(depth, ' ') << "</" << latexname << ">\n";
2428 void Buffer::makeLinuxDocFile(string const & fname, bool nice, bool body_only)
2430 ofstream ofs(fname.c_str());
2433 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2437 niceFile = nice; // this will be used by included files.
2439 LyXTextClass const & tclass =
2440 textclasslist.TextClass(params.textclass);
2442 LaTeXFeatures features(params, tclass.numLayouts());
2447 string top_element = textclasslist.LatexnameOfClass(params.textclass);
2450 string sgml_includedfiles=features.getIncludedFiles(fname);
2452 if (params.preamble.empty() && sgml_includedfiles.empty()) {
2453 ofs << "<!doctype linuxdoc system>\n\n";
2455 ofs << "<!doctype linuxdoc system [ "
2456 << params.preamble << sgml_includedfiles << " \n]>\n\n";
2459 if (params.options.empty())
2460 sgmlOpenTag(ofs, 0, top_element);
2462 string top = top_element;
2464 top += params.options;
2465 sgmlOpenTag(ofs, 0, top);
2469 ofs << "<!-- " << LYX_DOCVERSION
2470 << " created this file. For more info see http://www.lyx.org/"
2473 Paragraph::depth_type depth = 0; // paragraph depth
2474 Paragraph * par = paragraph;
2476 vector<string> environment_stack(5);
2479 LyXLayout const & style =
2480 textclasslist.Style(params.textclass,
2483 // treat <toc> as a special case for compatibility with old code
2484 if (par->getChar(0) == Paragraph::META_INSET) {
2485 Inset * inset = par->getInset(0);
2486 Inset::Code lyx_code = inset->lyxCode();
2487 if (lyx_code == Inset::TOC_CODE){
2488 string const temp = "toc";
2489 sgmlOpenTag(ofs, depth, temp);
2496 // environment tag closing
2497 for (; depth > par->params().depth(); --depth) {
2498 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2499 environment_stack[depth].erase();
2502 // write opening SGML tags
2503 switch (style.latextype) {
2504 case LATEX_PARAGRAPH:
2505 if (depth == par->params().depth()
2506 && !environment_stack[depth].empty()) {
2507 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2508 environment_stack[depth].erase();
2514 sgmlOpenTag(ofs, depth, style.latexname());
2519 linuxDocError(par, 0,
2520 _("Error : Wrong depth for"
2521 " LatexType Command.\n"));
2523 if (!environment_stack[depth].empty()){
2524 sgmlCloseTag(ofs, depth,
2525 environment_stack[depth]);
2529 environment_stack[depth].erase();
2530 sgmlOpenTag(ofs, depth, style.latexname());
2533 case LATEX_ENVIRONMENT:
2534 case LATEX_ITEM_ENVIRONMENT:
2535 if (depth == par->params().depth()
2536 && environment_stack[depth] != style.latexname()) {
2537 sgmlCloseTag(ofs, depth,
2538 environment_stack[depth]);
2539 environment_stack[depth].erase();
2541 if (depth < par->params().depth()) {
2542 depth = par->params().depth();
2543 environment_stack[depth].erase();
2545 if (environment_stack[depth] != style.latexname()) {
2547 sgmlOpenTag(ofs, depth, "p");
2549 sgmlOpenTag(ofs, depth, style.latexname());
2551 if (environment_stack.size() == depth + 1)
2552 environment_stack.push_back("!-- --");
2553 environment_stack[depth] = style.latexname();
2556 if (style.latexparam() == "CDATA")
2559 if (style.latextype == LATEX_ENVIRONMENT) break;
2561 if (style.labeltype == LABEL_MANUAL)
2566 sgmlOpenTag(ofs, depth + 1, item_name);
2569 sgmlOpenTag(ofs, depth, style.latexname());
2573 simpleLinuxDocOnePar(ofs, par, depth);
2578 // write closing SGML tags
2579 switch (style.latextype) {
2582 case LATEX_ENVIRONMENT:
2583 case LATEX_ITEM_ENVIRONMENT:
2584 if (style.latexparam() == "CDATA")
2588 sgmlCloseTag(ofs, depth, style.latexname());
2594 for (int i=depth; i >= 0; --i)
2595 sgmlCloseTag(ofs, depth, environment_stack[i]);
2599 sgmlCloseTag(ofs, 0, top_element);
2603 // How to check for successful close
2607 void Buffer::docBookHandleCaption(ostream & os, string & inner_tag,
2608 Paragraph::depth_type depth, int desc_on,
2611 Paragraph * tpar = par;
2613 && (tpar->layout != textclasslist.NumberOfLayout(params.textclass,
2615 tpar = tpar->next();
2618 tpar->layout == textclasslist.NumberOfLayout(params.textclass,
2619 "Caption").second) {
2620 sgmlOpenTag(os, depth + 1, inner_tag);
2622 simpleDocBookOnePar(os, extra_par, tpar,
2623 desc_on, depth + 2);
2624 sgmlCloseTag(os, depth+1, inner_tag);
2625 if (!extra_par.empty())
2631 // checks, if newcol chars should be put into this line
2632 // writes newline, if necessary.
2635 void linux_doc_line_break(ostream & os, string::size_type & colcount,
2636 string::size_type newcol)
2639 if (colcount > lyxrc.ascii_linelen) {
2641 colcount = newcol; // assume write after this call
2656 string tag_name(PAR_TAG const & pt) {
2658 case NONE: return "!-- --";
2659 case TT: return "tt";
2660 case SF: return "sf";
2661 case BF: return "bf";
2662 case IT: return "it";
2663 case SL: return "sl";
2664 case EM: return "em";
2671 void operator|=(PAR_TAG & p1, PAR_TAG const & p2)
2673 p1 = static_cast<PAR_TAG>(p1 | p2);
2678 void reset(PAR_TAG & p1, PAR_TAG const & p2)
2680 p1 = static_cast<PAR_TAG>( p1 & ~p2);
2688 // Handle internal paragraph parsing -- layout already processed.
2689 void Buffer::simpleLinuxDocOnePar(ostream & os,
2691 Paragraph::depth_type /*depth*/)
2693 LyXLayout const & style = textclasslist.Style(params.textclass,
2695 string::size_type char_line_count = 5; // Heuristic choice ;-)
2697 // gets paragraph main font
2700 if (style.labeltype == LABEL_MANUAL) {
2701 font_old = style.labelfont;
2704 font_old = style.font;
2708 LyXFont::FONT_FAMILY family_type = LyXFont::ROMAN_FAMILY;
2709 LyXFont::FONT_SERIES series_type = LyXFont::MEDIUM_SERIES;
2710 LyXFont::FONT_SHAPE shape_type = LyXFont::UP_SHAPE;
2713 stack < PAR_TAG > tag_state;
2714 // parsing main loop
2715 for (Paragraph::size_type i = 0; i < par->size(); ++i) {
2717 PAR_TAG tag_close = NONE;
2718 list < PAR_TAG > tag_open;
2720 LyXFont const font = par->getFont(params, i);
2722 if (font_old.family() != font.family()) {
2723 switch (family_type) {
2724 case LyXFont::SANS_FAMILY:
2727 case LyXFont::TYPEWRITER_FAMILY:
2734 family_type = font.family();
2736 switch (family_type) {
2737 case LyXFont::SANS_FAMILY:
2738 tag_open.push_back(SF);
2740 case LyXFont::TYPEWRITER_FAMILY:
2741 tag_open.push_back(TT);
2748 if (font_old.series() != font.series()) {
2749 switch (series_type) {
2750 case LyXFont::BOLD_SERIES:
2757 series_type = font.series();
2759 switch (series_type) {
2760 case LyXFont::BOLD_SERIES:
2761 tag_open.push_back(BF);
2769 if (font_old.shape() != font.shape()) {
2770 switch (shape_type) {
2771 case LyXFont::ITALIC_SHAPE:
2774 case LyXFont::SLANTED_SHAPE:
2781 shape_type = font.shape();
2783 switch (shape_type) {
2784 case LyXFont::ITALIC_SHAPE:
2785 tag_open.push_back(IT);
2787 case LyXFont::SLANTED_SHAPE:
2788 tag_open.push_back(SL);
2795 if (font_old.emph() != font.emph()) {
2796 if (font.emph() == LyXFont::ON) {
2797 tag_open.push_back(EM);
2806 list < PAR_TAG > temp;
2807 while(!tag_state.empty() && tag_close ) {
2808 PAR_TAG k = tag_state.top();
2810 os << "</" << tag_name(k) << ">";
2817 for(list< PAR_TAG >::const_iterator j = temp.begin();
2818 j != temp.end(); ++j) {
2820 os << "<" << tag_name(*j) << ">";
2823 for(list< PAR_TAG >::const_iterator j = tag_open.begin();
2824 j != tag_open.end(); ++j) {
2826 os << "<" << tag_name(*j) << ">";
2829 char c = par->getChar(i);
2831 if (c == Paragraph::META_INSET) {
2832 Inset * inset = par->getInset(i);
2833 inset->linuxdoc(this, os);
2840 font.latex() == LyXFont::ON ||
2842 style.latexparam() == "CDATA") {
2843 // "TeX"-Mode on == > SGML-Mode on.
2849 if (par->linuxDocConvertChar(c, sgml_string)
2850 && !style.free_spacing) {
2851 // in freespacing mode, spaces are
2852 // non-breaking characters
2853 if (desc_on) {// if char is ' ' then...
2856 linux_doc_line_break(os, char_line_count, 6);
2860 linux_doc_line_break(os, char_line_count, 1);
2865 char_line_count += sgml_string.length();
2871 while (!tag_state.empty()) {
2872 os << "</" << tag_name(tag_state.top()) << ">";
2876 // resets description flag correctly
2878 // <tag> not closed...
2879 linux_doc_line_break(os, char_line_count, 6);
2885 // Print an error message.
2886 void Buffer::linuxDocError(Paragraph * par, int pos,
2887 string const & message)
2889 // insert an error marker in text
2890 InsetError * new_inset = new InsetError(message);
2891 par->insertInset(pos, new_inset);
2895 void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
2897 ofstream ofs(fname.c_str());
2899 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2903 Paragraph * par = paragraph;
2905 niceFile = nice; // this will be used by Insetincludes.
2907 LyXTextClass const & tclass =
2908 textclasslist.TextClass(params.textclass);
2910 LaTeXFeatures features(params, tclass.numLayouts());
2915 string top_element = textclasslist.LatexnameOfClass(params.textclass);
2918 string sgml_includedfiles = features.getIncludedFiles(fname);
2920 ofs << "<!doctype " << top_element
2921 << " public \"-//OASIS//DTD DocBook V3.1//EN\"";
2923 if (params.preamble.empty() && sgml_includedfiles.empty())
2926 ofs << "\n [ " << params.preamble
2927 << sgml_includedfiles << " \n]>\n\n";
2930 string top = top_element;
2932 top += params.language->code();
2935 if (!params.options.empty()) {
2937 top += params.options;
2939 sgmlOpenTag(ofs, 0, top);
2941 ofs << "<!-- DocBook file was created by " << LYX_DOCVERSION
2942 << "\n See http://www.lyx.org/ for more information -->\n";
2944 vector<string> environment_stack(10);
2945 vector<string> environment_inner(10);
2946 vector<string> command_stack(10);
2948 bool command_flag = false;
2949 Paragraph::depth_type command_depth = 0;
2950 Paragraph::depth_type command_base = 0;
2951 Paragraph::depth_type cmd_depth = 0;
2952 Paragraph::depth_type depth = 0; // paragraph depth
2955 string command_name;
2961 int desc_on = 0; // description mode
2963 LyXLayout const & style =
2964 textclasslist.Style(params.textclass,
2967 // environment tag closing
2968 for (; depth > par->params().depth(); --depth) {
2969 if (environment_inner[depth] != "!-- --") {
2970 item_name = "listitem";
2971 sgmlCloseTag(ofs, command_depth + depth,
2973 if (environment_inner[depth] == "varlistentry")
2974 sgmlCloseTag(ofs, depth+command_depth,
2975 environment_inner[depth]);
2977 sgmlCloseTag(ofs, depth + command_depth,
2978 environment_stack[depth]);
2979 environment_stack[depth].erase();
2980 environment_inner[depth].erase();
2983 if (depth == par->params().depth()
2984 && environment_stack[depth] != style.latexname()
2985 && !environment_stack[depth].empty()) {
2986 if (environment_inner[depth] != "!-- --") {
2987 item_name= "listitem";
2988 sgmlCloseTag(ofs, command_depth+depth,
2990 if (environment_inner[depth] == "varlistentry")
2992 depth + command_depth,
2993 environment_inner[depth]);
2996 sgmlCloseTag(ofs, depth + command_depth,
2997 environment_stack[depth]);
2999 environment_stack[depth].erase();
3000 environment_inner[depth].erase();
3003 // Write opening SGML tags.
3004 switch (style.latextype) {
3005 case LATEX_PARAGRAPH:
3006 sgmlOpenTag(ofs, depth + command_depth,
3012 linuxDocError(par, 0,
3013 _("Error : Wrong depth for "
3014 "LatexType Command.\n"));
3016 command_name = style.latexname();
3018 sgmlparam = style.latexparam();
3019 c_params = split(sgmlparam, c_depth,'|');
3021 cmd_depth = lyx::atoi(c_depth);
3024 if (cmd_depth < command_base) {
3025 for (Paragraph::depth_type j = command_depth; j >= command_base; --j)
3026 sgmlCloseTag(ofs, j, command_stack[j]);
3027 command_depth = command_base = cmd_depth;
3028 } else if (cmd_depth <= command_depth) {
3029 for (int j = command_depth; j >= int(cmd_depth); --j)
3030 sgmlCloseTag(ofs, j, command_stack[j]);
3031 command_depth = cmd_depth;
3033 command_depth = cmd_depth;
3035 command_depth = command_base = cmd_depth;
3036 command_flag = true;
3038 if (command_stack.size() == command_depth + 1)
3039 command_stack.push_back(string());
3040 command_stack[command_depth] = command_name;
3042 // treat label as a special case for
3043 // more WYSIWYM handling.
3044 if (par->getChar(0) == Paragraph::META_INSET) {
3045 Inset * inset = par->getInset(0);
3046 Inset::Code lyx_code = inset->lyxCode();
3047 if (lyx_code == Inset::LABEL_CODE){
3048 command_name += " id=\"";
3049 command_name += (static_cast<InsetCommand *>(inset))->getContents();
3050 command_name += "\"";
3055 sgmlOpenTag(ofs, depth + command_depth, command_name);
3056 if (c_params.empty())
3057 item_name = "title";
3059 item_name = c_params;
3060 sgmlOpenTag(ofs, depth + 1 + command_depth, item_name);
3063 case LATEX_ENVIRONMENT:
3064 case LATEX_ITEM_ENVIRONMENT:
3065 if (depth < par->params().depth()) {
3066 depth = par->params().depth();
3067 environment_stack[depth].erase();
3070 if (environment_stack[depth] != style.latexname()) {
3071 if(environment_stack.size() == depth + 1) {
3072 environment_stack.push_back("!-- --");
3073 environment_inner.push_back("!-- --");
3075 environment_stack[depth] = style.latexname();
3076 environment_inner[depth] = "!-- --";
3077 sgmlOpenTag(ofs, depth + command_depth,
3078 environment_stack[depth]);
3080 if (environment_inner[depth] != "!-- --") {
3081 item_name= "listitem";
3083 command_depth + depth,
3085 if (environment_inner[depth] == "varlistentry")
3087 depth + command_depth,
3088 environment_inner[depth]);
3092 if (style.latextype == LATEX_ENVIRONMENT) {
3093 if (!style.latexparam().empty()) {
3094 if(style.latexparam() == "CDATA")
3097 sgmlOpenTag(ofs, depth + command_depth,
3098 style.latexparam());
3103 desc_on = (style.labeltype == LABEL_MANUAL);
3106 environment_inner[depth]= "varlistentry";
3108 environment_inner[depth]= "listitem";
3110 sgmlOpenTag(ofs, depth + 1 + command_depth,
3111 environment_inner[depth]);
3115 sgmlOpenTag(ofs, depth + 1 + command_depth,
3119 sgmlOpenTag(ofs, depth + 1 + command_depth,
3124 sgmlOpenTag(ofs, depth + command_depth,
3130 simpleDocBookOnePar(ofs, extra_par, par, desc_on,
3131 depth + 1 + command_depth);
3135 // write closing SGML tags
3136 switch (style.latextype) {
3138 if (c_params.empty())
3142 sgmlCloseTag(ofs, depth + command_depth, end_tag);
3144 case LATEX_ENVIRONMENT:
3145 if (!style.latexparam().empty()) {
3146 if(style.latexparam() == "CDATA")
3149 sgmlCloseTag(ofs, depth + command_depth,
3150 style.latexparam());
3153 case LATEX_ITEM_ENVIRONMENT:
3154 if (desc_on == 1) break;
3156 sgmlCloseTag(ofs, depth + 1 + command_depth, end_tag);
3158 case LATEX_PARAGRAPH:
3159 sgmlCloseTag(ofs, depth + command_depth, style.latexname());
3162 sgmlCloseTag(ofs, depth + command_depth, style.latexname());
3168 for (int d = depth; d >= 0; --d) {
3169 if (!environment_stack[depth].empty()) {
3170 if (environment_inner[depth] != "!-- --") {
3171 item_name = "listitem";
3172 sgmlCloseTag(ofs, command_depth + depth,
3174 if (environment_inner[depth] == "varlistentry")
3175 sgmlCloseTag(ofs, depth + command_depth,
3176 environment_inner[depth]);
3179 sgmlCloseTag(ofs, depth + command_depth,
3180 environment_stack[depth]);
3184 for (int j = command_depth; j >= 0 ; --j)
3185 if (!command_stack[j].empty())
3186 sgmlCloseTag(ofs, j, command_stack[j]);
3189 sgmlCloseTag(ofs, 0, top_element);
3192 // How to check for successful close
3196 void Buffer::simpleDocBookOnePar(ostream & os, string & extra,
3197 Paragraph * par, int & desc_on,
3198 Paragraph::depth_type depth) const
3200 bool emph_flag = false;
3202 LyXLayout const & style = textclasslist.Style(params.textclass,
3205 LyXFont font_old = style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
3207 int char_line_count = depth;
3208 //if (!style.free_spacing)
3209 // os << string(depth,' ');
3211 // parsing main loop
3212 for (Paragraph::size_type i = 0;
3213 i < par->size(); ++i) {
3214 LyXFont font = par->getFont(params, i);
3216 // handle <emphasis> tag
3217 if (font_old.emph() != font.emph()) {
3218 if (font.emph() == LyXFont::ON) {
3222 os << "</emphasis>";
3227 char c = par->getChar(i);
3229 if (c == Paragraph::META_INSET) {
3230 Inset * inset = par->getInset(i);
3231 std::ostringstream ost;
3232 inset->docBook(this, ost);
3233 string tmp_out = ost.str().c_str();
3236 // This code needs some explanation:
3237 // Two insets are treated specially
3238 // label if it is the first element in a command paragraph
3240 // graphics inside tables or figure floats can't go on
3241 // title (the equivalente in latex for this case is caption
3242 // and title should come first
3245 if (desc_on!= 3 || i!= 0) {
3246 if (!tmp_out.empty() && tmp_out[0] == '@') {
3248 extra += frontStrip(tmp_out, '@');
3250 os << frontStrip(tmp_out, '@');
3256 } else if (font.latex() == LyXFont::ON) {
3257 // "TeX"-Mode on ==> SGML-Mode on.
3264 if (par->linuxDocConvertChar(c, sgml_string)
3265 && !style.free_spacing) { // in freespacing
3267 // non-breaking characters
3271 os << "\n</term><listitem><para>";
3284 os << "</emphasis>";
3287 // resets description flag correctly
3289 // <term> not closed...
3292 if(style.free_spacing) os << '\n';
3296 // This should be enabled when the Chktex class is implemented. (Asger)
3297 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
3298 // Other flags: -wall -v0 -x
3299 int Buffer::runChktex()
3301 if (!users->text) return 0;
3303 users->owner()->prohibitInput();
3305 // get LaTeX-Filename
3306 string const name = getLatexName();
3307 string path = OnlyPath(filename);
3309 string const org_path = path;
3310 if (lyxrc.use_tempdir || (IsDirWriteable(path) < 1)) {
3314 Path p(path); // path to LaTeX file
3315 users->owner()->message(_("Running chktex..."));
3317 // Remove all error insets
3318 bool const removedErrorInsets = users->removeAutoInsets();
3320 // Generate the LaTeX file if neccessary
3321 makeLaTeXFile(name, org_path, false);
3324 Chktex chktex(lyxrc.chktex_command, name, filepath);
3325 int res = chktex.run(terr); // run chktex
3328 WriteAlert(_("chktex did not work!"),
3329 _("Could not run with file:"), name);
3330 } else if (res > 0) {
3331 // Insert all errors as errors boxes
3332 users->insertErrors(terr);
3335 // if we removed error insets before we ran chktex or if we inserted
3336 // error insets after we ran chktex, this must be run:
3337 if (removedErrorInsets || res){
3339 users->fitCursor(users->text);
3341 users->owner()->allowInput();
3347 void Buffer::validate(LaTeXFeatures & features) const
3349 Paragraph * par = paragraph;
3350 LyXTextClass const & tclass =
3351 textclasslist.TextClass(params.textclass);
3353 // AMS Style is at document level
3355 features.amsstyle = (params.use_amsmath ||
3356 tclass.provides(LyXTextClass::amsmath));
3359 // We don't use "lyxerr.debug" because of speed. (Asger)
3360 if (lyxerr.debugging(Debug::LATEX))
3361 lyxerr << "Paragraph: " << par << endl;
3363 // Now just follow the list of paragraphs and run
3364 // validate on each of them.
3365 par->validate(features);
3367 // and then the next paragraph
3371 // the bullet shapes are buffer level not paragraph level
3372 // so they are tested here
3373 for (int i = 0; i < 4; ++i) {
3374 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
3375 int const font = params.user_defined_bullets[i].getFont();
3377 int const c = params
3378 .user_defined_bullets[i]
3385 features.latexsym = true;
3387 } else if (font == 1) {
3388 features.amssymb = true;
3389 } else if ((font >= 2 && font <= 5)) {
3390 features.pifont = true;
3395 if (lyxerr.debugging(Debug::LATEX)) {
3396 features.showStruct();
3401 void Buffer::setPaperStuff()
3403 params.papersize = BufferParams::PAPER_DEFAULT;
3404 char const c1 = params.paperpackage;
3405 if (c1 == BufferParams::PACKAGE_NONE) {
3406 char const c2 = params.papersize2;
3407 if (c2 == BufferParams::VM_PAPER_USLETTER)
3408 params.papersize = BufferParams::PAPER_USLETTER;
3409 else if (c2 == BufferParams::VM_PAPER_USLEGAL)
3410 params.papersize = BufferParams::PAPER_LEGALPAPER;
3411 else if (c2 == BufferParams::VM_PAPER_USEXECUTIVE)
3412 params.papersize = BufferParams::PAPER_EXECUTIVEPAPER;
3413 else if (c2 == BufferParams::VM_PAPER_A3)
3414 params.papersize = BufferParams::PAPER_A3PAPER;
3415 else if (c2 == BufferParams::VM_PAPER_A4)
3416 params.papersize = BufferParams::PAPER_A4PAPER;
3417 else if (c2 == BufferParams::VM_PAPER_A5)
3418 params.papersize = BufferParams::PAPER_A5PAPER;
3419 else if ((c2 == BufferParams::VM_PAPER_B3) || (c2 == BufferParams::VM_PAPER_B4) ||
3420 (c2 == BufferParams::VM_PAPER_B5))
3421 params.papersize = BufferParams::PAPER_B5PAPER;
3422 } else if ((c1 == BufferParams::PACKAGE_A4) || (c1 == BufferParams::PACKAGE_A4WIDE) ||
3423 (c1 == BufferParams::PACKAGE_WIDEMARGINSA4))
3424 params.papersize = BufferParams::PAPER_A4PAPER;
3428 // This function should be in Buffer because it's a buffer's property (ale)
3429 string const Buffer::getIncludeonlyList(char delim)
3432 for (inset_iterator it = inset_iterator_begin();
3433 it != inset_iterator_end(); ++it) {
3434 if ((*it)->lyxCode() == Inset::INCLUDE_CODE) {
3435 InsetInclude * insetinc =
3436 static_cast<InsetInclude *>(*it);
3437 if (insetinc->isIncludeOnly()) {
3440 lst += insetinc->getRelFileBaseName();
3444 lyxerr[Debug::INFO] << "Includeonly(" << lst << ')' << endl;
3449 vector<string> const Buffer::getLabelList()
3451 /// if this is a child document and the parent is already loaded
3452 /// Use the parent's list instead [ale990407]
3453 if (!params.parentname.empty()
3454 && bufferlist.exists(params.parentname)) {
3455 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3457 return tmp->getLabelList();
3460 vector<string> label_list;
3461 for (inset_iterator it = inset_iterator_begin();
3462 it != inset_iterator_end(); ++it) {
3463 vector<string> const l = (*it)->getLabelList();
3464 label_list.insert(label_list.end(), l.begin(), l.end());
3470 Buffer::Lists const Buffer::getLists() const
3473 Paragraph * par = paragraph;
3475 LyXTextClassList::size_type cap;
3476 boost::tie(found, cap) = textclasslist
3477 .NumberOfLayout(params.textclass, "Caption");
3480 char const labeltype =
3481 textclasslist.Style(params.textclass,
3482 par->getLayout()).labeltype;
3484 if (labeltype >= LABEL_COUNTER_CHAPTER
3485 && labeltype <= LABEL_COUNTER_CHAPTER + params.tocdepth) {
3486 // insert this into the table of contents
3487 SingleList & item = l["TOC"];
3490 textclasslist.TextClass(params.textclass).maxcounter());
3491 item.push_back(TocItem(par, depth, par->asString(this, true)));
3493 // For each paragrph, traverse its insets and look for
3497 Paragraph::inset_iterator it =
3498 par->inset_iterator_begin();
3499 Paragraph::inset_iterator end =
3500 par->inset_iterator_end();
3502 for (; it != end; ++it) {
3503 if ((*it)->lyxCode() == Inset::FLOAT_CODE) {
3505 static_cast<InsetFloat*>(*it);
3507 string const type = il->type();
3509 // Now find the caption in the float...
3510 // We now tranverse the paragraphs of
3512 Paragraph * tmp = il->inset.paragraph();
3514 if (tmp->layout == cap) {
3515 SingleList & item = l[type];
3517 tostr(item.size()+1) + ". " + tmp->asString(this, false);
3518 item.push_back(TocItem(tmp, 0 , str));
3525 lyxerr << "caption not found" << endl;
3534 // This is also a buffer property (ale)
3535 vector<pair<string, string> > const Buffer::getBibkeyList()
3537 /// if this is a child document and the parent is already loaded
3538 /// Use the parent's list instead [ale990412]
3539 if (!params.parentname.empty() && bufferlist.exists(params.parentname)) {
3540 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3542 return tmp->getBibkeyList();
3545 vector<pair<string, string> > keys;
3546 Paragraph * par = paragraph;
3549 keys.push_back(pair<string, string>(par->bibkey->getContents(),
3550 par->asString(this, false)));
3554 // Might be either using bibtex or a child has bibliography
3556 for (inset_iterator it = inset_iterator_begin();
3557 it != inset_iterator_end(); ++it) {
3558 // Search for Bibtex or Include inset
3559 if ((*it)->lyxCode() == Inset::BIBTEX_CODE) {
3560 vector<pair<string,string> > tmp =
3561 static_cast<InsetBibtex*>(*it)->getKeys(this);
3562 keys.insert(keys.end(), tmp.begin(), tmp.end());
3563 } else if ((*it)->lyxCode() == Inset::INCLUDE_CODE) {
3564 vector<pair<string,string> > const tmp =
3565 static_cast<InsetInclude*>(*it)->getKeys();
3566 keys.insert(keys.end(), tmp.begin(), tmp.end());
3575 bool Buffer::isDepClean(string const & name) const
3577 DEPCLEAN * item = dep_clean;
3578 while (item && item->master != name)
3580 if (!item) return true;
3585 void Buffer::markDepClean(string const & name)
3588 dep_clean = new DEPCLEAN;
3589 dep_clean->clean = true;
3590 dep_clean->master = name;
3591 dep_clean->next = 0;
3593 DEPCLEAN * item = dep_clean;
3594 while (item && item->master != name)
3599 item = new DEPCLEAN;
3601 item->master = name;
3608 bool Buffer::dispatch(string const & command)
3610 // Split command string into command and argument
3612 string line = frontStrip(command);
3613 string const arg = strip(frontStrip(split(line, cmd, ' ')));
3615 return dispatch(lyxaction.LookupFunc(cmd), arg);
3619 bool Buffer::dispatch(int action, string const & argument)
3621 bool dispatched = true;
3624 Exporter::Export(this, argument, false);
3634 void Buffer::resizeInsets(BufferView * bv)
3636 /// then remove all LyXText in text-insets
3637 Paragraph * par = paragraph;
3638 for (; par; par = par->next()) {
3639 par->resizeInsetsLyXText(bv);
3644 void Buffer::redraw()
3647 users->fitCursor(users->text);
3651 void Buffer::changeLanguage(Language const * from, Language const * to)
3654 Paragraph * par = paragraph;
3656 par->changeLanguage(params, from, to);
3662 bool Buffer::isMultiLingual()
3664 Paragraph * par = paragraph;
3666 if (par->isMultiLingual(params))
3674 Buffer::inset_iterator::inset_iterator(Paragraph * paragraph,
3675 Paragraph::size_type pos)
3678 it = par->InsetIterator(pos);
3679 if (it == par->inset_iterator_end()) {
3686 void Buffer::inset_iterator::setParagraph()
3689 it = par->inset_iterator_begin();
3690 if (it != par->inset_iterator_end())
3695 // We maintain an invariant that whenever par = 0 then it = 0
3699 Inset * Buffer::getInsetFromID(int id_arg) const
3701 for (inset_iterator it = inset_const_iterator_begin();
3702 it != inset_const_iterator_end(); ++it)
3704 if ((*it)->id() == id_arg)
3706 Inset * in = (*it)->getInsetFromID(id_arg);
3714 Paragraph * Buffer::getParFromID(int id) const
3716 if (id < 0) return 0;
3717 Paragraph * par = paragraph;
3719 if (par->id() == id) {
3722 Paragraph * tmp = par->getParFromID(id);