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"
114 using std::make_pair;
122 // all these externs should eventually be removed.
123 extern BufferList bufferlist;
125 extern LyXAction lyxaction;
129 const int LYX_FORMAT = 220;
133 extern int tex_code_break_column;
136 Buffer::Buffer(string const & file, bool ronly)
138 lyxerr[Debug::INFO] << "Buffer::Buffer()" << endl;
140 filepath = OnlyPath(file);
149 if (read_only || (lyxrc.use_tempdir)) {
150 tmppath = CreateBufferTmpDir();
151 } else tmppath.erase();
157 lyxerr[Debug::INFO] << "Buffer::~Buffer()" << endl;
158 // here the buffer should take care that it is
159 // saved properly, before it goes into the void.
161 // make sure that views using this buffer
166 if (!tmppath.empty()) {
167 DestroyBufferTmpDir(tmppath);
170 Paragraph * par = paragraph;
173 tmppar = par->next();
181 string const Buffer::getLatexName(bool no_path) const
183 string name = ChangeExtension(MakeLatexName(filename), ".tex");
185 return OnlyFilename(name);
191 pair<Buffer::LogType, string> const Buffer::getLogName(void) const
193 string const filename = getLatexName(false);
195 if (filename.empty())
196 return make_pair(Buffer::latexlog, string());
198 string path = OnlyPath(filename);
200 if (lyxrc.use_tempdir || (IsDirWriteable(path) < 1))
203 string const fname = AddName(path,
204 OnlyFilename(ChangeExtension(filename,
207 AddName(path, OnlyFilename(
208 ChangeExtension(filename,
209 formats.Extension("literate") + ".out")));
211 // If no Latex log or Build log is newer, show Build log
213 FileInfo const f_fi(fname);
214 FileInfo const b_fi(bname);
217 (!f_fi.exist() || f_fi.getModificationTime() < b_fi.getModificationTime())) {
218 lyxerr[Debug::FILES] << "Log name calculated as : " << bname << endl;
219 return make_pair(Buffer::buildlog, bname);
221 lyxerr[Debug::FILES] << "Log name calculated as : " << fname << endl;
222 return make_pair(Buffer::latexlog, fname);
226 void Buffer::setReadonly(bool flag)
228 if (read_only != flag) {
231 users->owner()->getDialogs()->updateBufferDependent(false);
234 WarnReadonly(filename);
239 bool Buffer::saveParamsAsDefaults() // const
241 string const fname = AddName(AddPath(user_lyxdir, "templates/"),
243 Buffer defaults = Buffer(fname);
245 // Use the current buffer's parameters as default
246 defaults.params = params;
248 // add an empty paragraph. Is this enough?
249 defaults.paragraph = new Paragraph;
251 return defaults.writeFile(defaults.filename, false);
255 /// Update window titles of all users
256 // Should work on a list
257 void Buffer::updateTitles() const
259 if (users) users->owner()->updateWindowTitle();
263 /// Reset autosave timer of all users
264 // Should work on a list
265 void Buffer::resetAutosaveTimers() const
267 if (users) users->owner()->resetAutosaveTimer();
271 void Buffer::setFileName(string const & newfile)
273 filename = MakeAbsPath(newfile);
274 filepath = OnlyPath(filename);
275 setReadonly(IsFileWriteable(filename) == 0);
280 // We'll remove this later. (Lgb)
283 string last_inset_read;
287 ErtComp() : active(false), in_tabular(false) {
294 std::stack<ErtComp> ert_stack;
303 // candidate for move to BufferView
304 // (at least some parts in the beginning of the func)
307 // changed to be public and have one parameter
308 // if par = 0 normal behavior
309 // else insert behavior
310 // Returns false if "\the_end" is not read for formats >= 2.13. (Asger)
311 bool Buffer::readLyXformat2(LyXLex & lex, Paragraph * par)
315 ert_comp.contents.erase();
316 ert_comp.active = false;
317 ert_comp.in_tabular = false;
321 Paragraph::depth_type depth = 0;
322 bool the_end_read = false;
324 Paragraph * first_par = 0;
325 LyXFont font(LyXFont::ALL_INHERIT, params.language);
326 if (file_format < 216 && params.language->lang() == "hebrew")
327 font.setLanguage(default_language);
332 // We are inserting into an existing document
333 users->text->breakParagraph(users);
334 first_par = users->text->firstParagraph();
337 // We don't want to adopt the parameters from the
338 // document we insert, so we skip until the text begins:
341 string const pretoken = lex.GetString();
342 if (pretoken == "\\layout") {
343 lex.pushToken(pretoken);
351 string const token = lex.GetString();
353 if (token.empty()) continue;
355 lyxerr[Debug::PARSER] << "Handling token: `"
356 << token << "'" << endl;
359 parseSingleLyXformat2Token(lex, par, first_par,
367 paragraph = first_par;
369 if (unknown_layouts > 0) {
370 string s = _("Couldn't set the layout for ");
371 if (unknown_layouts == 1) {
372 s += _("one paragraph");
374 s += tostr(unknown_layouts);
375 s += _(" paragraphs");
377 WriteAlert(_("Textclass Loading Error!"), s,
378 _("When reading " + fileName()));
385 void Buffer::insertErtContents(Paragraph * par, int & pos,
386 LyXFont const & font, bool set_inactive)
388 if (!ert_comp.contents.empty()) {
389 lyxerr[Debug::INSETS] << "ERT contents:\n"
390 << ert_comp.contents << endl;
391 Inset * inset = new InsetERT(ert_comp.contents);
392 par->insertInset(pos++, inset, font);
393 ert_comp.contents.erase();
396 ert_comp.active = false;
402 Buffer::parseSingleLyXformat2Token(LyXLex & lex, Paragraph *& par,
403 Paragraph *& first_par,
404 string const & token, int & pos,
405 Paragraph::depth_type & depth,
409 bool the_end_read = false;
410 #ifndef NO_PEXTRA_REALLY
411 // This is super temporary but is needed to get the compability
412 // mode for minipages work correctly together with new tabulars.
413 static int call_depth;
415 bool checkminipage = false;
416 static Paragraph * minipar;
417 static Paragraph * parBeforeMinipage;
420 if (token[0] != '\\') {
422 if (ert_comp.active) {
423 ert_comp.contents += token;
426 for (string::const_iterator cit = token.begin();
427 cit != token.end(); ++cit) {
428 par->insertChar(pos, (*cit), font);
431 checkminipage = true;
435 } else if (token == "\\i") {
436 Inset * inset = new InsetLatexAccent;
437 inset->read(this, lex);
438 par->insertInset(pos, inset, font);
440 } else if (token == "\\layout") {
442 ert_comp.in_tabular = false;
444 insertErtContents(par, pos, font);
447 string const layoutname = lex.GetString();
448 pair<bool, LyXTextClass::LayoutList::size_type> pp
449 = textclasslist.NumberOfLayout(params.textclass,
453 if (compare_no_case(layoutname, "latex") == 0) {
454 ert_comp.active = true;
458 // The is the compability reading of layout caption.
459 // It can be removed in LyX version 1.3.0. (Lgb)
460 if (compare_no_case(layoutname, "caption") == 0) {
461 // We expect that the par we are now working on is
462 // really inside a InsetText inside a InsetFloat.
463 // We also know that captions can only be
464 // one paragraph. (Lgb)
466 // We should now read until the next "\layout"
468 // This is probably not good enough, what if the
469 // caption is the last par in the document (Lgb)
470 istream & ist = lex.getStream();
476 if (prefixIs(line, "\\layout")) {
480 if (prefixIs(line, "\\begin_inset"))
482 if (prefixIs(line, "\\end_inset")) {
493 // Now we should have the whole layout in ss
494 // we should now be able to give this to the
496 ss << "\\end_inset\n";
498 // This seems like a bug in stringstream.
499 // We really should be able to use ss
501 istringstream is(ss.str());
503 tmplex.setStream(is);
504 Inset * inset = new InsetCaption;
505 inset->Read(this, tmplex);
506 par->InsertInset(pos, inset, font);
513 par = new Paragraph(par);
517 par->layout = pp.second;
520 // use default layout "Standard" (0)
523 string const s = _("Layout had to be changed from\n")
524 + layoutname + _(" to ")
525 + textclasslist.NameOfLayout(params.textclass, par->layout);
526 InsetError * new_inset = new InsetError(s);
527 par->insertInset(0, new_inset);
529 // Test whether the layout is obsolete.
530 LyXLayout const & layout =
531 textclasslist.Style(params.textclass,
533 if (!layout.obsoleted_by().empty())
534 par->layout = textclasslist
535 .NumberOfLayout(params.textclass,
536 layout.obsoleted_by())
538 par->params().depth(depth);
539 font = LyXFont(LyXFont::ALL_INHERIT, params.language);
540 if (file_format < 216
541 && params.language->lang() == "hebrew")
542 font.setLanguage(default_language);
547 } else if (token == "\\begin_float") {
548 // This is the compability reader. It can be removed in
549 // LyX version 1.3.0. (Lgb)
551 string const tmptok = lex.GetString();
552 //lyxerr << "old float: " << tmptok << endl;
555 stringstream old_float;
557 if (tmptok == "footnote") {
558 inset = new InsetFoot;
559 } else if (tmptok == "margin") {
560 inset = new InsetMarginal;
561 } else if (tmptok == "fig") {
562 inset = new InsetFloat("figure");
563 old_float << "placement htbp\n"
565 } else if (tmptok == "tab") {
566 inset = new InsetFloat("table");
567 old_float << "placement htbp\n"
569 } else if (tmptok == "alg") {
570 inset = new InsetFloat("algorithm");
571 old_float << "placement htbp\n"
573 } else if (tmptok == "wide-fig") {
574 inset = new InsetFloat("figure");
575 //InsetFloat * tmp = new InsetFloat("figure");
578 old_float << "placement htbp\n"
580 } else if (tmptok == "wide-tab") {
581 inset = new InsetFloat("table");
582 //InsetFloat * tmp = new InsetFloat("table");
585 old_float << "placement htbp\n"
591 return false; // no end read yet
594 old_float << "collapsed true\n";
596 // Here we need to check for \end_deeper and handle that
597 // before we do the footnote parsing.
598 // This _is_ a hack! (Lgb)
601 string const tmp = lex.GetString();
602 if (tmp == "\\end_deeper") {
603 //lyxerr << "\\end_deeper caught!" << endl;
605 lex.printError("\\end_deeper: "
606 "depth is already null");
611 old_float << tmp << ' ';
616 old_float << lex.getLongString("\\end_float")
617 << "\n\\end_inset\n";
618 //lyxerr << "Float Body:\n" << old_float.str() << endl;
619 // That this does not work seems like a bug
620 // in stringstream. (Lgb)
621 istringstream istr(old_float.str());
623 nylex.setStream(istr);
624 inset->read(this, nylex);
625 par->insertInset(pos, inset, font);
627 } else if (token == "\\begin_deeper") {
629 } else if (token == "\\end_deeper") {
631 lex.printError("\\end_deeper: "
632 "depth is already null");
636 } else if (token == "\\begin_preamble") {
637 params.readPreamble(lex);
638 } else if (token == "\\textclass") {
640 pair<bool, LyXTextClassList::size_type> pp =
641 textclasslist.NumberOfClass(lex.GetString());
643 params.textclass = pp.second;
645 WriteAlert(string(_("Textclass error")),
646 string(_("The document uses an unknown textclass \"")) +
647 lex.GetString() + string("\"."),
648 string(_("LyX will not be able to produce output correctly.")));
649 params.textclass = 0;
651 if (!textclasslist.Load(params.textclass)) {
652 // if the textclass wasn't loaded properly
653 // we need to either substitute another
654 // or stop loading the file.
655 // I can substitute but I don't see how I can
656 // stop loading... ideas?? ARRae980418
657 WriteAlert(_("Textclass Loading Error!"),
658 string(_("Can't load textclass ")) +
659 textclasslist.NameOfClass(params.textclass),
660 _("-- substituting default"));
661 params.textclass = 0;
663 } else if (token == "\\options") {
665 params.options = lex.GetString();
666 } else if (token == "\\language") {
667 params.readLanguage(lex);
668 } else if (token == "\\fontencoding") {
670 } else if (token == "\\inputencoding") {
672 params.inputenc = lex.GetString();
673 } else if (token == "\\graphics") {
674 params.readGraphicsDriver(lex);
675 } else if (token == "\\fontscheme") {
677 params.fonts = lex.GetString();
678 } else if (token == "\\noindent") {
679 par->params().noindent(true);
680 } else if (token == "\\fill_top") {
681 par->params().spaceTop(VSpace(VSpace::VFILL));
682 } else if (token == "\\fill_bottom") {
683 par->params().spaceBottom(VSpace(VSpace::VFILL));
684 } else if (token == "\\line_top") {
685 par->params().lineTop(true);
686 } else if (token == "\\line_bottom") {
687 par->params().lineBottom(true);
688 } else if (token == "\\pagebreak_top") {
689 par->params().pagebreakTop(true);
690 } else if (token == "\\pagebreak_bottom") {
691 par->params().pagebreakBottom(true);
692 } else if (token == "\\start_of_appendix") {
693 par->params().startOfAppendix(true);
694 } else if (token == "\\paragraph_separation") {
695 int tmpret = lex.FindToken(string_paragraph_separation);
696 if (tmpret == -1) ++tmpret;
697 if (tmpret != LYX_LAYOUT_DEFAULT)
698 params.paragraph_separation =
699 static_cast<BufferParams::PARSEP>(tmpret);
700 } else if (token == "\\defskip") {
702 params.defskip = VSpace(lex.GetString());
703 } else if (token == "\\epsfig") { // obsolete
704 // Indeed it is obsolete, but we HAVE to be backwards
705 // compatible until 0.14, because otherwise all figures
706 // in existing documents are irretrivably lost. (Asger)
707 params.readGraphicsDriver(lex);
708 } else if (token == "\\quotes_language") {
709 int tmpret = lex.FindToken(string_quotes_language);
710 if (tmpret == -1) ++tmpret;
711 if (tmpret != LYX_LAYOUT_DEFAULT) {
712 InsetQuotes::quote_language tmpl =
713 InsetQuotes::EnglishQ;
716 tmpl = InsetQuotes::EnglishQ;
719 tmpl = InsetQuotes::SwedishQ;
722 tmpl = InsetQuotes::GermanQ;
725 tmpl = InsetQuotes::PolishQ;
728 tmpl = InsetQuotes::FrenchQ;
731 tmpl = InsetQuotes::DanishQ;
734 params.quotes_language = tmpl;
736 } else if (token == "\\quotes_times") {
738 switch (lex.GetInteger()) {
740 params.quotes_times = InsetQuotes::SingleQ;
743 params.quotes_times = InsetQuotes::DoubleQ;
746 } else if (token == "\\papersize") {
747 int tmpret = lex.FindToken(string_papersize);
751 params.papersize2 = tmpret;
752 } else if (token == "\\paperpackage") {
753 int tmpret = lex.FindToken(string_paperpackages);
756 params.paperpackage = BufferParams::PACKAGE_NONE;
758 params.paperpackage = tmpret;
759 } else if (token == "\\use_geometry") {
761 params.use_geometry = lex.GetInteger();
762 } else if (token == "\\use_amsmath") {
764 params.use_amsmath = lex.GetInteger();
765 } else if (token == "\\use_natbib") {
767 params.use_natbib = lex.GetInteger();
768 } else if (token == "\\use_numerical_citations") {
770 params.use_numerical_citations = lex.GetInteger();
771 } else if (token == "\\paperorientation") {
772 int tmpret = lex.FindToken(string_orientation);
773 if (tmpret == -1) ++tmpret;
774 if (tmpret != LYX_LAYOUT_DEFAULT)
775 params.orientation = static_cast<BufferParams::PAPER_ORIENTATION>(tmpret);
776 } else if (token == "\\paperwidth") {
778 params.paperwidth = lex.GetString();
779 } else if (token == "\\paperheight") {
781 params.paperheight = lex.GetString();
782 } else if (token == "\\leftmargin") {
784 params.leftmargin = lex.GetString();
785 } else if (token == "\\topmargin") {
787 params.topmargin = lex.GetString();
788 } else if (token == "\\rightmargin") {
790 params.rightmargin = lex.GetString();
791 } else if (token == "\\bottommargin") {
793 params.bottommargin = lex.GetString();
794 } else if (token == "\\headheight") {
796 params.headheight = lex.GetString();
797 } else if (token == "\\headsep") {
799 params.headsep = lex.GetString();
800 } else if (token == "\\footskip") {
802 params.footskip = lex.GetString();
803 } else if (token == "\\paperfontsize") {
805 params.fontsize = strip(lex.GetString());
806 } else if (token == "\\papercolumns") {
808 params.columns = lex.GetInteger();
809 } else if (token == "\\papersides") {
811 switch (lex.GetInteger()) {
813 case 1: params.sides = LyXTextClass::OneSide; break;
814 case 2: params.sides = LyXTextClass::TwoSides; break;
816 } else if (token == "\\paperpagestyle") {
818 params.pagestyle = strip(lex.GetString());
819 } else if (token == "\\bullet") {
821 int const index = lex.GetInteger();
823 int temp_int = lex.GetInteger();
824 params.user_defined_bullets[index].setFont(temp_int);
825 params.temp_bullets[index].setFont(temp_int);
827 temp_int = lex.GetInteger();
828 params.user_defined_bullets[index].setCharacter(temp_int);
829 params.temp_bullets[index].setCharacter(temp_int);
831 temp_int = lex.GetInteger();
832 params.user_defined_bullets[index].setSize(temp_int);
833 params.temp_bullets[index].setSize(temp_int);
835 string const temp_str = lex.GetString();
836 if (temp_str != "\\end_bullet") {
837 // this element isn't really necessary for
838 // parsing but is easier for humans
839 // to understand bullets. Put it back and
840 // set a debug message?
841 lex.printError("\\end_bullet expected, got" + temp_str);
842 //how can I put it back?
844 } else if (token == "\\bulletLaTeX") {
846 int const index = lex.GetInteger();
848 string temp_str = lex.GetString();
850 while (temp_str != "\\end_bullet") {
851 // this loop structure is needed when user
852 // enters an empty string since the first
853 // thing returned will be the \\end_bullet
855 // if the LaTeX entry has spaces. Each element
856 // therefore needs to be read in turn
859 temp_str = lex.GetString();
861 params.user_defined_bullets[index].setText(sum_str);
862 params.temp_bullets[index].setText(sum_str);
863 } else if (token == "\\secnumdepth") {
865 params.secnumdepth = lex.GetInteger();
866 } else if (token == "\\tocdepth") {
868 params.tocdepth = lex.GetInteger();
869 } else if (token == "\\spacing") {
871 string const tmp = strip(lex.GetString());
872 Spacing::Space tmp_space = Spacing::Default;
874 if (tmp == "single") {
875 tmp_space = Spacing::Single;
876 } else if (tmp == "onehalf") {
877 tmp_space = Spacing::Onehalf;
878 } else if (tmp == "double") {
879 tmp_space = Spacing::Double;
880 } else if (tmp == "other") {
882 tmp_space = Spacing::Other;
883 tmp_val = lex.GetFloat();
885 lex.printError("Unknown spacing token: '$$Token'");
887 // Small hack so that files written with klyx will be
890 par->params().spacing(Spacing(tmp_space, tmp_val));
892 params.spacing.set(tmp_space, tmp_val);
894 } else if (token == "\\paragraph_spacing") {
896 string const tmp = strip(lex.GetString());
897 if (tmp == "single") {
898 par->params().spacing(Spacing(Spacing::Single));
899 } else if (tmp == "onehalf") {
900 par->params().spacing(Spacing(Spacing::Onehalf));
901 } else if (tmp == "double") {
902 par->params().spacing(Spacing(Spacing::Double));
903 } else if (tmp == "other") {
905 par->params().spacing(Spacing(Spacing::Other,
908 lex.printError("Unknown spacing token: '$$Token'");
910 } else if (token == "\\float_placement") {
912 params.float_placement = lex.GetString();
913 } else if (token == "\\family") {
915 font.setLyXFamily(lex.GetString());
916 } else if (token == "\\series") {
918 font.setLyXSeries(lex.GetString());
919 } else if (token == "\\shape") {
921 font.setLyXShape(lex.GetString());
922 } else if (token == "\\size") {
924 font.setLyXSize(lex.GetString());
927 #warning compatability hack needed
929 } else if (token == "\\latex") {
931 string const tok = lex.GetString();
932 // This is dirty, but gone with LyX3. (Asger)
933 if (tok == "no_latex")
934 font.setLatex(LyXFont::OFF);
935 else if (tok == "latex")
936 font.setLatex(LyXFont::ON);
937 else if (tok == "default")
938 font.setLatex(LyXFont::INHERIT);
940 lex.printError("Unknown LaTeX font flag "
943 } else if (token == "\\latex") {
945 string const tok = lex.GetString();
946 if (tok == "no_latex") {
948 insertErtContents(par, pos, font);
949 } else if (tok == "latex") {
950 ert_comp.active = true;
951 } else if (tok == "default") {
953 insertErtContents(par, pos, font);
955 lex.printError("Unknown LaTeX font flag "
959 } else if (token == "\\lang") {
961 string const tok = lex.GetString();
962 Language const * lang = languages.getLanguage(tok);
964 font.setLanguage(lang);
966 font.setLanguage(params.language);
967 lex.printError("Unknown language `$$Token'");
969 } else if (token == "\\numeric") {
971 font.setNumber(font.setLyXMisc(lex.GetString()));
972 } else if (token == "\\emph") {
974 font.setEmph(font.setLyXMisc(lex.GetString()));
975 } else if (token == "\\bar") {
977 string const tok = lex.GetString();
978 // This is dirty, but gone with LyX3. (Asger)
980 font.setUnderbar(LyXFont::ON);
981 else if (tok == "no")
982 font.setUnderbar(LyXFont::OFF);
983 else if (tok == "default")
984 font.setUnderbar(LyXFont::INHERIT);
986 lex.printError("Unknown bar font flag "
988 } else if (token == "\\noun") {
990 font.setNoun(font.setLyXMisc(lex.GetString()));
991 } else if (token == "\\color") {
993 font.setLyXColor(lex.GetString());
994 } else if (token == "\\align") {
995 int tmpret = lex.FindToken(string_align);
996 if (tmpret == -1) ++tmpret;
997 if (tmpret != LYX_LAYOUT_DEFAULT) { // tmpret != 99 ???
998 int const tmpret2 = int(pow(2.0, tmpret));
999 //lyxerr << "Tmpret2 = " << tmpret2 << endl;
1000 par->params().align(LyXAlignment(tmpret2));
1002 } else if (token == "\\added_space_top") {
1004 par->params().spaceTop(VSpace(lex.GetString()));
1005 } else if (token == "\\added_space_bottom") {
1007 par->params().spaceBottom(VSpace(lex.GetString()));
1008 #ifndef NO_PEXTRA_REALLY
1009 } else if (token == "\\pextra_type") {
1011 par->params().pextraType(lex.GetInteger());
1012 } else if (token == "\\pextra_width") {
1014 par->params().pextraWidth(lex.GetString());
1015 } else if (token == "\\pextra_widthp") {
1017 par->params().pextraWidthp(lex.GetString());
1018 } else if (token == "\\pextra_alignment") {
1020 par->params().pextraAlignment(lex.GetInteger());
1021 } else if (token == "\\pextra_hfill") {
1023 par->params().pextraHfill(lex.GetInteger());
1024 } else if (token == "\\pextra_start_minipage") {
1026 par->params().pextraStartMinipage(lex.GetInteger());
1028 } else if (token == "\\labelwidthstring") {
1030 par->params().labelWidthString(lex.GetString());
1031 // do not delete this token, it is still needed!
1032 } else if (token == "\\end_inset") {
1033 lyxerr << "Solitary \\end_inset. Missing \\begin_inset?.\n"
1034 << "Last inset read was: " << last_inset_read
1036 // Simply ignore this. The insets do not have
1038 // But insets should read it, it is a part of
1039 // the inset isn't it? Lgb.
1040 } else if (token == "\\begin_inset") {
1042 insertErtContents(par, pos, font, false);
1043 ert_stack.push(ert_comp);
1044 ert_comp = ErtComp();
1046 readInset(lex, par, pos, font);
1048 ert_comp = ert_stack.top();
1051 } else if (token == "\\SpecialChar") {
1052 LyXLayout const & layout =
1053 textclasslist.Style(params.textclass,
1056 // Insets don't make sense in a free-spacing context! ---Kayvan
1057 if (layout.free_spacing) {
1060 string next_token = lex.GetString();
1061 if (next_token == "\\-") {
1062 par->insertChar(pos, '-', font);
1063 } else if (next_token == "\\protected_separator"
1064 || next_token == "~") {
1065 par->insertChar(pos, ' ', font);
1067 lex.printError("Token `$$Token' "
1069 "paragraph layout!");
1074 Inset * inset = new InsetSpecialChar;
1075 inset->read(this, lex);
1076 par->insertInset(pos, inset, font);
1079 } else if (token == "\\newline") {
1082 if (!ert_comp.in_tabular && ert_comp.active) {
1083 ert_comp.contents += char(Paragraph::META_NEWLINE);
1085 // Since we cannot know it this is only a regular
1086 // newline or a tabular cell delimter we have to
1087 // handle the ERT here.
1088 insertErtContents(par, pos, font, false);
1090 par->insertChar(pos, Paragraph::META_NEWLINE, font);
1094 par->insertChar(pos, Paragraph::META_NEWLINE, font);
1097 } else if (token == "\\LyXTable") {
1099 ert_comp.in_tabular = true;
1101 Inset * inset = new InsetTabular(*this);
1102 inset->read(this, lex);
1103 par->insertInset(pos, inset, font);
1105 // because of OLD_TABULAR_READ where tabulars have been
1107 checkminipage = true;
1108 } else if (token == "\\hfill") {
1109 par->insertChar(pos, Paragraph::META_HFILL, font);
1111 } else if (token == "\\protected_separator") { // obsolete
1112 // This is a backward compability thingie. (Lgb)
1113 // Remove it later some time...introduced with fileformat
1115 LyXLayout const & layout =
1116 textclasslist.Style(params.textclass,
1119 if (layout.free_spacing) {
1120 par->insertChar(pos, ' ', font);
1122 Inset * inset = new InsetSpecialChar(InsetSpecialChar::PROTECTED_SEPARATOR);
1123 par->insertInset(pos, inset, font);
1126 } else if (token == "\\bibitem") { // ale970302
1128 InsetCommandParams p("bibitem", "dummy");
1129 par->bibkey = new InsetBibKey(p);
1131 par->bibkey->read(this, lex);
1132 } else if (token == "\\backslash") {
1134 if (ert_comp.active) {
1135 ert_comp.contents += "\\";
1138 par->insertChar(pos, '\\', font);
1143 } else if (token == "\\the_end") {
1145 // If we still have some ert active here we have to insert
1146 // it so we don't loose it. (Lgb)
1147 insertErtContents(par, pos, font);
1149 the_end_read = true;
1150 minipar = parBeforeMinipage = 0;
1153 if (ert_comp.active) {
1154 ert_comp.contents += token;
1157 // This should be insurance for the future: (Asger)
1158 lex.printError("Unknown token `$$Token'. "
1159 "Inserting as text.");
1160 string::const_iterator cit = token.begin();
1161 string::const_iterator end = token.end();
1162 for (; cit != end; ++cit) {
1163 par->insertChar(pos, (*cit), font);
1170 #ifndef NO_PEXTRA_REALLY
1171 // now check if we have a minipage paragraph as at this
1172 // point we already read all the necessary data!
1173 // this cannot be done in layout because there we did
1174 // not read yet the paragraph PEXTRA-params (Jug)
1176 // BEGIN pextra_minipage compability
1177 // This should be removed in 1.3.x (Lgb)
1179 // This compability code is not perfect. In a couple
1180 // of rand cases it fails. When the minipage par is
1181 // the first par in the document, and when there are
1182 // none or only one regular paragraphs after the
1183 // minipage. Currently I am not investing any effort
1184 // in fixing those cases.
1186 //lyxerr << "Call depth: " << call_depth << endl;
1187 if (checkminipage && (call_depth == 1)) {
1188 checkminipage = false;
1189 if (minipar && (minipar != par) &&
1190 (par->params().pextraType()==Paragraph::PEXTRA_MINIPAGE))
1192 lyxerr << "minipages in a row" << endl;
1193 if (par->params().pextraStartMinipage()) {
1194 lyxerr << "start new minipage" << endl;
1195 // minipages in a row
1196 par->previous()->next(0);
1199 Paragraph * tmp = minipar;
1201 tmp->params().pextraType(0);
1202 tmp->params().pextraWidth(string());
1203 tmp->params().pextraWidthp(string());
1204 tmp->params().pextraAlignment(0);
1205 tmp->params().pextraHfill(false);
1206 tmp->params().pextraStartMinipage(false);
1209 // create a new paragraph to insert the
1210 // minipages in the following case
1211 if (par->params().pextraStartMinipage() &&
1212 !par->params().pextraHfill())
1214 Paragraph * p = new Paragraph;
1216 p->previous(parBeforeMinipage);
1217 parBeforeMinipage->next(p);
1219 p->params().depth(parBeforeMinipage->params().depth());
1220 parBeforeMinipage = p;
1222 InsetMinipage * mini = new InsetMinipage;
1223 mini->pos(static_cast<InsetMinipage::Position>(par->params().pextraAlignment()));
1224 mini->width(par->params().pextraWidth());
1225 if (!par->params().pextraWidthp().empty()) {
1226 lyxerr << "WP:" << mini->width() << endl;
1227 mini->width(tostr(par->params().pextraWidthp())+"%");
1229 mini->inset.paragraph(par);
1230 // Insert the minipage last in the
1231 // previous paragraph.
1232 if (par->params().pextraHfill()) {
1233 parBeforeMinipage->insertChar
1234 (parBeforeMinipage->size(), Paragraph::META_HFILL);
1236 parBeforeMinipage->insertInset
1237 (parBeforeMinipage->size(), mini);
1241 lyxerr << "new minipage par" << endl;
1242 //nothing to do just continue reading
1245 } else if (minipar && (minipar != par)) {
1246 lyxerr << "last minipage par read" << endl;
1247 // The last paragraph read was not part of a
1248 // minipage but the par linked list is...
1249 // So we need to remove the last par from the
1251 if (par->previous())
1252 par->previous()->next(0);
1253 par->previous(parBeforeMinipage);
1254 parBeforeMinipage->next(par);
1255 Paragraph * tmp = minipar;
1257 tmp->params().pextraType(0);
1258 tmp->params().pextraWidth(string());
1259 tmp->params().pextraWidthp(string());
1260 tmp->params().pextraAlignment(0);
1261 tmp->params().pextraHfill(false);
1262 tmp->params().pextraStartMinipage(false);
1265 depth = parBeforeMinipage->params().depth();
1266 minipar = parBeforeMinipage = 0;
1267 } else if (!minipar &&
1268 (par->params().pextraType() == Paragraph::PEXTRA_MINIPAGE))
1270 // par is the first paragraph in a minipage
1271 lyxerr << "begin minipage" << endl;
1272 // To minimize problems for
1273 // the users we will insert
1274 // the first minipage in
1275 // a sequence of minipages
1276 // in its own paragraph.
1277 Paragraph * p = new Paragraph;
1279 p->previous(par->previous());
1281 p->params().depth(depth);
1282 par->params().depth(0);
1284 if (par->previous())
1285 par->previous()->next(p);
1287 parBeforeMinipage = p;
1289 if (!first_par || (first_par == par))
1292 InsetMinipage * mini = new InsetMinipage;
1293 mini->pos(static_cast<InsetMinipage::Position>(minipar->params().pextraAlignment()));
1294 mini->width(minipar->params().pextraWidth());
1295 if (!par->params().pextraWidthp().empty()) {
1296 lyxerr << "WP:" << mini->width() << endl;
1297 mini->width(tostr(par->params().pextraWidthp())+"%");
1299 mini->inset.paragraph(minipar);
1301 // Insert the minipage last in the
1302 // previous paragraph.
1303 if (minipar->params().pextraHfill()) {
1304 parBeforeMinipage->insertChar
1305 (parBeforeMinipage->size(),Paragraph::META_HFILL);
1307 parBeforeMinipage->insertInset
1308 (parBeforeMinipage->size(), mini);
1311 // End of pextra_minipage compability
1314 return the_end_read;
1318 void Buffer::readInset(LyXLex & lex, Paragraph *& par,
1319 int & pos, LyXFont & font)
1321 // consistency check
1322 if (lex.GetString() != "\\begin_inset") {
1323 lyxerr << "Buffer::readInset: Consistency check failed."
1330 string const tmptok = lex.GetString();
1331 last_inset_read = tmptok;
1333 // test the different insets
1334 if (tmptok == "LatexCommand") {
1335 InsetCommandParams inscmd;
1338 string const cmdName = inscmd.getCmdName();
1340 // This strange command allows LyX to recognize "natbib" style
1341 // citations: citet, citep, Citet etc.
1342 if (compare_no_case(cmdName, "cite", 4) == 0) {
1343 inset = new InsetCitation(inscmd);
1344 } else if (cmdName == "bibitem") {
1345 lex.printError("Wrong place for bibitem");
1346 inset = new InsetBibKey(inscmd);
1347 } else if (cmdName == "BibTeX") {
1348 inset = new InsetBibtex(inscmd);
1349 } else if (cmdName == "index") {
1350 inset = new InsetIndex(inscmd);
1351 } else if (cmdName == "include") {
1352 inset = new InsetInclude(inscmd, *this);
1353 } else if (cmdName == "label") {
1354 inset = new InsetLabel(inscmd);
1355 } else if (cmdName == "url"
1356 || cmdName == "htmlurl") {
1357 inset = new InsetUrl(inscmd);
1358 } else if (cmdName == "ref"
1359 || cmdName == "pageref"
1360 || cmdName == "vref"
1361 || cmdName == "vpageref"
1362 || cmdName == "prettyref") {
1363 if (!inscmd.getOptions().empty()
1364 || !inscmd.getContents().empty()) {
1365 inset = new InsetRef(inscmd, *this);
1367 } else if (cmdName == "tableofcontents") {
1368 inset = new InsetTOC(inscmd);
1369 } else if (cmdName == "listofalgorithms") {
1370 inset = new InsetFloatList("algorithm");
1371 } else if (cmdName == "listoffigures") {
1372 inset = new InsetFloatList("figure");
1373 } else if (cmdName == "listoftables") {
1374 inset = new InsetFloatList("table");
1375 } else if (cmdName == "printindex") {
1376 inset = new InsetPrintIndex(inscmd);
1377 } else if (cmdName == "lyxparent") {
1378 inset = new InsetParent(inscmd, *this);
1381 if (tmptok == "Quotes") {
1382 inset = new InsetQuotes;
1383 } else if (tmptok == "External") {
1384 inset = new InsetExternal;
1385 } else if (tmptok == "FormulaMacro") {
1386 inset = new InsetFormulaMacro;
1387 } else if (tmptok == "Formula") {
1388 inset = new InsetFormula;
1389 } else if (tmptok == "Figure") {
1390 inset = new InsetFig(100, 100, *this);
1391 } else if (tmptok == "Info") {
1392 inset = new InsetInfo;
1393 } else if (tmptok == "Include") {
1394 InsetCommandParams p( "Include" );
1395 inset = new InsetInclude(p, *this);
1396 } else if (tmptok == "ERT") {
1397 inset = new InsetERT;
1398 } else if (tmptok == "Tabular") {
1399 inset = new InsetTabular(*this);
1400 } else if (tmptok == "Text") {
1401 inset = new InsetText;
1402 } else if (tmptok == "Foot") {
1403 inset = new InsetFoot;
1404 } else if (tmptok == "Marginal") {
1405 inset = new InsetMarginal;
1406 } else if (tmptok == "Minipage") {
1407 inset = new InsetMinipage;
1408 } else if (tmptok == "Float") {
1410 string tmptok = lex.GetString();
1411 inset = new InsetFloat(tmptok);
1412 } else if (tmptok == "List") {
1413 inset = new InsetList;
1414 } else if (tmptok == "Theorem") {
1415 inset = new InsetList;
1416 } else if (tmptok == "Caption") {
1417 inset = new InsetCaption;
1418 } else if (tmptok == "GRAPHICS") {
1419 inset = new InsetGraphics;
1420 } else if (tmptok == "FloatList") {
1421 inset = new InsetFloatList;
1424 if (inset) inset->read(this, lex);
1428 par->insertInset(pos, inset, font);
1434 bool Buffer::readFile(LyXLex & lex, Paragraph * par)
1438 string const token(lex.GetString());
1439 if (token == "\\lyxformat") { // the first token _must_ be...
1441 string tmp_format = lex.GetString();
1442 //lyxerr << "LyX Format: `" << tmp_format << "'" << endl;
1443 // if present remove ".," from string.
1444 string::size_type dot = tmp_format.find_first_of(".,");
1445 //lyxerr << " dot found at " << dot << endl;
1446 if (dot != string::npos)
1447 tmp_format.erase(dot, 1);
1448 file_format = strToInt(tmp_format);
1449 if (file_format == LYX_FORMAT) {
1451 } else if (file_format > LYX_FORMAT) {
1453 WriteAlert(_("Warning!"),
1454 _("LyX file format is newer that what"),
1455 _("is supported in this LyX version. Expect some problems."));
1457 } else if (file_format < LYX_FORMAT) {
1459 if (file_format < 200) {
1460 WriteAlert(_("ERROR!"),
1461 _("Old LyX file format found. "
1462 "Use LyX 0.10.x to read this!"));
1466 bool the_end = readLyXformat2(lex, par);
1468 // the_end was added in 213
1469 if (file_format < 213)
1473 WriteAlert(_("Warning!"),
1474 _("Reading of document is not complete"),
1475 _("Maybe the document is truncated"));
1477 } else { // "\\lyxformat" not found
1478 WriteAlert(_("ERROR!"), _("Not a LyX file!"));
1481 WriteAlert(_("ERROR!"), _("Unable to read file!"));
1486 // Should probably be moved to somewhere else: BufferView? LyXView?
1487 bool Buffer::save() const
1489 // We don't need autosaves in the immediate future. (Asger)
1490 resetAutosaveTimers();
1494 if (lyxrc.make_backup) {
1495 s = fileName() + '~';
1496 if (!lyxrc.backupdir_path.empty())
1497 s = AddName(lyxrc.backupdir_path,
1498 subst(os::slashify_path(s),'/','!'));
1500 // Rename is the wrong way of making a backup,
1501 // this is the correct way.
1502 /* truss cp fil fil2:
1503 lstat("LyXVC3.lyx", 0xEFFFF898) Err#2 ENOENT
1504 stat("LyXVC.lyx", 0xEFFFF688) = 0
1505 open("LyXVC.lyx", O_RDONLY) = 3
1506 open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
1507 fstat(4, 0xEFFFF508) = 0
1508 fstat(3, 0xEFFFF508) = 0
1509 read(3, " # T h i s f i l e w".., 8192) = 5579
1510 write(4, " # T h i s f i l e w".., 5579) = 5579
1511 read(3, 0xEFFFD4A0, 8192) = 0
1514 chmod("LyXVC3.lyx", 0100644) = 0
1515 lseek(0, 0, SEEK_CUR) = 46440
1519 // Should probably have some more error checking here.
1520 // Should be cleaned up in 0.13, at least a bit.
1521 // Doing it this way, also makes the inodes stay the same.
1522 // This is still not a very good solution, in particular we
1523 // might loose the owner of the backup.
1524 FileInfo finfo(fileName());
1525 if (finfo.exist()) {
1526 mode_t fmode = finfo.getMode();
1527 struct utimbuf times = {
1528 finfo.getAccessTime(),
1529 finfo.getModificationTime() };
1531 ifstream ifs(fileName().c_str());
1532 ofstream ofs(s.c_str(), ios::out|ios::trunc);
1537 ::chmod(s.c_str(), fmode);
1539 if (::utime(s.c_str(), ×)) {
1540 lyxerr << "utime error." << endl;
1543 lyxerr << "LyX was not able to make "
1544 "backup copy. Beware." << endl;
1549 if (writeFile(fileName(), false)) {
1551 removeAutosaveFile(fileName());
1553 // Saving failed, so backup is not backup
1554 if (lyxrc.make_backup) {
1555 lyx::rename(s, fileName());
1563 // Returns false if unsuccesful
1564 bool Buffer::writeFile(string const & fname, bool flag) const
1566 // if flag is false writeFile will not create any GUI
1567 // warnings, only cerr.
1568 // Needed for autosave in background or panic save (Matthias 120496)
1570 if (read_only && (fname == filename)) {
1571 // Here we should come with a question if we should
1572 // perform the write anyway.
1574 lyxerr << _("Error! Document is read-only: ")
1577 WriteAlert(_("Error! Document is read-only: "),
1582 FileInfo finfo(fname);
1583 if (finfo.exist() && !finfo.writable()) {
1584 // Here we should come with a question if we should
1585 // try to do the save anyway. (i.e. do a chmod first)
1587 lyxerr << _("Error! Cannot write file: ")
1590 WriteFSAlert(_("Error! Cannot write file: "),
1595 ofstream ofs(fname.c_str());
1598 lyxerr << _("Error! Cannot open file: ")
1601 WriteFSAlert(_("Error! Cannot open file: "),
1607 // Use the standard "C" locale for file output.
1608 ofs.imbue(std::locale::classic());
1611 // The top of the file should not be written by params.
1613 // write out a comment in the top of the file
1614 ofs << '#' << LYX_DOCVERSION
1615 << " created this file. For more info see http://www.lyx.org/\n"
1616 << "\\lyxformat " << LYX_FORMAT << "\n";
1618 // now write out the buffer paramters.
1619 params.writeFile(ofs);
1621 Paragraph::depth_type depth = 0;
1623 // this will write out all the paragraphs
1624 // using recursive descent.
1625 paragraph->writeFile(this, ofs, params, depth);
1627 // Write marker that shows file is complete
1628 ofs << "\n\\the_end" << endl;
1632 // how to check if close went ok?
1633 // Following is an attempt... (BE 20001011)
1635 // good() returns false if any error occured, including some
1636 // formatting error.
1637 // bad() returns true if something bad happened in the buffer,
1638 // which should include file system full errors.
1645 lyxerr << "Buffer::writeFile: BAD ERROR!" << endl;
1647 lyxerr << "Buffer::writeFile: NOT SO BAD ERROR!"
1657 string const Buffer::asciiParagraph(Paragraph const * par,
1658 unsigned int linelen) const
1660 ostringstream buffer;
1661 Paragraph::depth_type depth = 0;
1663 Paragraph::depth_type ltype_depth = 0;
1664 unsigned int currlinelen = 0;
1665 bool ref_printed = false;
1669 if (!par->previous()) {
1670 // begins or ends a deeper area ?
1671 if (depth != par->params().depth()) {
1672 if (par->params().depth() > depth) {
1673 while (par->params().depth() > depth) {
1677 while (par->params().depth() < depth) {
1683 // First write the layout
1684 string const tmp = textclasslist.NameOfLayout(params.textclass, par->layout);
1685 if (tmp == "Itemize") {
1687 ltype_depth = depth + 1;
1688 } else if (tmp == "Enumerate") {
1690 ltype_depth = depth + 1;
1691 } else if (contains(tmp, "ection")) {
1693 ltype_depth = depth + 1;
1694 } else if (contains(tmp, "aragraph")) {
1696 ltype_depth = depth + 1;
1697 } else if (tmp == "Description") {
1699 ltype_depth = depth + 1;
1700 } else if (tmp == "Abstract") {
1703 } else if (tmp == "Bibliography") {
1711 /* maybe some vertical spaces */
1713 /* the labelwidthstring used in lists */
1717 /* some pagebreaks? */
1721 /* what about the alignment */
1723 lyxerr << "Should this ever happen?" << endl;
1727 LyXFont const font1 = LyXFont(LyXFont::ALL_INHERIT, params.language);
1729 for (Paragraph::size_type i = 0; i < par->size(); ++i) {
1730 if (!i && !noparbreak) {
1733 for (Paragraph::depth_type j = 0; j < depth; ++j)
1735 currlinelen = depth * 2;
1738 case 4: // (Sub)Paragraph
1739 case 5: // Description
1743 buffer << "Abstract\n\n";
1745 buffer << "Abstract: ";
1747 case 7: // Bibliography
1750 buffer << "References\n\n";
1752 buffer << "References: ";
1757 buffer << par->params().labelString() << " ";
1760 if (ltype_depth > depth) {
1761 for (Paragraph::depth_type j = ltype_depth - 1;
1764 currlinelen += (ltype_depth-depth)*2;
1768 LyXFont const font2 = par->getFontSettings(params, i);
1769 if (font1.latex() != font2.latex()) {
1770 if (font2.latex() == LyXFont::OFF)
1779 char c = par->getUChar(params, i);
1783 case Paragraph::META_INSET:
1785 Inset const * inset = par->getInset(i);
1787 if (!inset->ascii(this, buffer)) {
1790 rsplit(buffer.str().c_str(),
1792 currlinelen += s.length();
1794 // to be sure it breaks paragraph
1795 currlinelen += linelen;
1801 case Paragraph::META_NEWLINE:
1804 for (Paragraph::depth_type j = 0;
1808 currlinelen = depth * 2;
1809 if (ltype_depth > depth) {
1810 for (Paragraph::depth_type j = ltype_depth;
1813 currlinelen += (ltype_depth - depth) * 2;
1817 case Paragraph::META_HFILL:
1826 if ((linelen > 0) && (currlinelen > (linelen - 10)) &&
1827 (c == ' ') && ((i + 2) < par->size()))
1830 for (Paragraph::depth_type j = 0;
1833 currlinelen = depth * 2;
1834 if (ltype_depth > depth) {
1835 for (Paragraph::depth_type j = ltype_depth;
1838 currlinelen += (ltype_depth-depth)*2;
1840 } else if (c != '\0')
1843 lyxerr[Debug::INFO] << "writeAsciiFile: NULL char in structure." << endl;
1848 return buffer.str().c_str();
1852 void Buffer::writeFileAscii(string const & fname, int linelen)
1854 ofstream ofs(fname.c_str());
1856 WriteFSAlert(_("Error: Cannot write file:"), fname);
1859 writeFileAscii(ofs, linelen);
1863 void Buffer::writeFileAscii(ostream & ofs, int linelen)
1865 Paragraph * par = paragraph;
1867 ofs << asciiParagraph(par, linelen);
1875 void Buffer::makeLaTeXFile(string const & fname,
1876 string const & original_path,
1877 bool nice, bool only_body)
1879 lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
1881 niceFile = nice; // this will be used by Insetincludes.
1883 tex_code_break_column = lyxrc.ascii_linelen;
1885 LyXTextClass const & tclass =
1886 textclasslist.TextClass(params.textclass);
1888 ofstream ofs(fname.c_str());
1890 WriteFSAlert(_("Error: Cannot open file: "), fname);
1894 // validate the buffer.
1895 lyxerr[Debug::LATEX] << " Validating buffer..." << endl;
1896 LaTeXFeatures features(params, tclass.numLayouts());
1898 lyxerr[Debug::LATEX] << " Buffer validation done." << endl;
1901 // The starting paragraph of the coming rows is the
1902 // first paragraph of the document. (Asger)
1903 texrow.start(paragraph, 0);
1905 if (!only_body && nice) {
1906 ofs << "%% " LYX_DOCVERSION " created this file. "
1907 "For more info, see http://www.lyx.org/.\n"
1908 "%% Do not edit unless you really know what "
1913 lyxerr[Debug::INFO] << "lyx header finished" << endl;
1914 // There are a few differences between nice LaTeX and usual files:
1915 // usual is \batchmode and has a
1916 // special input@path to allow the including of figures
1917 // with either \input or \includegraphics (what figinsets do).
1918 // batchmode is not set if there is a tex_code_break_column.
1919 // In this case somebody is interested in the generated LaTeX,
1920 // so this is OK. input@path is set when the actual parameter
1921 // original_path is set. This is done for usual tex-file, but not
1922 // for nice-latex-file. (Matthias 250696)
1925 // code for usual, NOT nice-latex-file
1926 ofs << "\\batchmode\n"; // changed
1927 // from \nonstopmode
1930 if (!original_path.empty()) {
1931 ofs << "\\makeatletter\n"
1932 << "\\def\\input@path{{"
1933 << os::external_path(original_path) << "/}}\n"
1934 << "\\makeatother\n";
1940 ofs << "\\documentclass";
1942 ostringstream options; // the document class options.
1944 if (tokenPos(tclass.opt_fontsize(),
1945 '|', params.fontsize) >= 0) {
1946 // only write if existing in list (and not default)
1947 options << params.fontsize << "pt,";
1951 if (!params.use_geometry &&
1952 (params.paperpackage == BufferParams::PACKAGE_NONE)) {
1953 switch (params.papersize) {
1954 case BufferParams::PAPER_A4PAPER:
1955 options << "a4paper,";
1957 case BufferParams::PAPER_USLETTER:
1958 options << "letterpaper,";
1960 case BufferParams::PAPER_A5PAPER:
1961 options << "a5paper,";
1963 case BufferParams::PAPER_B5PAPER:
1964 options << "b5paper,";
1966 case BufferParams::PAPER_EXECUTIVEPAPER:
1967 options << "executivepaper,";
1969 case BufferParams::PAPER_LEGALPAPER:
1970 options << "legalpaper,";
1976 if (params.sides != tclass.sides()) {
1977 switch (params.sides) {
1978 case LyXTextClass::OneSide:
1979 options << "oneside,";
1981 case LyXTextClass::TwoSides:
1982 options << "twoside,";
1988 if (params.columns != tclass.columns()) {
1989 if (params.columns == 2)
1990 options << "twocolumn,";
1992 options << "onecolumn,";
1995 if (!params.use_geometry
1996 && params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
1997 options << "landscape,";
1999 // language should be a parameter to \documentclass
2001 ostringstream language_options;
2002 if (params.language->babel() == "hebrew"
2003 && default_language->babel() != "hebrew")
2004 // This seems necessary
2005 features.UsedLanguages.insert(default_language);
2007 if (lyxrc.language_use_babel ||
2008 params.language->lang() != lyxrc.default_language ||
2009 !features.UsedLanguages.empty()) {
2011 for (LaTeXFeatures::LanguageList::const_iterator cit =
2012 features.UsedLanguages.begin();
2013 cit != features.UsedLanguages.end(); ++cit)
2014 language_options << (*cit)->babel() << ',';
2015 language_options << params.language->babel();
2016 if (lyxrc.language_global_options)
2017 options << language_options.str() << ',';
2020 // the user-defined options
2021 if (!params.options.empty()) {
2022 options << params.options << ',';
2025 string strOptions(options.str().c_str());
2026 if (!strOptions.empty()){
2027 strOptions = strip(strOptions, ',');
2028 ofs << '[' << strOptions << ']';
2032 << textclasslist.LatexnameOfClass(params.textclass)
2035 // end of \documentclass defs
2037 // font selection must be done before loading fontenc.sty
2038 // The ae package is not needed when using OT1 font encoding.
2039 if (params.fonts != "default" &&
2040 (params.fonts != "ae" || lyxrc.fontenc != "default")) {
2041 ofs << "\\usepackage{" << params.fonts << "}\n";
2043 if (params.fonts == "ae") {
2044 ofs << "\\usepackage{aecompl}\n";
2048 // this one is not per buffer
2049 if (lyxrc.fontenc != "default") {
2050 ofs << "\\usepackage[" << lyxrc.fontenc
2055 if (params.inputenc == "auto") {
2056 string const doc_encoding =
2057 params.language->encoding()->LatexName();
2059 // Create a list with all the input encodings used
2061 set<string> encodings;
2062 for (LaTeXFeatures::LanguageList::const_iterator it =
2063 features.UsedLanguages.begin();
2064 it != features.UsedLanguages.end(); ++it)
2065 if ((*it)->encoding()->LatexName() != doc_encoding)
2066 encodings.insert((*it)->encoding()->LatexName());
2068 ofs << "\\usepackage[";
2069 std::copy(encodings.begin(), encodings.end(),
2070 std::ostream_iterator<string>(ofs, ","));
2071 ofs << doc_encoding << "]{inputenc}\n";
2073 } else if (params.inputenc != "default") {
2074 ofs << "\\usepackage[" << params.inputenc
2079 // At the very beginning the text parameters.
2080 if (params.paperpackage != BufferParams::PACKAGE_NONE) {
2081 switch (params.paperpackage) {
2082 case BufferParams::PACKAGE_A4:
2083 ofs << "\\usepackage{a4}\n";
2086 case BufferParams::PACKAGE_A4WIDE:
2087 ofs << "\\usepackage{a4wide}\n";
2090 case BufferParams::PACKAGE_WIDEMARGINSA4:
2091 ofs << "\\usepackage[widemargins]{a4}\n";
2096 if (params.use_geometry) {
2097 ofs << "\\usepackage{geometry}\n";
2099 ofs << "\\geometry{verbose";
2100 if (params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
2101 ofs << ",landscape";
2102 switch (params.papersize2) {
2103 case BufferParams::VM_PAPER_CUSTOM:
2104 if (!params.paperwidth.empty())
2105 ofs << ",paperwidth="
2106 << params.paperwidth;
2107 if (!params.paperheight.empty())
2108 ofs << ",paperheight="
2109 << params.paperheight;
2111 case BufferParams::VM_PAPER_USLETTER:
2112 ofs << ",letterpaper";
2114 case BufferParams::VM_PAPER_USLEGAL:
2115 ofs << ",legalpaper";
2117 case BufferParams::VM_PAPER_USEXECUTIVE:
2118 ofs << ",executivepaper";
2120 case BufferParams::VM_PAPER_A3:
2123 case BufferParams::VM_PAPER_A4:
2126 case BufferParams::VM_PAPER_A5:
2129 case BufferParams::VM_PAPER_B3:
2132 case BufferParams::VM_PAPER_B4:
2135 case BufferParams::VM_PAPER_B5:
2139 // default papersize ie BufferParams::VM_PAPER_DEFAULT
2140 switch (lyxrc.default_papersize) {
2141 case BufferParams::PAPER_DEFAULT: // keep compiler happy
2142 case BufferParams::PAPER_USLETTER:
2143 ofs << ",letterpaper";
2145 case BufferParams::PAPER_LEGALPAPER:
2146 ofs << ",legalpaper";
2148 case BufferParams::PAPER_EXECUTIVEPAPER:
2149 ofs << ",executivepaper";
2151 case BufferParams::PAPER_A3PAPER:
2154 case BufferParams::PAPER_A4PAPER:
2157 case BufferParams::PAPER_A5PAPER:
2160 case BufferParams::PAPER_B5PAPER:
2165 if (!params.topmargin.empty())
2166 ofs << ",tmargin=" << params.topmargin;
2167 if (!params.bottommargin.empty())
2168 ofs << ",bmargin=" << params.bottommargin;
2169 if (!params.leftmargin.empty())
2170 ofs << ",lmargin=" << params.leftmargin;
2171 if (!params.rightmargin.empty())
2172 ofs << ",rmargin=" << params.rightmargin;
2173 if (!params.headheight.empty())
2174 ofs << ",headheight=" << params.headheight;
2175 if (!params.headsep.empty())
2176 ofs << ",headsep=" << params.headsep;
2177 if (!params.footskip.empty())
2178 ofs << ",footskip=" << params.footskip;
2182 if (features.amsstyle
2183 && !tclass.provides(LyXTextClass::amsmath)) {
2184 ofs << "\\usepackage{amsmath}\n";
2188 if (tokenPos(tclass.opt_pagestyle(),
2189 '|', params.pagestyle) >= 0) {
2190 if (params.pagestyle == "fancy") {
2191 ofs << "\\usepackage{fancyhdr}\n";
2194 ofs << "\\pagestyle{" << params.pagestyle << "}\n";
2198 // We try to load babel late, in case it interferes
2199 // with other packages.
2201 string tmp = lyxrc.language_package;
2202 if (!lyxrc.language_global_options
2203 && tmp == "\\usepackage{babel}")
2204 tmp = string("\\usepackage[") +
2205 language_options.str().c_str() +
2211 if (params.secnumdepth != tclass.secnumdepth()) {
2212 ofs << "\\setcounter{secnumdepth}{"
2213 << params.secnumdepth
2217 if (params.tocdepth != tclass.tocdepth()) {
2218 ofs << "\\setcounter{tocdepth}{"
2224 if (params.paragraph_separation) {
2225 switch (params.defskip.kind()) {
2226 case VSpace::SMALLSKIP:
2227 ofs << "\\setlength\\parskip{\\smallskipamount}\n";
2229 case VSpace::MEDSKIP:
2230 ofs << "\\setlength\\parskip{\\medskipamount}\n";
2232 case VSpace::BIGSKIP:
2233 ofs << "\\setlength\\parskip{\\bigskipamount}\n";
2235 case VSpace::LENGTH:
2236 ofs << "\\setlength\\parskip{"
2237 << params.defskip.length().asLatexString()
2240 default: // should never happen // Then delete it.
2241 ofs << "\\setlength\\parskip{\\medskipamount}\n";
2246 ofs << "\\setlength\\parindent{0pt}\n";
2250 // Now insert the LyX specific LaTeX commands...
2252 // The optional packages;
2253 string preamble(features.getPackages());
2255 // this might be useful...
2256 preamble += "\n\\makeatletter\n";
2258 // Some macros LyX will need
2259 string tmppreamble(features.getMacros());
2261 if (!tmppreamble.empty()) {
2262 preamble += "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2263 "LyX specific LaTeX commands.\n"
2264 + tmppreamble + '\n';
2267 // the text class specific preamble
2268 tmppreamble = features.getTClassPreamble();
2269 if (!tmppreamble.empty()) {
2270 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2271 "Textclass specific LaTeX commands.\n"
2272 + tmppreamble + '\n';
2275 /* the user-defined preamble */
2276 if (!params.preamble.empty()) {
2277 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2278 "User specified LaTeX commands.\n"
2279 + params.preamble + '\n';
2282 preamble += "\\makeatother\n";
2284 // Itemize bullet settings need to be last in case the user
2285 // defines their own bullets that use a package included
2286 // in the user-defined preamble -- ARRae
2287 // Actually it has to be done much later than that
2288 // since some packages like frenchb make modifications
2289 // at \begin{document} time -- JMarc
2291 for (int i = 0; i < 4; ++i) {
2292 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
2293 if (bullets_def.empty())
2294 bullets_def="\\AtBeginDocument{\n";
2295 bullets_def += " \\renewcommand{\\labelitemi";
2297 // `i' is one less than the item to modify
2304 bullets_def += "ii";
2310 bullets_def += "}{" +
2311 params.user_defined_bullets[i].getText()
2316 if (!bullets_def.empty())
2317 preamble += bullets_def + "}\n\n";
2319 for (int j = countChar(preamble, '\n'); j-- ;) {
2326 ofs << "\\begin{document}\n";
2329 lyxerr[Debug::INFO] << "preamble finished, now the body." << endl;
2331 if (!lyxrc.language_auto_begin) {
2332 ofs << subst(lyxrc.language_command_begin, "$$lang",
2333 params.language->babel())
2338 latexParagraphs(ofs, paragraph, 0, texrow);
2340 // add this just in case after all the paragraphs
2344 if (!lyxrc.language_auto_end) {
2345 ofs << subst(lyxrc.language_command_end, "$$lang",
2346 params.language->babel())
2352 ofs << "\\end{document}\n";
2355 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
2357 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
2361 // Just to be sure. (Asger)
2364 // tex_code_break_column's value is used to decide
2365 // if we are in batchmode or not (within mathed_write()
2366 // in math_write.C) so we must set it to a non-zero
2367 // value when we leave otherwise we save incorrect .lyx files.
2368 tex_code_break_column = lyxrc.ascii_linelen;
2372 lyxerr << "File was not closed properly." << endl;
2375 lyxerr[Debug::INFO] << "Finished making latex file." << endl;
2380 // LaTeX all paragraphs from par to endpar, if endpar == 0 then to the end
2382 void Buffer::latexParagraphs(ostream & ofs, Paragraph * par,
2383 Paragraph * endpar, TexRow & texrow) const
2385 bool was_title = false;
2386 bool already_title = false;
2389 while (par != endpar) {
2390 LyXLayout const & layout =
2391 textclasslist.Style(params.textclass,
2394 if (layout.intitle) {
2395 if (already_title) {
2396 lyxerr <<"Error in latexParagraphs: You"
2397 " should not mix title layouts"
2398 " with normal ones." << endl;
2401 } else if (was_title && !already_title) {
2402 ofs << "\\maketitle\n";
2404 already_title = true;
2408 if (layout.isEnvironment()) {
2409 par = par->TeXEnvironment(this, params, ofs, texrow);
2411 par = par->TeXOnePar(this, params, ofs, texrow, false);
2414 // It might be that we only have a title in this document
2415 if (was_title && !already_title) {
2416 ofs << "\\maketitle\n";
2422 bool Buffer::isLatex() const
2424 return textclasslist.TextClass(params.textclass).outputType() == LATEX;
2428 bool Buffer::isLinuxDoc() const
2430 return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC;
2434 bool Buffer::isLiterate() const
2436 return textclasslist.TextClass(params.textclass).outputType() == LITERATE;
2440 bool Buffer::isDocBook() const
2442 return textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2446 bool Buffer::isSGML() const
2448 return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC ||
2449 textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2453 void Buffer::sgmlOpenTag(ostream & os, Paragraph::depth_type depth,
2454 string const & latexname) const
2456 if (!latexname.empty() && latexname != "!-- --")
2457 os << "<!-- " << depth << " -->" << "<" << latexname << ">";
2458 //os << string(depth, ' ') << "<" << latexname << ">\n";
2462 void Buffer::sgmlCloseTag(ostream & os, Paragraph::depth_type depth,
2463 string const & latexname) const
2465 if (!latexname.empty() && latexname != "!-- --")
2466 os << "<!-- " << depth << " -->" << "</" << latexname << ">\n";
2467 //os << string(depth, ' ') << "</" << latexname << ">\n";
2471 void Buffer::makeLinuxDocFile(string const & fname, bool nice, bool body_only)
2473 ofstream ofs(fname.c_str());
2476 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2480 niceFile = nice; // this will be used by included files.
2482 LyXTextClass const & tclass =
2483 textclasslist.TextClass(params.textclass);
2485 LaTeXFeatures features(params, tclass.numLayouts());
2490 string top_element = textclasslist.LatexnameOfClass(params.textclass);
2493 string sgml_includedfiles=features.getIncludedFiles(fname);
2495 if (params.preamble.empty() && sgml_includedfiles.empty()) {
2496 ofs << "<!doctype linuxdoc system>\n\n";
2498 ofs << "<!doctype linuxdoc system [ "
2499 << params.preamble << sgml_includedfiles << " \n]>\n\n";
2502 if (params.options.empty())
2503 sgmlOpenTag(ofs, 0, top_element);
2505 string top = top_element;
2507 top += params.options;
2508 sgmlOpenTag(ofs, 0, top);
2512 ofs << "<!-- " << LYX_DOCVERSION
2513 << " created this file. For more info see http://www.lyx.org/"
2516 Paragraph::depth_type depth = 0; // paragraph depth
2517 Paragraph * par = paragraph;
2519 vector<string> environment_stack(5);
2522 LyXLayout const & style =
2523 textclasslist.Style(params.textclass,
2526 // treat <toc> as a special case for compatibility with old code
2527 if (par->getChar(0) == Paragraph::META_INSET) {
2528 Inset * inset = par->getInset(0);
2529 Inset::Code lyx_code = inset->lyxCode();
2530 if (lyx_code == Inset::TOC_CODE){
2531 string const temp = "toc";
2532 sgmlOpenTag(ofs, depth, temp);
2539 // environment tag closing
2540 for (; depth > par->params().depth(); --depth) {
2541 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2542 environment_stack[depth].erase();
2545 // write opening SGML tags
2546 switch (style.latextype) {
2547 case LATEX_PARAGRAPH:
2548 if (depth == par->params().depth()
2549 && !environment_stack[depth].empty()) {
2550 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2551 environment_stack[depth].erase();
2557 sgmlOpenTag(ofs, depth, style.latexname());
2562 linuxDocError(par, 0,
2563 _("Error : Wrong depth for"
2564 " LatexType Command.\n"));
2566 if (!environment_stack[depth].empty()){
2567 sgmlCloseTag(ofs, depth,
2568 environment_stack[depth]);
2572 environment_stack[depth].erase();
2573 sgmlOpenTag(ofs, depth, style.latexname());
2576 case LATEX_ENVIRONMENT:
2577 case LATEX_ITEM_ENVIRONMENT:
2578 if (depth == par->params().depth()
2579 && environment_stack[depth] != style.latexname()) {
2580 sgmlCloseTag(ofs, depth,
2581 environment_stack[depth]);
2582 environment_stack[depth].erase();
2584 if (depth < par->params().depth()) {
2585 depth = par->params().depth();
2586 environment_stack[depth].erase();
2588 if (environment_stack[depth] != style.latexname()) {
2590 sgmlOpenTag(ofs, depth, "p");
2592 sgmlOpenTag(ofs, depth, style.latexname());
2594 if (environment_stack.size() == depth + 1)
2595 environment_stack.push_back("!-- --");
2596 environment_stack[depth] = style.latexname();
2599 if (style.latexparam() == "CDATA")
2602 if (style.latextype == LATEX_ENVIRONMENT) break;
2604 if (style.labeltype == LABEL_MANUAL)
2609 sgmlOpenTag(ofs, depth + 1, item_name);
2612 sgmlOpenTag(ofs, depth, style.latexname());
2616 simpleLinuxDocOnePar(ofs, par, depth);
2621 // write closing SGML tags
2622 switch (style.latextype) {
2625 case LATEX_ENVIRONMENT:
2626 case LATEX_ITEM_ENVIRONMENT:
2627 if (style.latexparam() == "CDATA")
2631 sgmlCloseTag(ofs, depth, style.latexname());
2637 for (int i=depth; i >= 0; --i)
2638 sgmlCloseTag(ofs, depth, environment_stack[i]);
2642 sgmlCloseTag(ofs, 0, top_element);
2646 // How to check for successful close
2650 void Buffer::docBookHandleCaption(ostream & os, string & inner_tag,
2651 Paragraph::depth_type depth, int desc_on,
2654 Paragraph * tpar = par;
2656 && (tpar->layout != textclasslist.NumberOfLayout(params.textclass,
2658 tpar = tpar->next();
2661 tpar->layout == textclasslist.NumberOfLayout(params.textclass,
2662 "Caption").second) {
2663 sgmlOpenTag(os, depth + 1, inner_tag);
2665 simpleDocBookOnePar(os, extra_par, tpar,
2666 desc_on, depth + 2);
2667 sgmlCloseTag(os, depth+1, inner_tag);
2668 if (!extra_par.empty())
2674 // checks, if newcol chars should be put into this line
2675 // writes newline, if necessary.
2678 void linux_doc_line_break(ostream & os, string::size_type & colcount,
2679 string::size_type newcol)
2682 if (colcount > lyxrc.ascii_linelen) {
2684 colcount = newcol; // assume write after this call
2699 string tag_name(PAR_TAG const & pt) {
2701 case NONE: return "!-- --";
2702 case TT: return "tt";
2703 case SF: return "sf";
2704 case BF: return "bf";
2705 case IT: return "it";
2706 case SL: return "sl";
2707 case EM: return "em";
2714 void operator|=(PAR_TAG & p1, PAR_TAG const & p2)
2716 p1 = static_cast<PAR_TAG>(p1 | p2);
2721 void reset(PAR_TAG & p1, PAR_TAG const & p2)
2723 p1 = static_cast<PAR_TAG>( p1 & ~p2);
2731 // Handle internal paragraph parsing -- layout already processed.
2732 void Buffer::simpleLinuxDocOnePar(ostream & os,
2734 Paragraph::depth_type /*depth*/)
2736 LyXLayout const & style = textclasslist.Style(params.textclass,
2738 string::size_type char_line_count = 5; // Heuristic choice ;-)
2740 // gets paragraph main font
2743 if (style.labeltype == LABEL_MANUAL) {
2744 font_old = style.labelfont;
2747 font_old = style.font;
2751 LyXFont::FONT_FAMILY family_type = LyXFont::ROMAN_FAMILY;
2752 LyXFont::FONT_SERIES series_type = LyXFont::MEDIUM_SERIES;
2753 LyXFont::FONT_SHAPE shape_type = LyXFont::UP_SHAPE;
2756 stack < PAR_TAG > tag_state;
2757 // parsing main loop
2758 for (Paragraph::size_type i = 0; i < par->size(); ++i) {
2760 PAR_TAG tag_close = NONE;
2761 list < PAR_TAG > tag_open;
2763 LyXFont const font = par->getFont(params, i);
2765 if (font_old.family() != font.family()) {
2766 switch (family_type) {
2767 case LyXFont::SANS_FAMILY:
2770 case LyXFont::TYPEWRITER_FAMILY:
2777 family_type = font.family();
2779 switch (family_type) {
2780 case LyXFont::SANS_FAMILY:
2781 tag_open.push_back(SF);
2783 case LyXFont::TYPEWRITER_FAMILY:
2784 tag_open.push_back(TT);
2791 if (font_old.series() != font.series()) {
2792 switch (series_type) {
2793 case LyXFont::BOLD_SERIES:
2800 series_type = font.series();
2802 switch (series_type) {
2803 case LyXFont::BOLD_SERIES:
2804 tag_open.push_back(BF);
2812 if (font_old.shape() != font.shape()) {
2813 switch (shape_type) {
2814 case LyXFont::ITALIC_SHAPE:
2817 case LyXFont::SLANTED_SHAPE:
2824 shape_type = font.shape();
2826 switch (shape_type) {
2827 case LyXFont::ITALIC_SHAPE:
2828 tag_open.push_back(IT);
2830 case LyXFont::SLANTED_SHAPE:
2831 tag_open.push_back(SL);
2838 if (font_old.emph() != font.emph()) {
2839 if (font.emph() == LyXFont::ON) {
2840 tag_open.push_back(EM);
2849 list < PAR_TAG > temp;
2850 while(!tag_state.empty() && tag_close ) {
2851 PAR_TAG k = tag_state.top();
2853 os << "</" << tag_name(k) << ">";
2860 for(list< PAR_TAG >::const_iterator j = temp.begin();
2861 j != temp.end(); ++j) {
2863 os << "<" << tag_name(*j) << ">";
2866 for(list< PAR_TAG >::const_iterator j = tag_open.begin();
2867 j != tag_open.end(); ++j) {
2869 os << "<" << tag_name(*j) << ">";
2872 char c = par->getChar(i);
2874 if (c == Paragraph::META_INSET) {
2875 Inset * inset = par->getInset(i);
2876 inset->linuxdoc(this, os);
2883 font.latex() == LyXFont::ON ||
2885 style.latexparam() == "CDATA") {
2886 // "TeX"-Mode on == > SGML-Mode on.
2892 if (par->linuxDocConvertChar(c, sgml_string)
2893 && !style.free_spacing) {
2894 // in freespacing mode, spaces are
2895 // non-breaking characters
2896 if (desc_on) {// if char is ' ' then...
2899 linux_doc_line_break(os, char_line_count, 6);
2903 linux_doc_line_break(os, char_line_count, 1);
2908 char_line_count += sgml_string.length();
2914 while (!tag_state.empty()) {
2915 os << "</" << tag_name(tag_state.top()) << ">";
2919 // resets description flag correctly
2921 // <tag> not closed...
2922 linux_doc_line_break(os, char_line_count, 6);
2928 // Print an error message.
2929 void Buffer::linuxDocError(Paragraph * par, int pos,
2930 string const & message)
2932 // insert an error marker in text
2933 InsetError * new_inset = new InsetError(message);
2934 par->insertInset(pos, new_inset);
2938 void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
2940 ofstream ofs(fname.c_str());
2942 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2946 Paragraph * par = paragraph;
2948 niceFile = nice; // this will be used by Insetincludes.
2950 LyXTextClass const & tclass =
2951 textclasslist.TextClass(params.textclass);
2953 LaTeXFeatures features(params, tclass.numLayouts());
2958 string top_element = textclasslist.LatexnameOfClass(params.textclass);
2961 string sgml_includedfiles = features.getIncludedFiles(fname);
2963 ofs << "<!doctype " << top_element
2964 << " public \"-//OASIS//DTD DocBook V3.1//EN\"";
2966 if (params.preamble.empty() && sgml_includedfiles.empty())
2969 ofs << "\n [ " << params.preamble
2970 << sgml_includedfiles << " \n]>\n\n";
2973 string top = top_element;
2975 top += params.language->code();
2978 if (!params.options.empty()) {
2980 top += params.options;
2982 sgmlOpenTag(ofs, 0, top);
2984 ofs << "<!-- DocBook file was created by " << LYX_DOCVERSION
2985 << "\n See http://www.lyx.org/ for more information -->\n";
2987 vector<string> environment_stack(10);
2988 vector<string> environment_inner(10);
2989 vector<string> command_stack(10);
2991 bool command_flag = false;
2992 Paragraph::depth_type command_depth = 0;
2993 Paragraph::depth_type command_base = 0;
2994 Paragraph::depth_type cmd_depth = 0;
2995 Paragraph::depth_type depth = 0; // paragraph depth
2998 string command_name;
3004 int desc_on = 0; // description mode
3006 LyXLayout const & style =
3007 textclasslist.Style(params.textclass,
3010 // environment tag closing
3011 for (; depth > par->params().depth(); --depth) {
3012 if (environment_inner[depth] != "!-- --") {
3013 item_name = "listitem";
3014 sgmlCloseTag(ofs, command_depth + depth,
3016 if (environment_inner[depth] == "varlistentry")
3017 sgmlCloseTag(ofs, depth+command_depth,
3018 environment_inner[depth]);
3020 sgmlCloseTag(ofs, depth + command_depth,
3021 environment_stack[depth]);
3022 environment_stack[depth].erase();
3023 environment_inner[depth].erase();
3026 if (depth == par->params().depth()
3027 && environment_stack[depth] != style.latexname()
3028 && !environment_stack[depth].empty()) {
3029 if (environment_inner[depth] != "!-- --") {
3030 item_name= "listitem";
3031 sgmlCloseTag(ofs, command_depth+depth,
3033 if (environment_inner[depth] == "varlistentry")
3035 depth + command_depth,
3036 environment_inner[depth]);
3039 sgmlCloseTag(ofs, depth + command_depth,
3040 environment_stack[depth]);
3042 environment_stack[depth].erase();
3043 environment_inner[depth].erase();
3046 // Write opening SGML tags.
3047 switch (style.latextype) {
3048 case LATEX_PARAGRAPH:
3049 sgmlOpenTag(ofs, depth + command_depth,
3055 linuxDocError(par, 0,
3056 _("Error : Wrong depth for "
3057 "LatexType Command.\n"));
3059 command_name = style.latexname();
3061 sgmlparam = style.latexparam();
3062 c_params = split(sgmlparam, c_depth,'|');
3064 cmd_depth = lyx::atoi(c_depth);
3067 if (cmd_depth < command_base) {
3068 for (Paragraph::depth_type j = command_depth; j >= command_base; --j)
3069 sgmlCloseTag(ofs, j, command_stack[j]);
3070 command_depth = command_base = cmd_depth;
3071 } else if (cmd_depth <= command_depth) {
3072 for (int j = command_depth; j >= int(cmd_depth); --j)
3073 sgmlCloseTag(ofs, j, command_stack[j]);
3074 command_depth = cmd_depth;
3076 command_depth = cmd_depth;
3078 command_depth = command_base = cmd_depth;
3079 command_flag = true;
3081 if (command_stack.size() == command_depth + 1)
3082 command_stack.push_back(string());
3083 command_stack[command_depth] = command_name;
3085 // treat label as a special case for
3086 // more WYSIWYM handling.
3087 if (par->getChar(0) == Paragraph::META_INSET) {
3088 Inset * inset = par->getInset(0);
3089 Inset::Code lyx_code = inset->lyxCode();
3090 if (lyx_code == Inset::LABEL_CODE){
3091 command_name += " id=\"";
3092 command_name += (static_cast<InsetCommand *>(inset))->getContents();
3093 command_name += "\"";
3098 sgmlOpenTag(ofs, depth + command_depth, command_name);
3099 if (c_params.empty())
3100 item_name = "title";
3102 item_name = c_params;
3103 sgmlOpenTag(ofs, depth + 1 + command_depth, item_name);
3106 case LATEX_ENVIRONMENT:
3107 case LATEX_ITEM_ENVIRONMENT:
3108 if (depth < par->params().depth()) {
3109 depth = par->params().depth();
3110 environment_stack[depth].erase();
3113 if (environment_stack[depth] != style.latexname()) {
3114 if(environment_stack.size() == depth + 1) {
3115 environment_stack.push_back("!-- --");
3116 environment_inner.push_back("!-- --");
3118 environment_stack[depth] = style.latexname();
3119 environment_inner[depth] = "!-- --";
3120 sgmlOpenTag(ofs, depth + command_depth,
3121 environment_stack[depth]);
3123 if (environment_inner[depth] != "!-- --") {
3124 item_name= "listitem";
3126 command_depth + depth,
3128 if (environment_inner[depth] == "varlistentry")
3130 depth + command_depth,
3131 environment_inner[depth]);
3135 if (style.latextype == LATEX_ENVIRONMENT) {
3136 if (!style.latexparam().empty()) {
3137 if(style.latexparam() == "CDATA")
3140 sgmlOpenTag(ofs, depth + command_depth,
3141 style.latexparam());
3146 desc_on = (style.labeltype == LABEL_MANUAL);
3149 environment_inner[depth]= "varlistentry";
3151 environment_inner[depth]= "listitem";
3153 sgmlOpenTag(ofs, depth + 1 + command_depth,
3154 environment_inner[depth]);
3158 sgmlOpenTag(ofs, depth + 1 + command_depth,
3162 sgmlOpenTag(ofs, depth + 1 + command_depth,
3167 sgmlOpenTag(ofs, depth + command_depth,
3173 simpleDocBookOnePar(ofs, extra_par, par, desc_on,
3174 depth + 1 + command_depth);
3178 // write closing SGML tags
3179 switch (style.latextype) {
3181 if (c_params.empty())
3185 sgmlCloseTag(ofs, depth + command_depth, end_tag);
3187 case LATEX_ENVIRONMENT:
3188 if (!style.latexparam().empty()) {
3189 if(style.latexparam() == "CDATA")
3192 sgmlCloseTag(ofs, depth + command_depth,
3193 style.latexparam());
3196 case LATEX_ITEM_ENVIRONMENT:
3197 if (desc_on == 1) break;
3199 sgmlCloseTag(ofs, depth + 1 + command_depth, end_tag);
3201 case LATEX_PARAGRAPH:
3202 sgmlCloseTag(ofs, depth + command_depth, style.latexname());
3205 sgmlCloseTag(ofs, depth + command_depth, style.latexname());
3211 for (int d = depth; d >= 0; --d) {
3212 if (!environment_stack[depth].empty()) {
3213 if (environment_inner[depth] != "!-- --") {
3214 item_name = "listitem";
3215 sgmlCloseTag(ofs, command_depth + depth,
3217 if (environment_inner[depth] == "varlistentry")
3218 sgmlCloseTag(ofs, depth + command_depth,
3219 environment_inner[depth]);
3222 sgmlCloseTag(ofs, depth + command_depth,
3223 environment_stack[depth]);
3227 for (int j = command_depth; j >= 0 ; --j)
3228 if (!command_stack[j].empty())
3229 sgmlCloseTag(ofs, j, command_stack[j]);
3232 sgmlCloseTag(ofs, 0, top_element);
3235 // How to check for successful close
3239 void Buffer::simpleDocBookOnePar(ostream & os, string & extra,
3240 Paragraph * par, int & desc_on,
3241 Paragraph::depth_type depth) const
3243 bool emph_flag = false;
3245 LyXLayout const & style = textclasslist.Style(params.textclass,
3248 LyXFont font_old = style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
3250 int char_line_count = depth;
3251 //if (!style.free_spacing)
3252 // os << string(depth,' ');
3254 // parsing main loop
3255 for (Paragraph::size_type i = 0;
3256 i < par->size(); ++i) {
3257 LyXFont font = par->getFont(params, i);
3259 // handle <emphasis> tag
3260 if (font_old.emph() != font.emph()) {
3261 if (font.emph() == LyXFont::ON) {
3265 os << "</emphasis>";
3270 char c = par->getChar(i);
3272 if (c == Paragraph::META_INSET) {
3273 Inset * inset = par->getInset(i);
3275 inset->docBook(this, ost);
3276 string tmp_out = ost.str().c_str();
3279 // This code needs some explanation:
3280 // Two insets are treated specially
3281 // label if it is the first element in a command paragraph
3283 // graphics inside tables or figure floats can't go on
3284 // title (the equivalente in latex for this case is caption
3285 // and title should come first
3288 if (desc_on!= 3 || i!= 0) {
3289 if (!tmp_out.empty() && tmp_out[0] == '@') {
3291 extra += frontStrip(tmp_out, '@');
3293 os << frontStrip(tmp_out, '@');
3299 } else if (font.latex() == LyXFont::ON) {
3300 // "TeX"-Mode on ==> SGML-Mode on.
3307 if (par->linuxDocConvertChar(c, sgml_string)
3308 && !style.free_spacing) { // in freespacing
3310 // non-breaking characters
3314 os << "\n</term><listitem><para>";
3327 os << "</emphasis>";
3330 // resets description flag correctly
3332 // <term> not closed...
3335 if(style.free_spacing) os << '\n';
3339 // This should be enabled when the Chktex class is implemented. (Asger)
3340 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
3341 // Other flags: -wall -v0 -x
3342 int Buffer::runChktex()
3344 if (!users->text) return 0;
3346 users->owner()->prohibitInput();
3348 // get LaTeX-Filename
3349 string const name = getLatexName();
3350 string path = OnlyPath(filename);
3352 string const org_path = path;
3353 if (lyxrc.use_tempdir || (IsDirWriteable(path) < 1)) {
3357 Path p(path); // path to LaTeX file
3358 users->owner()->message(_("Running chktex..."));
3360 // Remove all error insets
3361 bool const removedErrorInsets = users->removeAutoInsets();
3363 // Generate the LaTeX file if neccessary
3364 makeLaTeXFile(name, org_path, false);
3367 Chktex chktex(lyxrc.chktex_command, name, filepath);
3368 int res = chktex.run(terr); // run chktex
3371 WriteAlert(_("chktex did not work!"),
3372 _("Could not run with file:"), name);
3373 } else if (res > 0) {
3374 // Insert all errors as errors boxes
3375 users->insertErrors(terr);
3378 // if we removed error insets before we ran chktex or if we inserted
3379 // error insets after we ran chktex, this must be run:
3380 if (removedErrorInsets || res){
3382 users->fitCursor(users->text);
3384 users->owner()->allowInput();
3390 void Buffer::validate(LaTeXFeatures & features) const
3392 Paragraph * par = paragraph;
3393 LyXTextClass const & tclass =
3394 textclasslist.TextClass(params.textclass);
3396 // AMS Style is at document level
3397 features.amsstyle = (params.use_amsmath ||
3398 tclass.provides(LyXTextClass::amsmath));
3401 // We don't use "lyxerr.debug" because of speed. (Asger)
3402 if (lyxerr.debugging(Debug::LATEX))
3403 lyxerr << "Paragraph: " << par << endl;
3405 // Now just follow the list of paragraphs and run
3406 // validate on each of them.
3407 par->validate(features);
3409 // and then the next paragraph
3413 // the bullet shapes are buffer level not paragraph level
3414 // so they are tested here
3415 for (int i = 0; i < 4; ++i) {
3416 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
3417 int const font = params.user_defined_bullets[i].getFont();
3419 int const c = params
3420 .user_defined_bullets[i]
3427 features.latexsym = true;
3429 } else if (font == 1) {
3430 features.amssymb = true;
3431 } else if ((font >= 2 && font <= 5)) {
3432 features.pifont = true;
3437 if (lyxerr.debugging(Debug::LATEX)) {
3438 features.showStruct();
3443 void Buffer::setPaperStuff()
3445 params.papersize = BufferParams::PAPER_DEFAULT;
3446 char const c1 = params.paperpackage;
3447 if (c1 == BufferParams::PACKAGE_NONE) {
3448 char const c2 = params.papersize2;
3449 if (c2 == BufferParams::VM_PAPER_USLETTER)
3450 params.papersize = BufferParams::PAPER_USLETTER;
3451 else if (c2 == BufferParams::VM_PAPER_USLEGAL)
3452 params.papersize = BufferParams::PAPER_LEGALPAPER;
3453 else if (c2 == BufferParams::VM_PAPER_USEXECUTIVE)
3454 params.papersize = BufferParams::PAPER_EXECUTIVEPAPER;
3455 else if (c2 == BufferParams::VM_PAPER_A3)
3456 params.papersize = BufferParams::PAPER_A3PAPER;
3457 else if (c2 == BufferParams::VM_PAPER_A4)
3458 params.papersize = BufferParams::PAPER_A4PAPER;
3459 else if (c2 == BufferParams::VM_PAPER_A5)
3460 params.papersize = BufferParams::PAPER_A5PAPER;
3461 else if ((c2 == BufferParams::VM_PAPER_B3) || (c2 == BufferParams::VM_PAPER_B4) ||
3462 (c2 == BufferParams::VM_PAPER_B5))
3463 params.papersize = BufferParams::PAPER_B5PAPER;
3464 } else if ((c1 == BufferParams::PACKAGE_A4) || (c1 == BufferParams::PACKAGE_A4WIDE) ||
3465 (c1 == BufferParams::PACKAGE_WIDEMARGINSA4))
3466 params.papersize = BufferParams::PAPER_A4PAPER;
3470 // This function should be in Buffer because it's a buffer's property (ale)
3471 string const Buffer::getIncludeonlyList(char delim)
3474 for (inset_iterator it = inset_iterator_begin();
3475 it != inset_iterator_end(); ++it) {
3476 if ((*it)->lyxCode() == Inset::INCLUDE_CODE) {
3477 InsetInclude * insetinc =
3478 static_cast<InsetInclude *>(*it);
3479 if (insetinc->isIncludeOnly()) {
3482 lst += insetinc->getRelFileBaseName();
3486 lyxerr[Debug::INFO] << "Includeonly(" << lst << ')' << endl;
3491 vector<string> const Buffer::getLabelList()
3493 /// if this is a child document and the parent is already loaded
3494 /// Use the parent's list instead [ale990407]
3495 if (!params.parentname.empty()
3496 && bufferlist.exists(params.parentname)) {
3497 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3499 return tmp->getLabelList();
3502 vector<string> label_list;
3503 for (inset_iterator it = inset_iterator_begin();
3504 it != inset_iterator_end(); ++it) {
3505 vector<string> const l = (*it)->getLabelList();
3506 label_list.insert(label_list.end(), l.begin(), l.end());
3512 Buffer::Lists const Buffer::getLists() const
3515 Paragraph * par = paragraph;
3517 LyXTextClassList::size_type cap;
3518 boost::tie(found, cap) = textclasslist
3519 .NumberOfLayout(params.textclass, "Caption");
3522 char const labeltype =
3523 textclasslist.Style(params.textclass,
3524 par->getLayout()).labeltype;
3526 if (labeltype >= LABEL_COUNTER_CHAPTER
3527 && labeltype <= LABEL_COUNTER_CHAPTER + params.tocdepth) {
3528 // insert this into the table of contents
3529 SingleList & item = l["TOC"];
3532 textclasslist.TextClass(params.textclass).maxcounter());
3533 item.push_back(TocItem(par, depth, par->asString(this, true)));
3535 // For each paragrph, traverse its insets and look for
3539 Paragraph::inset_iterator it =
3540 par->inset_iterator_begin();
3541 Paragraph::inset_iterator end =
3542 par->inset_iterator_end();
3544 for (; it != end; ++it) {
3545 if ((*it)->lyxCode() == Inset::FLOAT_CODE) {
3547 static_cast<InsetFloat*>(*it);
3549 string const type = il->type();
3551 // Now find the caption in the float...
3552 // We now tranverse the paragraphs of
3554 Paragraph * tmp = il->inset.paragraph();
3556 if (tmp->layout == cap) {
3557 SingleList & item = l[type];
3559 tostr(item.size()+1) + ". " + tmp->asString(this, false);
3560 item.push_back(TocItem(tmp, 0 , str));
3567 lyxerr << "caption not found" << endl;
3576 // This is also a buffer property (ale)
3577 vector<pair<string, string> > const Buffer::getBibkeyList()
3579 /// if this is a child document and the parent is already loaded
3580 /// Use the parent's list instead [ale990412]
3581 if (!params.parentname.empty() && bufferlist.exists(params.parentname)) {
3582 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3584 return tmp->getBibkeyList();
3587 vector<pair<string, string> > keys;
3588 Paragraph * par = paragraph;
3591 keys.push_back(pair<string, string>(par->bibkey->getContents(),
3592 par->asString(this, false)));
3596 // Might be either using bibtex or a child has bibliography
3598 for (inset_iterator it = inset_iterator_begin();
3599 it != inset_iterator_end(); ++it) {
3600 // Search for Bibtex or Include inset
3601 if ((*it)->lyxCode() == Inset::BIBTEX_CODE) {
3602 vector<pair<string,string> > tmp =
3603 static_cast<InsetBibtex*>(*it)->getKeys(this);
3604 keys.insert(keys.end(), tmp.begin(), tmp.end());
3605 } else if ((*it)->lyxCode() == Inset::INCLUDE_CODE) {
3606 vector<pair<string,string> > const tmp =
3607 static_cast<InsetInclude*>(*it)->getKeys();
3608 keys.insert(keys.end(), tmp.begin(), tmp.end());
3617 bool Buffer::isDepClean(string const & name) const
3619 DEPCLEAN * item = dep_clean;
3620 while (item && item->master != name)
3622 if (!item) return true;
3627 void Buffer::markDepClean(string const & name)
3630 dep_clean = new DEPCLEAN;
3631 dep_clean->clean = true;
3632 dep_clean->master = name;
3633 dep_clean->next = 0;
3635 DEPCLEAN * item = dep_clean;
3636 while (item && item->master != name)
3641 item = new DEPCLEAN;
3643 item->master = name;
3650 bool Buffer::dispatch(string const & command)
3652 // Split command string into command and argument
3654 string line = frontStrip(command);
3655 string const arg = strip(frontStrip(split(line, cmd, ' ')));
3657 return dispatch(lyxaction.LookupFunc(cmd), arg);
3661 bool Buffer::dispatch(int action, string const & argument)
3663 bool dispatched = true;
3666 Exporter::Export(this, argument, false);
3676 void Buffer::resizeInsets(BufferView * bv)
3678 /// then remove all LyXText in text-insets
3679 Paragraph * par = paragraph;
3680 for (; par; par = par->next()) {
3681 par->resizeInsetsLyXText(bv);
3686 void Buffer::redraw()
3689 users->fitCursor(users->text);
3693 void Buffer::changeLanguage(Language const * from, Language const * to)
3696 Paragraph * par = paragraph;
3698 par->changeLanguage(params, from, to);
3704 bool Buffer::isMultiLingual()
3706 Paragraph * par = paragraph;
3708 if (par->isMultiLingual(params))
3716 Buffer::inset_iterator::inset_iterator(Paragraph * paragraph,
3717 Paragraph::size_type pos)
3720 it = par->InsetIterator(pos);
3721 if (it == par->inset_iterator_end()) {
3728 void Buffer::inset_iterator::setParagraph()
3731 it = par->inset_iterator_begin();
3732 if (it != par->inset_iterator_end())
3737 // We maintain an invariant that whenever par = 0 then it = 0
3741 Inset * Buffer::getInsetFromID(int id_arg) const
3743 for (inset_iterator it = inset_const_iterator_begin();
3744 it != inset_const_iterator_end(); ++it)
3746 if ((*it)->id() == id_arg)
3748 Inset * in = (*it)->getInsetFromID(id_arg);
3756 Paragraph * Buffer::getParFromID(int id) const
3758 if (id < 0) return 0;
3759 Paragraph * par = paragraph;
3761 if (par->id() == id) {
3764 Paragraph * tmp = par->getParFromID(id);