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 // candidate for move to BufferView
282 // (at least some parts in the beginning of the func)
285 // changed to be public and have one parameter
286 // if par = 0 normal behavior
287 // else insert behavior
288 // Returns false if "\the_end" is not read for formats >= 2.13. (Asger)
289 bool Buffer::readLyXformat2(LyXLex & lex, Paragraph * par)
292 Paragraph::depth_type depth = 0;
293 bool the_end_read = false;
295 Paragraph * return_par = 0;
296 LyXFont font(LyXFont::ALL_INHERIT, params.language);
297 if (file_format < 216 && params.language->lang() == "hebrew")
298 font.setLanguage(default_language);
299 // If we are inserting, we cheat and get a token in advance
300 bool has_token = false;
306 // We are inserting into an existing document
307 users->text->breakParagraph(users);
308 return_par = users->text->firstParagraph();
311 // We don't want to adopt the parameters from the
312 // document we insert, so we skip until the text begins:
315 pretoken = lex.GetString();
316 if (pretoken == "\\layout") {
328 pretoken = lex.GetString();
331 if (pretoken.empty()) continue;
334 parseSingleLyXformat2Token(lex, par, return_par,
335 pretoken, pos, depth,
343 paragraph = return_par;
349 // We'll remove this later. (Lgb)
352 string last_inset_read;
353 string inset_ert_contents;
354 bool ert_active = false;
359 void Buffer::insertErtContents(Paragraph * par, int & pos,
360 LyXFont const & font, bool set_inactive)
362 if (!inset_ert_contents.empty()) {
363 lyxerr[Debug::INSETS] << "ERT contents:\n"
364 << inset_ert_contents << endl;
365 Inset * inset = new InsetERT(inset_ert_contents);
366 par->insertInset(pos++, inset, font);
367 inset_ert_contents.erase();
376 Buffer::parseSingleLyXformat2Token(LyXLex & lex, Paragraph *& par,
377 Paragraph *& return_par,
378 string const & token, int & pos,
379 Paragraph::depth_type & depth,
383 bool the_end_read = false;
384 #ifndef NO_PEXTRA_REALLY
385 // This is super temporary but is needed to get the compability
386 // mode for minipages work correctly together with new tabulars.
387 static int call_depth;
389 bool checkminipage = false;
390 static Paragraph * minipar;
391 static Paragraph * parBeforeMinipage;
394 if (token[0] != '\\') {
397 inset_ert_contents += token;
400 for (string::const_iterator cit = token.begin();
401 cit != token.end(); ++cit) {
402 par->insertChar(pos, (*cit), font);
405 checkminipage = true;
409 } else if (token == "\\i") {
410 Inset * inset = new InsetLatexAccent;
411 inset->read(this, lex);
412 par->insertInset(pos, inset, font);
414 } else if (token == "\\layout") {
417 insertErtContents(par, pos, font);
420 string const layoutname = lex.GetString();
421 pair<bool, LyXTextClass::LayoutList::size_type> pp
422 = textclasslist.NumberOfLayout(params.textclass,
426 if (compare_no_case(layoutname, "latex") == 0) {
431 // The is the compability reading of layout caption.
432 // It can be removed in LyX version 1.3.0. (Lgb)
433 if (compare_no_case(layoutname, "caption") == 0) {
434 // We expect that the par we are now working on is
435 // really inside a InsetText inside a InsetFloat.
436 // We also know that captions can only be
437 // one paragraph. (Lgb)
439 // We should now read until the next "\layout"
441 // This is probably not good enough, what if the
442 // caption is the last par in the document (Lgb)
443 istream & ist = lex.getStream();
449 if (prefixIs(line, "\\layout")) {
453 if (prefixIs(line, "\\begin_inset"))
455 if (prefixIs(line, "\\end_inset")) {
466 // Now we should have the whole layout in ss
467 // we should now be able to give this to the
469 ss << "\\end_inset\n";
471 // This seems like a bug in stringstream.
472 // We really should be able to use ss
474 istringstream is(ss.str());
476 tmplex.setStream(is);
477 Inset * inset = new InsetCaption;
478 inset->Read(this, tmplex);
479 par->InsertInset(pos, inset, font);
486 par = new Paragraph(par);
490 par->layout = pp.second;
493 // use default layout "Standard" (0)
496 // Test whether the layout is obsolete.
497 LyXLayout const & layout =
498 textclasslist.Style(params.textclass,
500 if (!layout.obsoleted_by().empty())
501 par->layout = textclasslist
502 .NumberOfLayout(params.textclass,
503 layout.obsoleted_by())
505 par->params().depth(depth);
506 font = LyXFont(LyXFont::ALL_INHERIT, params.language);
507 if (file_format < 216
508 && params.language->lang() == "hebrew")
509 font.setLanguage(default_language);
514 } else if (token == "\\begin_float") {
515 // This is the compability reader. It can be removed in
516 // LyX version 1.3.0. (Lgb)
518 string const tmptok = lex.GetString();
519 //lyxerr << "old float: " << tmptok << endl;
522 stringstream old_float;
524 if (tmptok == "footnote") {
525 inset = new InsetFoot;
526 } else if (tmptok == "margin") {
527 inset = new InsetMarginal;
528 } else if (tmptok == "fig") {
529 inset = new InsetFloat("figure");
530 old_float << "placement htbp\n"
532 } else if (tmptok == "tab") {
533 inset = new InsetFloat("table");
534 old_float << "placement htbp\n"
536 } else if (tmptok == "alg") {
537 inset = new InsetFloat("algorithm");
538 old_float << "placement htbp\n"
540 } else if (tmptok == "wide-fig") {
541 inset = new InsetFloat("figure");
542 //InsetFloat * tmp = new InsetFloat("figure");
545 old_float << "placement htbp\n"
547 } else if (tmptok == "wide-tab") {
548 inset = new InsetFloat("table");
549 //InsetFloat * tmp = new InsetFloat("table");
552 old_float << "placement htbp\n"
558 return false; // no end read yet
561 old_float << "collapsed true\n";
563 // Here we need to check for \end_deeper and handle that
564 // before we do the footnote parsing.
565 // This _is_ a hack! (Lgb)
568 string const tmp = lex.GetString();
569 if (tmp == "\\end_deeper") {
570 //lyxerr << "\\end_deeper caught!" << endl;
572 lex.printError("\\end_deeper: "
573 "depth is already null");
578 old_float << tmp << ' ';
583 old_float << lex.getLongString("\\end_float")
584 << "\n\\end_inset\n";
585 //lyxerr << "Float Body:\n" << old_float.str() << endl;
586 // That this does not work seems like a bug
587 // in stringstream. (Lgb)
588 istringstream istr(old_float.str());
590 nylex.setStream(istr);
591 inset->read(this, nylex);
592 par->insertInset(pos, inset, font);
594 } else if (token == "\\begin_deeper") {
596 } else if (token == "\\end_deeper") {
598 lex.printError("\\end_deeper: "
599 "depth is already null");
603 } else if (token == "\\begin_preamble") {
604 params.readPreamble(lex);
605 } else if (token == "\\textclass") {
607 pair<bool, LyXTextClassList::size_type> pp =
608 textclasslist.NumberOfClass(lex.GetString());
610 params.textclass = pp.second;
612 WriteAlert(string(_("Textclass error")),
613 string(_("The document uses an unknown textclass \"")) +
614 lex.GetString() + string("\"."),
615 string(_("LyX will not be able to produce output correctly.")));
616 params.textclass = 0;
618 if (!textclasslist.Load(params.textclass)) {
619 // if the textclass wasn't loaded properly
620 // we need to either substitute another
621 // or stop loading the file.
622 // I can substitute but I don't see how I can
623 // stop loading... ideas?? ARRae980418
624 WriteAlert(_("Textclass Loading Error!"),
625 string(_("Can't load textclass ")) +
626 textclasslist.NameOfClass(params.textclass),
627 _("-- substituting default"));
628 params.textclass = 0;
630 } else if (token == "\\options") {
632 params.options = lex.GetString();
633 } else if (token == "\\language") {
634 params.readLanguage(lex);
635 } else if (token == "\\fontencoding") {
637 } else if (token == "\\inputencoding") {
639 params.inputenc = lex.GetString();
640 } else if (token == "\\graphics") {
641 params.readGraphicsDriver(lex);
642 } else if (token == "\\fontscheme") {
644 params.fonts = lex.GetString();
645 } else if (token == "\\noindent") {
646 par->params().noindent(true);
647 } else if (token == "\\fill_top") {
648 par->params().spaceTop(VSpace(VSpace::VFILL));
649 } else if (token == "\\fill_bottom") {
650 par->params().spaceBottom(VSpace(VSpace::VFILL));
651 } else if (token == "\\line_top") {
652 par->params().lineTop(true);
653 } else if (token == "\\line_bottom") {
654 par->params().lineBottom(true);
655 } else if (token == "\\pagebreak_top") {
656 par->params().pagebreakTop(true);
657 } else if (token == "\\pagebreak_bottom") {
658 par->params().pagebreakBottom(true);
659 } else if (token == "\\start_of_appendix") {
660 par->params().startOfAppendix(true);
661 } else if (token == "\\paragraph_separation") {
662 int tmpret = lex.FindToken(string_paragraph_separation);
663 if (tmpret == -1) ++tmpret;
664 if (tmpret != LYX_LAYOUT_DEFAULT)
665 params.paragraph_separation =
666 static_cast<BufferParams::PARSEP>(tmpret);
667 } else if (token == "\\defskip") {
669 params.defskip = VSpace(lex.GetString());
670 } else if (token == "\\epsfig") { // obsolete
671 // Indeed it is obsolete, but we HAVE to be backwards
672 // compatible until 0.14, because otherwise all figures
673 // in existing documents are irretrivably lost. (Asger)
674 params.readGraphicsDriver(lex);
675 } else if (token == "\\quotes_language") {
676 int tmpret = lex.FindToken(string_quotes_language);
677 if (tmpret == -1) ++tmpret;
678 if (tmpret != LYX_LAYOUT_DEFAULT) {
679 InsetQuotes::quote_language tmpl =
680 InsetQuotes::EnglishQ;
683 tmpl = InsetQuotes::EnglishQ;
686 tmpl = InsetQuotes::SwedishQ;
689 tmpl = InsetQuotes::GermanQ;
692 tmpl = InsetQuotes::PolishQ;
695 tmpl = InsetQuotes::FrenchQ;
698 tmpl = InsetQuotes::DanishQ;
701 params.quotes_language = tmpl;
703 } else if (token == "\\quotes_times") {
705 switch (lex.GetInteger()) {
707 params.quotes_times = InsetQuotes::SingleQ;
710 params.quotes_times = InsetQuotes::DoubleQ;
713 } else if (token == "\\papersize") {
714 int tmpret = lex.FindToken(string_papersize);
718 params.papersize2 = tmpret;
719 } else if (token == "\\paperpackage") {
720 int tmpret = lex.FindToken(string_paperpackages);
723 params.paperpackage = BufferParams::PACKAGE_NONE;
725 params.paperpackage = tmpret;
726 } else if (token == "\\use_geometry") {
728 params.use_geometry = lex.GetInteger();
729 } else if (token == "\\use_amsmath") {
731 params.use_amsmath = lex.GetInteger();
732 } else if (token == "\\paperorientation") {
733 int tmpret = lex.FindToken(string_orientation);
734 if (tmpret == -1) ++tmpret;
735 if (tmpret != LYX_LAYOUT_DEFAULT)
736 params.orientation = static_cast<BufferParams::PAPER_ORIENTATION>(tmpret);
737 } else if (token == "\\paperwidth") {
739 params.paperwidth = lex.GetString();
740 } else if (token == "\\paperheight") {
742 params.paperheight = lex.GetString();
743 } else if (token == "\\leftmargin") {
745 params.leftmargin = lex.GetString();
746 } else if (token == "\\topmargin") {
748 params.topmargin = lex.GetString();
749 } else if (token == "\\rightmargin") {
751 params.rightmargin = lex.GetString();
752 } else if (token == "\\bottommargin") {
754 params.bottommargin = lex.GetString();
755 } else if (token == "\\headheight") {
757 params.headheight = lex.GetString();
758 } else if (token == "\\headsep") {
760 params.headsep = lex.GetString();
761 } else if (token == "\\footskip") {
763 params.footskip = lex.GetString();
764 } else if (token == "\\paperfontsize") {
766 params.fontsize = strip(lex.GetString());
767 } else if (token == "\\papercolumns") {
769 params.columns = lex.GetInteger();
770 } else if (token == "\\papersides") {
772 switch (lex.GetInteger()) {
774 case 1: params.sides = LyXTextClass::OneSide; break;
775 case 2: params.sides = LyXTextClass::TwoSides; break;
777 } else if (token == "\\paperpagestyle") {
779 params.pagestyle = strip(lex.GetString());
780 } else if (token == "\\bullet") {
782 int const index = lex.GetInteger();
784 int temp_int = lex.GetInteger();
785 params.user_defined_bullets[index].setFont(temp_int);
786 params.temp_bullets[index].setFont(temp_int);
788 temp_int = lex.GetInteger();
789 params.user_defined_bullets[index].setCharacter(temp_int);
790 params.temp_bullets[index].setCharacter(temp_int);
792 temp_int = lex.GetInteger();
793 params.user_defined_bullets[index].setSize(temp_int);
794 params.temp_bullets[index].setSize(temp_int);
796 string const temp_str = lex.GetString();
797 if (temp_str != "\\end_bullet") {
798 // this element isn't really necessary for
799 // parsing but is easier for humans
800 // to understand bullets. Put it back and
801 // set a debug message?
802 lex.printError("\\end_bullet expected, got" + temp_str);
803 //how can I put it back?
805 } else if (token == "\\bulletLaTeX") {
807 int const index = lex.GetInteger();
809 string temp_str = lex.GetString();
811 while (temp_str != "\\end_bullet") {
812 // this loop structure is needed when user
813 // enters an empty string since the first
814 // thing returned will be the \\end_bullet
816 // if the LaTeX entry has spaces. Each element
817 // therefore needs to be read in turn
820 temp_str = lex.GetString();
822 params.user_defined_bullets[index].setText(sum_str);
823 params.temp_bullets[index].setText(sum_str);
824 } else if (token == "\\secnumdepth") {
826 params.secnumdepth = lex.GetInteger();
827 } else if (token == "\\tocdepth") {
829 params.tocdepth = lex.GetInteger();
830 } else if (token == "\\spacing") {
832 string const tmp = strip(lex.GetString());
833 Spacing::Space tmp_space = Spacing::Default;
835 if (tmp == "single") {
836 tmp_space = Spacing::Single;
837 } else if (tmp == "onehalf") {
838 tmp_space = Spacing::Onehalf;
839 } else if (tmp == "double") {
840 tmp_space = Spacing::Double;
841 } else if (tmp == "other") {
843 tmp_space = Spacing::Other;
844 tmp_val = lex.GetFloat();
846 lex.printError("Unknown spacing token: '$$Token'");
848 // Small hack so that files written with klyx will be
851 par->params().spacing(Spacing(tmp_space, tmp_val));
853 params.spacing.set(tmp_space, tmp_val);
855 } else if (token == "\\paragraph_spacing") {
857 string const tmp = strip(lex.GetString());
858 if (tmp == "single") {
859 par->params().spacing(Spacing(Spacing::Single));
860 } else if (tmp == "onehalf") {
861 par->params().spacing(Spacing(Spacing::Onehalf));
862 } else if (tmp == "double") {
863 par->params().spacing(Spacing(Spacing::Double));
864 } else if (tmp == "other") {
866 par->params().spacing(Spacing(Spacing::Other,
869 lex.printError("Unknown spacing token: '$$Token'");
871 } else if (token == "\\float_placement") {
873 params.float_placement = lex.GetString();
874 } else if (token == "\\family") {
876 font.setLyXFamily(lex.GetString());
877 } else if (token == "\\series") {
879 font.setLyXSeries(lex.GetString());
880 } else if (token == "\\shape") {
882 font.setLyXShape(lex.GetString());
883 } else if (token == "\\size") {
885 font.setLyXSize(lex.GetString());
888 #warning compatability hack needed
890 } else if (token == "\\latex") {
892 string const tok = lex.GetString();
893 // This is dirty, but gone with LyX3. (Asger)
894 if (tok == "no_latex")
895 font.setLatex(LyXFont::OFF);
896 else if (tok == "latex")
897 font.setLatex(LyXFont::ON);
898 else if (tok == "default")
899 font.setLatex(LyXFont::INHERIT);
901 lex.printError("Unknown LaTeX font flag "
904 } else if (token == "\\latex") {
906 string const tok = lex.GetString();
907 if (tok == "no_latex") {
909 insertErtContents(par, pos, font);
910 } else if (tok == "latex") {
912 } else if (tok == "default") {
914 insertErtContents(par, pos, font);
916 lex.printError("Unknown LaTeX font flag "
920 } else if (token == "\\lang") {
922 string const tok = lex.GetString();
923 Language const * lang = languages.getLanguage(tok);
925 font.setLanguage(lang);
927 font.setLanguage(params.language);
928 lex.printError("Unknown language `$$Token'");
930 } else if (token == "\\numeric") {
932 font.setNumber(font.setLyXMisc(lex.GetString()));
933 } else if (token == "\\emph") {
935 font.setEmph(font.setLyXMisc(lex.GetString()));
936 } else if (token == "\\bar") {
938 string const tok = lex.GetString();
939 // This is dirty, but gone with LyX3. (Asger)
941 font.setUnderbar(LyXFont::ON);
942 else if (tok == "no")
943 font.setUnderbar(LyXFont::OFF);
944 else if (tok == "default")
945 font.setUnderbar(LyXFont::INHERIT);
947 lex.printError("Unknown bar font flag "
949 } else if (token == "\\noun") {
951 font.setNoun(font.setLyXMisc(lex.GetString()));
952 } else if (token == "\\color") {
954 font.setLyXColor(lex.GetString());
955 } else if (token == "\\align") {
956 int tmpret = lex.FindToken(string_align);
957 if (tmpret == -1) ++tmpret;
958 if (tmpret != LYX_LAYOUT_DEFAULT) { // tmpret != 99 ???
959 int const tmpret2 = int(pow(2.0, tmpret));
960 //lyxerr << "Tmpret2 = " << tmpret2 << endl;
961 par->params().align(LyXAlignment(tmpret2));
963 } else if (token == "\\added_space_top") {
965 par->params().spaceTop(VSpace(lex.GetString()));
966 } else if (token == "\\added_space_bottom") {
968 par->params().spaceBottom(VSpace(lex.GetString()));
969 #ifndef NO_PEXTRA_REALLY
970 } else if (token == "\\pextra_type") {
972 par->params().pextraType(lex.GetInteger());
973 } else if (token == "\\pextra_width") {
975 par->params().pextraWidth(lex.GetString());
976 } else if (token == "\\pextra_widthp") {
978 par->params().pextraWidthp(lex.GetString());
979 } else if (token == "\\pextra_alignment") {
981 par->params().pextraAlignment(lex.GetInteger());
982 } else if (token == "\\pextra_hfill") {
984 par->params().pextraHfill(lex.GetInteger());
985 } else if (token == "\\pextra_start_minipage") {
987 par->params().pextraStartMinipage(lex.GetInteger());
989 } else if (token == "\\labelwidthstring") {
991 par->params().labelWidthString(lex.GetString());
992 // do not delete this token, it is still needed!
993 } else if (token == "\\end_inset") {
994 lyxerr << "Solitary \\end_inset. Missing \\begin_inset?.\n"
995 << "Last inset read was: " << last_inset_read
997 // Simply ignore this. The insets do not have
999 // But insets should read it, it is a part of
1000 // the inset isn't it? Lgb.
1001 } else if (token == "\\begin_inset") {
1002 readInset(lex, par, pos, font);
1003 } else if (token == "\\SpecialChar") {
1004 LyXLayout const & layout =
1005 textclasslist.Style(params.textclass,
1008 // Insets don't make sense in a free-spacing context! ---Kayvan
1009 if (layout.free_spacing) {
1012 string next_token = lex.GetString();
1013 if (next_token == "\\-") {
1014 par->insertChar(pos, '-', font);
1015 } else if (next_token == "\\protected_separator"
1016 || next_token == "~") {
1017 par->insertChar(pos, ' ', font);
1019 lex.printError("Token `$$Token' "
1021 "paragraph layout!");
1026 Inset * inset = new InsetSpecialChar;
1027 inset->read(this, lex);
1028 par->insertInset(pos, inset, font);
1031 } else if (token == "\\newline") {
1033 // Since we cannot know it this is only a regular newline or a
1034 // tabular cell delimter we have to handle the ERT here.
1035 insertErtContents(par, pos, font, false);
1037 par->insertChar(pos, Paragraph::META_NEWLINE, font);
1039 } else if (token == "\\LyXTable") {
1040 Inset * inset = new InsetTabular(*this);
1041 inset->read(this, lex);
1042 par->insertInset(pos, inset, font);
1044 // because of OLD_TABULAR_READ where tabulars have been
1046 checkminipage = true;
1047 } else if (token == "\\hfill") {
1048 par->insertChar(pos, Paragraph::META_HFILL, font);
1050 } else if (token == "\\protected_separator") { // obsolete
1051 // This is a backward compability thingie. (Lgb)
1052 // Remove it later some time...introduced with fileformat
1054 LyXLayout const & layout =
1055 textclasslist.Style(params.textclass,
1058 if (layout.free_spacing) {
1059 par->insertChar(pos, ' ', font);
1061 Inset * inset = new InsetSpecialChar(InsetSpecialChar::PROTECTED_SEPARATOR);
1062 par->insertInset(pos, inset, font);
1065 } else if (token == "\\bibitem") { // ale970302
1067 InsetCommandParams p("bibitem", "dummy");
1068 par->bibkey = new InsetBibKey(p);
1070 par->bibkey->read(this, lex);
1071 } else if (token == "\\backslash") {
1074 inset_ert_contents += "\\";
1077 par->insertChar(pos, '\\', font);
1082 } else if (token == "\\the_end") {
1084 // If we still have some ert active here we have to insert
1085 // it so we don't loose it. (Lgb)
1086 insertErtContents(par, pos, font);
1088 the_end_read = true;
1089 minipar = parBeforeMinipage = 0;
1093 inset_ert_contents += token;
1096 // This should be insurance for the future: (Asger)
1097 lex.printError("Unknown token `$$Token'. "
1098 "Inserting as text.");
1099 string::const_iterator cit = token.begin();
1100 string::const_iterator end = token.end();
1101 for (; cit != end; ++cit) {
1102 par->insertChar(pos, (*cit), font);
1109 #ifndef NO_PEXTRA_REALLY
1110 // now check if we have a minipage paragraph as at this
1111 // point we already read all the necessary data!
1112 // this cannot be done in layout because there we did
1113 // not read yet the paragraph PEXTRA-params (Jug)
1115 // BEGIN pextra_minipage compability
1116 // This should be removed in 1.3.x (Lgb)
1118 // This compability code is not perfect. In a couple
1119 // of rand cases it fails. When the minipage par is
1120 // the first par in the document, and when there are
1121 // none or only one regular paragraphs after the
1122 // minipage. Currently I am not investing any effort
1123 // in fixing those cases.
1125 //lyxerr << "Call depth: " << call_depth << endl;
1126 if (checkminipage && (call_depth == 1)) {
1127 checkminipage = false;
1128 if (minipar && (minipar != par) &&
1129 (par->params().pextraType()==Paragraph::PEXTRA_MINIPAGE))
1131 lyxerr << "minipages in a row" << endl;
1132 if (par->params().pextraStartMinipage()) {
1133 lyxerr << "start new minipage" << endl;
1134 // minipages in a row
1135 par->previous()->next(0);
1138 Paragraph * tmp = minipar;
1140 tmp->params().pextraType(0);
1141 tmp->params().pextraWidth(string());
1142 tmp->params().pextraWidthp(string());
1143 tmp->params().pextraAlignment(0);
1144 tmp->params().pextraHfill(false);
1145 tmp->params().pextraStartMinipage(false);
1148 // create a new paragraph to insert the
1149 // minipages in the following case
1150 if (par->params().pextraStartMinipage() &&
1151 !par->params().pextraHfill())
1153 Paragraph * p = new Paragraph;
1155 p->previous(parBeforeMinipage);
1156 parBeforeMinipage->next(p);
1158 p->params().depth(parBeforeMinipage->params().depth());
1159 parBeforeMinipage = p;
1161 InsetMinipage * mini = new InsetMinipage;
1162 mini->pos(static_cast<InsetMinipage::Position>(par->params().pextraAlignment()));
1163 mini->width(par->params().pextraWidth());
1164 if (!par->params().pextraWidthp().empty()) {
1165 lyxerr << "WP:" << mini->width() << endl;
1166 mini->width(tostr(par->params().pextraWidthp())+"%");
1168 mini->inset.paragraph(par);
1169 // Insert the minipage last in the
1170 // previous paragraph.
1171 if (par->params().pextraHfill()) {
1172 parBeforeMinipage->insertChar
1173 (parBeforeMinipage->size(), Paragraph::META_HFILL);
1175 parBeforeMinipage->insertInset
1176 (parBeforeMinipage->size(), mini);
1180 lyxerr << "new minipage par" << endl;
1181 //nothing to do just continue reading
1184 } else if (minipar && (minipar != par)) {
1185 lyxerr << "last minipage par read" << endl;
1186 // The last paragraph read was not part of a
1187 // minipage but the par linked list is...
1188 // So we need to remove the last par from the
1190 if (par->previous())
1191 par->previous()->next(0);
1192 par->previous(parBeforeMinipage);
1193 parBeforeMinipage->next(par);
1194 Paragraph * tmp = minipar;
1196 tmp->params().pextraType(0);
1197 tmp->params().pextraWidth(string());
1198 tmp->params().pextraWidthp(string());
1199 tmp->params().pextraAlignment(0);
1200 tmp->params().pextraHfill(false);
1201 tmp->params().pextraStartMinipage(false);
1204 depth = parBeforeMinipage->params().depth();
1205 minipar = parBeforeMinipage = 0;
1206 } else if (!minipar &&
1207 (par->params().pextraType() == Paragraph::PEXTRA_MINIPAGE))
1209 // par is the first paragraph in a minipage
1210 lyxerr << "begin minipage" << endl;
1211 // To minimize problems for
1212 // the users we will insert
1213 // the first minipage in
1214 // a sequence of minipages
1215 // in its own paragraph.
1216 Paragraph * p = new Paragraph;
1218 p->previous(par->previous());
1220 p->params().depth(depth);
1221 par->params().depth(0);
1223 if (par->previous())
1224 par->previous()->next(p);
1226 parBeforeMinipage = p;
1228 if (!return_par || (return_par == par))
1231 InsetMinipage * mini = new InsetMinipage;
1232 mini->pos(static_cast<InsetMinipage::Position>(minipar->params().pextraAlignment()));
1233 mini->width(minipar->params().pextraWidth());
1234 if (!par->params().pextraWidthp().empty()) {
1235 lyxerr << "WP:" << mini->width() << endl;
1236 mini->width(tostr(par->params().pextraWidthp())+"%");
1238 mini->inset.paragraph(minipar);
1240 // Insert the minipage last in the
1241 // previous paragraph.
1242 if (minipar->params().pextraHfill()) {
1243 parBeforeMinipage->insertChar
1244 (parBeforeMinipage->size(),Paragraph::META_HFILL);
1246 parBeforeMinipage->insertInset
1247 (parBeforeMinipage->size(), mini);
1250 // End of pextra_minipage compability
1253 return the_end_read;
1257 void Buffer::readInset(LyXLex & lex, Paragraph *& par,
1258 int & pos, LyXFont & font)
1260 // consistency check
1261 if (lex.GetString() != "\\begin_inset") {
1262 lyxerr << "Buffer::readInset: Consistency check failed."
1269 string const tmptok = lex.GetString();
1270 last_inset_read = tmptok;
1272 // test the different insets
1273 if (tmptok == "LatexCommand") {
1274 InsetCommandParams inscmd;
1277 string const cmdName = inscmd.getCmdName();
1279 if (cmdName == "cite") {
1280 inset = new InsetCitation(inscmd);
1281 } else if (cmdName == "bibitem") {
1282 lex.printError("Wrong place for bibitem");
1283 inset = new InsetBibKey(inscmd);
1284 } else if (cmdName == "BibTeX") {
1285 inset = new InsetBibtex(inscmd);
1286 } else if (cmdName == "index") {
1287 inset = new InsetIndex(inscmd);
1288 } else if (cmdName == "include") {
1289 inset = new InsetInclude(inscmd, *this);
1290 } else if (cmdName == "label") {
1291 inset = new InsetLabel(inscmd);
1292 } else if (cmdName == "url"
1293 || cmdName == "htmlurl") {
1294 inset = new InsetUrl(inscmd);
1295 } else if (cmdName == "ref"
1296 || cmdName == "pageref"
1297 || cmdName == "vref"
1298 || cmdName == "vpageref"
1299 || cmdName == "prettyref") {
1300 if (!inscmd.getOptions().empty()
1301 || !inscmd.getContents().empty()) {
1302 inset = new InsetRef(inscmd, *this);
1304 } else if (cmdName == "tableofcontents") {
1305 inset = new InsetTOC(inscmd);
1306 } else if (cmdName == "listofalgorithms") {
1307 inset = new InsetFloatList("algorithm");
1308 } else if (cmdName == "listoffigures") {
1309 inset = new InsetFloatList("figure");
1310 } else if (cmdName == "listoftables") {
1311 inset = new InsetFloatList("table");
1312 } else if (cmdName == "printindex") {
1313 inset = new InsetPrintIndex(inscmd);
1314 } else if (cmdName == "lyxparent") {
1315 inset = new InsetParent(inscmd, *this);
1318 if (tmptok == "Quotes") {
1319 inset = new InsetQuotes;
1320 } else if (tmptok == "External") {
1321 inset = new InsetExternal;
1322 } else if (tmptok == "FormulaMacro") {
1323 inset = new InsetFormulaMacro;
1324 } else if (tmptok == "Formula") {
1325 inset = new InsetFormula;
1326 } else if (tmptok == "Figure") {
1327 inset = new InsetFig(100, 100, *this);
1328 } else if (tmptok == "Info") {
1329 inset = new InsetInfo;
1330 } else if (tmptok == "Include") {
1331 InsetCommandParams p( "Include" );
1332 inset = new InsetInclude(p, *this);
1333 } else if (tmptok == "ERT") {
1334 inset = new InsetERT;
1335 } else if (tmptok == "Tabular") {
1336 inset = new InsetTabular(*this);
1337 } else if (tmptok == "Text") {
1338 inset = new InsetText;
1339 } else if (tmptok == "Foot") {
1340 inset = new InsetFoot;
1341 } else if (tmptok == "Marginal") {
1342 inset = new InsetMarginal;
1343 } else if (tmptok == "Minipage") {
1344 inset = new InsetMinipage;
1345 } else if (tmptok == "Float") {
1347 string tmptok = lex.GetString();
1348 inset = new InsetFloat(tmptok);
1349 } else if (tmptok == "List") {
1350 inset = new InsetList;
1351 } else if (tmptok == "Theorem") {
1352 inset = new InsetList;
1353 } else if (tmptok == "Caption") {
1354 inset = new InsetCaption;
1355 } else if (tmptok == "GRAPHICS") {
1356 inset = new InsetGraphics;
1357 } else if (tmptok == "FloatList") {
1358 inset = new InsetFloatList;
1361 if (inset) inset->read(this, lex);
1365 par->insertInset(pos, inset, font);
1371 bool Buffer::readFile(LyXLex & lex, Paragraph * par)
1375 string const token(lex.GetString());
1376 if (token == "\\lyxformat") { // the first token _must_ be...
1378 string tmp_format = lex.GetString();
1379 //lyxerr << "LyX Format: `" << tmp_format << "'" << endl;
1380 // if present remove ".," from string.
1381 string::size_type dot = tmp_format.find_first_of(".,");
1382 //lyxerr << " dot found at " << dot << endl;
1383 if (dot != string::npos)
1384 tmp_format.erase(dot, 1);
1385 file_format = strToInt(tmp_format);
1386 if (file_format == LYX_FORMAT) {
1388 } else if (file_format > LYX_FORMAT) {
1390 WriteAlert(_("Warning!"),
1391 _("LyX file format is newer that what"),
1392 _("is supported in this LyX version. Expect some problems."));
1394 } else if (file_format < LYX_FORMAT) {
1396 if (file_format < 200) {
1397 WriteAlert(_("ERROR!"),
1398 _("Old LyX file format found. "
1399 "Use LyX 0.10.x to read this!"));
1403 bool the_end = readLyXformat2(lex, par);
1405 // the_end was added in 213
1406 if (file_format < 213)
1410 WriteAlert(_("Warning!"),
1411 _("Reading of document is not complete"),
1412 _("Maybe the document is truncated"));
1414 } else { // "\\lyxformat" not found
1415 WriteAlert(_("ERROR!"), _("Not a LyX file!"));
1418 WriteAlert(_("ERROR!"), _("Unable to read file!"));
1423 // Should probably be moved to somewhere else: BufferView? LyXView?
1424 bool Buffer::save() const
1426 // We don't need autosaves in the immediate future. (Asger)
1427 resetAutosaveTimers();
1431 if (lyxrc.make_backup) {
1432 s = fileName() + '~';
1433 if (!lyxrc.backupdir_path.empty())
1434 s = AddName(lyxrc.backupdir_path,
1435 subst(os::slashify_path(s),'/','!'));
1437 // Rename is the wrong way of making a backup,
1438 // this is the correct way.
1439 /* truss cp fil fil2:
1440 lstat("LyXVC3.lyx", 0xEFFFF898) Err#2 ENOENT
1441 stat("LyXVC.lyx", 0xEFFFF688) = 0
1442 open("LyXVC.lyx", O_RDONLY) = 3
1443 open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
1444 fstat(4, 0xEFFFF508) = 0
1445 fstat(3, 0xEFFFF508) = 0
1446 read(3, " # T h i s f i l e w".., 8192) = 5579
1447 write(4, " # T h i s f i l e w".., 5579) = 5579
1448 read(3, 0xEFFFD4A0, 8192) = 0
1451 chmod("LyXVC3.lyx", 0100644) = 0
1452 lseek(0, 0, SEEK_CUR) = 46440
1456 // Should probably have some more error checking here.
1457 // Should be cleaned up in 0.13, at least a bit.
1458 // Doing it this way, also makes the inodes stay the same.
1459 // This is still not a very good solution, in particular we
1460 // might loose the owner of the backup.
1461 FileInfo finfo(fileName());
1462 if (finfo.exist()) {
1463 mode_t fmode = finfo.getMode();
1464 struct utimbuf times = {
1465 finfo.getAccessTime(),
1466 finfo.getModificationTime() };
1468 ifstream ifs(fileName().c_str());
1469 ofstream ofs(s.c_str(), ios::out|ios::trunc);
1474 ::chmod(s.c_str(), fmode);
1476 if (::utime(s.c_str(), ×)) {
1477 lyxerr << "utime error." << endl;
1480 lyxerr << "LyX was not able to make "
1481 "backup copy. Beware." << endl;
1486 if (writeFile(fileName(), false)) {
1488 removeAutosaveFile(fileName());
1490 // Saving failed, so backup is not backup
1491 if (lyxrc.make_backup) {
1492 lyx::rename(s, fileName());
1500 // Returns false if unsuccesful
1501 bool Buffer::writeFile(string const & fname, bool flag) const
1503 // if flag is false writeFile will not create any GUI
1504 // warnings, only cerr.
1505 // Needed for autosave in background or panic save (Matthias 120496)
1507 if (read_only && (fname == filename)) {
1508 // Here we should come with a question if we should
1509 // perform the write anyway.
1511 lyxerr << _("Error! Document is read-only: ")
1514 WriteAlert(_("Error! Document is read-only: "),
1519 FileInfo finfo(fname);
1520 if (finfo.exist() && !finfo.writable()) {
1521 // Here we should come with a question if we should
1522 // try to do the save anyway. (i.e. do a chmod first)
1524 lyxerr << _("Error! Cannot write file: ")
1527 WriteFSAlert(_("Error! Cannot write file: "),
1532 ofstream ofs(fname.c_str());
1535 lyxerr << _("Error! Cannot open file: ")
1538 WriteFSAlert(_("Error! Cannot open file: "),
1544 // Use the standard "C" locale for file output.
1545 ofs.imbue(std::locale::classic());
1548 // The top of the file should not be written by params.
1550 // write out a comment in the top of the file
1551 ofs << '#' << LYX_DOCVERSION
1552 << " created this file. For more info see http://www.lyx.org/\n"
1553 << "\\lyxformat " << LYX_FORMAT << "\n";
1555 // now write out the buffer paramters.
1556 params.writeFile(ofs);
1558 Paragraph::depth_type depth = 0;
1560 // this will write out all the paragraphs
1561 // using recursive descent.
1562 paragraph->writeFile(this, ofs, params, depth);
1564 // Write marker that shows file is complete
1565 ofs << "\n\\the_end" << endl;
1569 // how to check if close went ok?
1570 // Following is an attempt... (BE 20001011)
1572 // good() returns false if any error occured, including some
1573 // formatting error.
1574 // bad() returns true if something bad happened in the buffer,
1575 // which should include file system full errors.
1582 lyxerr << "Buffer::writeFile: BAD ERROR!" << endl;
1584 lyxerr << "Buffer::writeFile: NOT SO BAD ERROR!"
1594 string const Buffer::asciiParagraph(Paragraph const * par,
1595 unsigned int linelen) const
1597 ostringstream buffer;
1598 Paragraph::depth_type depth = 0;
1600 Paragraph::depth_type ltype_depth = 0;
1601 unsigned int currlinelen = 0;
1602 bool ref_printed = false;
1606 if (!par->previous()) {
1607 // begins or ends a deeper area ?
1608 if (depth != par->params().depth()) {
1609 if (par->params().depth() > depth) {
1610 while (par->params().depth() > depth) {
1614 while (par->params().depth() < depth) {
1620 // First write the layout
1621 string const tmp = textclasslist.NameOfLayout(params.textclass, par->layout);
1622 if (tmp == "Itemize") {
1624 ltype_depth = depth + 1;
1625 } else if (tmp == "Enumerate") {
1627 ltype_depth = depth + 1;
1628 } else if (contains(tmp, "ection")) {
1630 ltype_depth = depth + 1;
1631 } else if (contains(tmp, "aragraph")) {
1633 ltype_depth = depth + 1;
1634 } else if (tmp == "Description") {
1636 ltype_depth = depth + 1;
1637 } else if (tmp == "Abstract") {
1640 } else if (tmp == "Bibliography") {
1648 /* maybe some vertical spaces */
1650 /* the labelwidthstring used in lists */
1654 /* some pagebreaks? */
1658 /* what about the alignment */
1660 lyxerr << "Should this ever happen?" << endl;
1664 LyXFont const font1 = LyXFont(LyXFont::ALL_INHERIT, params.language);
1666 for (Paragraph::size_type i = 0; i < par->size(); ++i) {
1667 if (!i && !noparbreak) {
1670 for (Paragraph::depth_type j = 0; j < depth; ++j)
1672 currlinelen = depth * 2;
1675 case 4: // (Sub)Paragraph
1676 case 5: // Description
1680 buffer << "Abstract\n\n";
1682 buffer << "Abstract: ";
1684 case 7: // Bibliography
1687 buffer << "References\n\n";
1689 buffer << "References: ";
1694 buffer << par->params().labelString() << " ";
1697 if (ltype_depth > depth) {
1698 for (Paragraph::depth_type j = ltype_depth - 1;
1701 currlinelen += (ltype_depth-depth)*2;
1705 LyXFont const font2 = par->getFontSettings(params, i);
1706 if (font1.latex() != font2.latex()) {
1707 if (font2.latex() == LyXFont::OFF)
1716 char c = par->getUChar(params, i);
1720 case Paragraph::META_INSET:
1722 Inset const * inset = par->getInset(i);
1724 if (!inset->ascii(this, buffer)) {
1727 rsplit(buffer.str().c_str(),
1729 currlinelen += s.length();
1731 // to be sure it breaks paragraph
1732 currlinelen += linelen;
1738 case Paragraph::META_NEWLINE:
1741 for (Paragraph::depth_type j = 0;
1745 currlinelen = depth * 2;
1746 if (ltype_depth > depth) {
1747 for (Paragraph::depth_type j = ltype_depth;
1750 currlinelen += (ltype_depth - depth) * 2;
1754 case Paragraph::META_HFILL:
1763 if ((linelen > 0) && (currlinelen > (linelen - 10)) &&
1764 (c == ' ') && ((i + 2) < par->size()))
1767 for (Paragraph::depth_type j = 0;
1770 currlinelen = depth * 2;
1771 if (ltype_depth > depth) {
1772 for (Paragraph::depth_type j = ltype_depth;
1775 currlinelen += (ltype_depth-depth)*2;
1777 } else if (c != '\0')
1780 lyxerr[Debug::INFO] << "writeAsciiFile: NULL char in structure." << endl;
1785 return buffer.str().c_str();
1789 void Buffer::writeFileAscii(string const & fname, int linelen)
1791 ofstream ofs(fname.c_str());
1793 WriteFSAlert(_("Error: Cannot write file:"), fname);
1796 writeFileAscii(ofs, linelen);
1800 void Buffer::writeFileAscii(ostream & ofs, int linelen)
1802 Paragraph * par = paragraph;
1804 ofs << asciiParagraph(par, linelen);
1812 void Buffer::makeLaTeXFile(string const & fname,
1813 string const & original_path,
1814 bool nice, bool only_body)
1816 lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
1818 niceFile = nice; // this will be used by Insetincludes.
1820 tex_code_break_column = lyxrc.ascii_linelen;
1822 LyXTextClass const & tclass =
1823 textclasslist.TextClass(params.textclass);
1825 ofstream ofs(fname.c_str());
1827 WriteFSAlert(_("Error: Cannot open file: "), fname);
1831 // validate the buffer.
1832 lyxerr[Debug::LATEX] << " Validating buffer..." << endl;
1833 LaTeXFeatures features(params, tclass.numLayouts());
1835 lyxerr[Debug::LATEX] << " Buffer validation done." << endl;
1838 // The starting paragraph of the coming rows is the
1839 // first paragraph of the document. (Asger)
1840 texrow.start(paragraph, 0);
1842 if (!only_body && nice) {
1843 ofs << "%% " LYX_DOCVERSION " created this file. "
1844 "For more info, see http://www.lyx.org/.\n"
1845 "%% Do not edit unless you really know what "
1850 lyxerr[Debug::INFO] << "lyx header finished" << endl;
1851 // There are a few differences between nice LaTeX and usual files:
1852 // usual is \batchmode and has a
1853 // special input@path to allow the including of figures
1854 // with either \input or \includegraphics (what figinsets do).
1855 // batchmode is not set if there is a tex_code_break_column.
1856 // In this case somebody is interested in the generated LaTeX,
1857 // so this is OK. input@path is set when the actual parameter
1858 // original_path is set. This is done for usual tex-file, but not
1859 // for nice-latex-file. (Matthias 250696)
1862 // code for usual, NOT nice-latex-file
1863 ofs << "\\batchmode\n"; // changed
1864 // from \nonstopmode
1867 if (!original_path.empty()) {
1868 ofs << "\\makeatletter\n"
1869 << "\\def\\input@path{{"
1870 << os::external_path(original_path) << "/}}\n"
1871 << "\\makeatother\n";
1877 ofs << "\\documentclass";
1879 ostringstream options; // the document class options.
1881 if (tokenPos(tclass.opt_fontsize(),
1882 '|', params.fontsize) >= 0) {
1883 // only write if existing in list (and not default)
1884 options << params.fontsize << "pt,";
1888 if (!params.use_geometry &&
1889 (params.paperpackage == BufferParams::PACKAGE_NONE)) {
1890 switch (params.papersize) {
1891 case BufferParams::PAPER_A4PAPER:
1892 options << "a4paper,";
1894 case BufferParams::PAPER_USLETTER:
1895 options << "letterpaper,";
1897 case BufferParams::PAPER_A5PAPER:
1898 options << "a5paper,";
1900 case BufferParams::PAPER_B5PAPER:
1901 options << "b5paper,";
1903 case BufferParams::PAPER_EXECUTIVEPAPER:
1904 options << "executivepaper,";
1906 case BufferParams::PAPER_LEGALPAPER:
1907 options << "legalpaper,";
1913 if (params.sides != tclass.sides()) {
1914 switch (params.sides) {
1915 case LyXTextClass::OneSide:
1916 options << "oneside,";
1918 case LyXTextClass::TwoSides:
1919 options << "twoside,";
1925 if (params.columns != tclass.columns()) {
1926 if (params.columns == 2)
1927 options << "twocolumn,";
1929 options << "onecolumn,";
1932 if (!params.use_geometry
1933 && params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
1934 options << "landscape,";
1936 // language should be a parameter to \documentclass
1938 ostringstream language_options;
1939 if (params.language->babel() == "hebrew"
1940 && default_language->babel() != "hebrew")
1941 // This seems necessary
1942 features.UsedLanguages.insert(default_language);
1944 if (lyxrc.language_use_babel ||
1945 params.language->lang() != lyxrc.default_language ||
1946 !features.UsedLanguages.empty()) {
1948 for (LaTeXFeatures::LanguageList::const_iterator cit =
1949 features.UsedLanguages.begin();
1950 cit != features.UsedLanguages.end(); ++cit)
1951 language_options << (*cit)->babel() << ',';
1952 language_options << params.language->babel();
1953 if (lyxrc.language_global_options)
1954 options << language_options.str() << ',';
1957 // the user-defined options
1958 if (!params.options.empty()) {
1959 options << params.options << ',';
1962 string strOptions(options.str().c_str());
1963 if (!strOptions.empty()){
1964 strOptions = strip(strOptions, ',');
1965 ofs << '[' << strOptions << ']';
1969 << textclasslist.LatexnameOfClass(params.textclass)
1972 // end of \documentclass defs
1974 // font selection must be done before loading fontenc.sty
1975 // The ae package is not needed when using OT1 font encoding.
1976 if (params.fonts != "default" &&
1977 (params.fonts != "ae" || lyxrc.fontenc != "default")) {
1978 ofs << "\\usepackage{" << params.fonts << "}\n";
1980 if (params.fonts == "ae") {
1981 ofs << "\\usepackage{aecompl}\n";
1985 // this one is not per buffer
1986 if (lyxrc.fontenc != "default") {
1987 ofs << "\\usepackage[" << lyxrc.fontenc
1992 if (params.inputenc == "auto") {
1993 string const doc_encoding =
1994 params.language->encoding()->LatexName();
1996 // Create a list with all the input encodings used
1998 set<string> encodings;
1999 for (LaTeXFeatures::LanguageList::const_iterator it =
2000 features.UsedLanguages.begin();
2001 it != features.UsedLanguages.end(); ++it)
2002 if ((*it)->encoding()->LatexName() != doc_encoding)
2003 encodings.insert((*it)->encoding()->LatexName());
2005 ofs << "\\usepackage[";
2006 std::copy(encodings.begin(), encodings.end(),
2007 std::ostream_iterator<string>(ofs, ","));
2008 ofs << doc_encoding << "]{inputenc}\n";
2010 } else if (params.inputenc != "default") {
2011 ofs << "\\usepackage[" << params.inputenc
2016 // At the very beginning the text parameters.
2017 if (params.paperpackage != BufferParams::PACKAGE_NONE) {
2018 switch (params.paperpackage) {
2019 case BufferParams::PACKAGE_A4:
2020 ofs << "\\usepackage{a4}\n";
2023 case BufferParams::PACKAGE_A4WIDE:
2024 ofs << "\\usepackage{a4wide}\n";
2027 case BufferParams::PACKAGE_WIDEMARGINSA4:
2028 ofs << "\\usepackage[widemargins]{a4}\n";
2033 if (params.use_geometry) {
2034 ofs << "\\usepackage{geometry}\n";
2036 ofs << "\\geometry{verbose";
2037 if (params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
2038 ofs << ",landscape";
2039 switch (params.papersize2) {
2040 case BufferParams::VM_PAPER_CUSTOM:
2041 if (!params.paperwidth.empty())
2042 ofs << ",paperwidth="
2043 << params.paperwidth;
2044 if (!params.paperheight.empty())
2045 ofs << ",paperheight="
2046 << params.paperheight;
2048 case BufferParams::VM_PAPER_USLETTER:
2049 ofs << ",letterpaper";
2051 case BufferParams::VM_PAPER_USLEGAL:
2052 ofs << ",legalpaper";
2054 case BufferParams::VM_PAPER_USEXECUTIVE:
2055 ofs << ",executivepaper";
2057 case BufferParams::VM_PAPER_A3:
2060 case BufferParams::VM_PAPER_A4:
2063 case BufferParams::VM_PAPER_A5:
2066 case BufferParams::VM_PAPER_B3:
2069 case BufferParams::VM_PAPER_B4:
2072 case BufferParams::VM_PAPER_B5:
2076 // default papersize ie BufferParams::VM_PAPER_DEFAULT
2077 switch (lyxrc.default_papersize) {
2078 case BufferParams::PAPER_DEFAULT: // keep compiler happy
2079 case BufferParams::PAPER_USLETTER:
2080 ofs << ",letterpaper";
2082 case BufferParams::PAPER_LEGALPAPER:
2083 ofs << ",legalpaper";
2085 case BufferParams::PAPER_EXECUTIVEPAPER:
2086 ofs << ",executivepaper";
2088 case BufferParams::PAPER_A3PAPER:
2091 case BufferParams::PAPER_A4PAPER:
2094 case BufferParams::PAPER_A5PAPER:
2097 case BufferParams::PAPER_B5PAPER:
2102 if (!params.topmargin.empty())
2103 ofs << ",tmargin=" << params.topmargin;
2104 if (!params.bottommargin.empty())
2105 ofs << ",bmargin=" << params.bottommargin;
2106 if (!params.leftmargin.empty())
2107 ofs << ",lmargin=" << params.leftmargin;
2108 if (!params.rightmargin.empty())
2109 ofs << ",rmargin=" << params.rightmargin;
2110 if (!params.headheight.empty())
2111 ofs << ",headheight=" << params.headheight;
2112 if (!params.headsep.empty())
2113 ofs << ",headsep=" << params.headsep;
2114 if (!params.footskip.empty())
2115 ofs << ",footskip=" << params.footskip;
2119 if (features.amsstyle
2120 && !tclass.provides(LyXTextClass::amsmath)) {
2121 ofs << "\\usepackage{amsmath}\n";
2125 if (tokenPos(tclass.opt_pagestyle(),
2126 '|', params.pagestyle) >= 0) {
2127 if (params.pagestyle == "fancy") {
2128 ofs << "\\usepackage{fancyhdr}\n";
2131 ofs << "\\pagestyle{" << params.pagestyle << "}\n";
2135 // We try to load babel late, in case it interferes
2136 // with other packages.
2138 string tmp = lyxrc.language_package;
2139 if (!lyxrc.language_global_options
2140 && tmp == "\\usepackage{babel}")
2141 tmp = string("\\usepackage[") +
2142 language_options.str().c_str() +
2148 if (params.secnumdepth != tclass.secnumdepth()) {
2149 ofs << "\\setcounter{secnumdepth}{"
2150 << params.secnumdepth
2154 if (params.tocdepth != tclass.tocdepth()) {
2155 ofs << "\\setcounter{tocdepth}{"
2161 if (params.paragraph_separation) {
2162 switch (params.defskip.kind()) {
2163 case VSpace::SMALLSKIP:
2164 ofs << "\\setlength\\parskip{\\smallskipamount}\n";
2166 case VSpace::MEDSKIP:
2167 ofs << "\\setlength\\parskip{\\medskipamount}\n";
2169 case VSpace::BIGSKIP:
2170 ofs << "\\setlength\\parskip{\\bigskipamount}\n";
2172 case VSpace::LENGTH:
2173 ofs << "\\setlength\\parskip{"
2174 << params.defskip.length().asLatexString()
2177 default: // should never happen // Then delete it.
2178 ofs << "\\setlength\\parskip{\\medskipamount}\n";
2183 ofs << "\\setlength\\parindent{0pt}\n";
2187 // Now insert the LyX specific LaTeX commands...
2189 // The optional packages;
2190 string preamble(features.getPackages());
2192 // this might be useful...
2193 preamble += "\n\\makeatletter\n";
2195 // Some macros LyX will need
2196 string tmppreamble(features.getMacros());
2198 if (!tmppreamble.empty()) {
2199 preamble += "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2200 "LyX specific LaTeX commands.\n"
2201 + tmppreamble + '\n';
2204 // the text class specific preamble
2205 tmppreamble = features.getTClassPreamble();
2206 if (!tmppreamble.empty()) {
2207 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2208 "Textclass specific LaTeX commands.\n"
2209 + tmppreamble + '\n';
2212 /* the user-defined preamble */
2213 if (!params.preamble.empty()) {
2214 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2215 "User specified LaTeX commands.\n"
2216 + params.preamble + '\n';
2219 preamble += "\\makeatother\n";
2221 // Itemize bullet settings need to be last in case the user
2222 // defines their own bullets that use a package included
2223 // in the user-defined preamble -- ARRae
2224 // Actually it has to be done much later than that
2225 // since some packages like frenchb make modifications
2226 // at \begin{document} time -- JMarc
2228 for (int i = 0; i < 4; ++i) {
2229 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
2230 if (bullets_def.empty())
2231 bullets_def="\\AtBeginDocument{\n";
2232 bullets_def += " \\renewcommand{\\labelitemi";
2234 // `i' is one less than the item to modify
2241 bullets_def += "ii";
2247 bullets_def += "}{" +
2248 params.user_defined_bullets[i].getText()
2253 if (!bullets_def.empty())
2254 preamble += bullets_def + "}\n\n";
2256 for (int j = countChar(preamble, '\n'); j-- ;) {
2263 ofs << "\\begin{document}\n";
2266 lyxerr[Debug::INFO] << "preamble finished, now the body." << endl;
2268 if (!lyxrc.language_auto_begin) {
2269 ofs << subst(lyxrc.language_command_begin, "$$lang",
2270 params.language->babel())
2275 latexParagraphs(ofs, paragraph, 0, texrow);
2277 // add this just in case after all the paragraphs
2281 if (!lyxrc.language_auto_end) {
2282 ofs << subst(lyxrc.language_command_end, "$$lang",
2283 params.language->babel())
2289 ofs << "\\end{document}\n";
2292 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
2294 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
2298 // Just to be sure. (Asger)
2301 // tex_code_break_column's value is used to decide
2302 // if we are in batchmode or not (within mathed_write()
2303 // in math_write.C) so we must set it to a non-zero
2304 // value when we leave otherwise we save incorrect .lyx files.
2305 tex_code_break_column = lyxrc.ascii_linelen;
2309 lyxerr << "File was not closed properly." << endl;
2312 lyxerr[Debug::INFO] << "Finished making latex file." << endl;
2317 // LaTeX all paragraphs from par to endpar, if endpar == 0 then to the end
2319 void Buffer::latexParagraphs(ostream & ofs, Paragraph * par,
2320 Paragraph * endpar, TexRow & texrow) const
2322 bool was_title = false;
2323 bool already_title = false;
2326 while (par != endpar) {
2327 LyXLayout const & layout =
2328 textclasslist.Style(params.textclass,
2331 if (layout.intitle) {
2332 if (already_title) {
2333 lyxerr <<"Error in latexParagraphs: You"
2334 " should not mix title layouts"
2335 " with normal ones." << endl;
2338 } else if (was_title && !already_title) {
2339 ofs << "\\maketitle\n";
2341 already_title = true;
2345 if (layout.isEnvironment()) {
2346 par = par->TeXEnvironment(this, params, ofs, texrow);
2348 par = par->TeXOnePar(this, params, ofs, texrow, false);
2351 // It might be that we only have a title in this document
2352 if (was_title && !already_title) {
2353 ofs << "\\maketitle\n";
2359 bool Buffer::isLatex() const
2361 return textclasslist.TextClass(params.textclass).outputType() == LATEX;
2365 bool Buffer::isLinuxDoc() const
2367 return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC;
2371 bool Buffer::isLiterate() const
2373 return textclasslist.TextClass(params.textclass).outputType() == LITERATE;
2377 bool Buffer::isDocBook() const
2379 return textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2383 bool Buffer::isSGML() const
2385 return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC ||
2386 textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2390 void Buffer::sgmlOpenTag(ostream & os, Paragraph::depth_type depth,
2391 string const & latexname) const
2393 if (!latexname.empty() && latexname != "!-- --")
2394 os << "<!-- " << depth << " -->" << "<" << latexname << ">";
2395 //os << string(depth, ' ') << "<" << latexname << ">\n";
2399 void Buffer::sgmlCloseTag(ostream & os, Paragraph::depth_type depth,
2400 string const & latexname) const
2402 if (!latexname.empty() && latexname != "!-- --")
2403 os << "<!-- " << depth << " -->" << "</" << latexname << ">\n";
2404 //os << string(depth, ' ') << "</" << latexname << ">\n";
2408 void Buffer::makeLinuxDocFile(string const & fname, bool nice, bool body_only)
2410 ofstream ofs(fname.c_str());
2413 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2417 niceFile = nice; // this will be used by included files.
2419 LyXTextClass const & tclass =
2420 textclasslist.TextClass(params.textclass);
2422 LaTeXFeatures features(params, tclass.numLayouts());
2427 string top_element = textclasslist.LatexnameOfClass(params.textclass);
2430 string sgml_includedfiles=features.getIncludedFiles(fname);
2432 if (params.preamble.empty() && sgml_includedfiles.empty()) {
2433 ofs << "<!doctype linuxdoc system>\n\n";
2435 ofs << "<!doctype linuxdoc system [ "
2436 << params.preamble << sgml_includedfiles << " \n]>\n\n";
2439 if (params.options.empty())
2440 sgmlOpenTag(ofs, 0, top_element);
2442 string top = top_element;
2444 top += params.options;
2445 sgmlOpenTag(ofs, 0, top);
2449 ofs << "<!-- " << LYX_DOCVERSION
2450 << " created this file. For more info see http://www.lyx.org/"
2453 Paragraph::depth_type depth = 0; // paragraph depth
2454 Paragraph * par = paragraph;
2456 vector<string> environment_stack(5);
2459 LyXLayout const & style =
2460 textclasslist.Style(params.textclass,
2463 // treat <toc> as a special case for compatibility with old code
2464 if (par->getChar(0) == Paragraph::META_INSET) {
2465 Inset * inset = par->getInset(0);
2466 Inset::Code lyx_code = inset->lyxCode();
2467 if (lyx_code == Inset::TOC_CODE){
2468 string const temp = "toc";
2469 sgmlOpenTag(ofs, depth, temp);
2476 // environment tag closing
2477 for (; depth > par->params().depth(); --depth) {
2478 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2479 environment_stack[depth].erase();
2482 // write opening SGML tags
2483 switch (style.latextype) {
2484 case LATEX_PARAGRAPH:
2485 if (depth == par->params().depth()
2486 && !environment_stack[depth].empty()) {
2487 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2488 environment_stack[depth].erase();
2494 sgmlOpenTag(ofs, depth, style.latexname());
2499 linuxDocError(par, 0,
2500 _("Error : Wrong depth for"
2501 " LatexType Command.\n"));
2503 if (!environment_stack[depth].empty()){
2504 sgmlCloseTag(ofs, depth,
2505 environment_stack[depth]);
2509 environment_stack[depth].erase();
2510 sgmlOpenTag(ofs, depth, style.latexname());
2513 case LATEX_ENVIRONMENT:
2514 case LATEX_ITEM_ENVIRONMENT:
2515 if (depth == par->params().depth()
2516 && environment_stack[depth] != style.latexname()) {
2517 sgmlCloseTag(ofs, depth,
2518 environment_stack[depth]);
2519 environment_stack[depth].erase();
2521 if (depth < par->params().depth()) {
2522 depth = par->params().depth();
2523 environment_stack[depth].erase();
2525 if (environment_stack[depth] != style.latexname()) {
2527 sgmlOpenTag(ofs, depth, "p");
2529 sgmlOpenTag(ofs, depth, style.latexname());
2531 if (environment_stack.size() == depth + 1)
2532 environment_stack.push_back("!-- --");
2533 environment_stack[depth] = style.latexname();
2536 if (style.latexparam() == "CDATA")
2539 if (style.latextype == LATEX_ENVIRONMENT) break;
2541 if (style.labeltype == LABEL_MANUAL)
2546 sgmlOpenTag(ofs, depth + 1, item_name);
2549 sgmlOpenTag(ofs, depth, style.latexname());
2553 simpleLinuxDocOnePar(ofs, par, depth);
2558 // write closing SGML tags
2559 switch (style.latextype) {
2562 case LATEX_ENVIRONMENT:
2563 case LATEX_ITEM_ENVIRONMENT:
2564 if (style.latexparam() == "CDATA")
2568 sgmlCloseTag(ofs, depth, style.latexname());
2574 for (int i=depth; i >= 0; --i)
2575 sgmlCloseTag(ofs, depth, environment_stack[i]);
2579 sgmlCloseTag(ofs, 0, top_element);
2583 // How to check for successful close
2587 void Buffer::docBookHandleCaption(ostream & os, string & inner_tag,
2588 Paragraph::depth_type depth, int desc_on,
2591 Paragraph * tpar = par;
2593 && (tpar->layout != textclasslist.NumberOfLayout(params.textclass,
2595 tpar = tpar->next();
2598 tpar->layout == textclasslist.NumberOfLayout(params.textclass,
2599 "Caption").second) {
2600 sgmlOpenTag(os, depth + 1, inner_tag);
2602 simpleDocBookOnePar(os, extra_par, tpar,
2603 desc_on, depth + 2);
2604 sgmlCloseTag(os, depth+1, inner_tag);
2605 if (!extra_par.empty())
2611 // checks, if newcol chars should be put into this line
2612 // writes newline, if necessary.
2615 void linux_doc_line_break(ostream & os, string::size_type & colcount,
2616 string::size_type newcol)
2619 if (colcount > lyxrc.ascii_linelen) {
2621 colcount = newcol; // assume write after this call
2636 string tag_name(PAR_TAG const & pt) {
2638 case NONE: return "!-- --";
2639 case TT: return "tt";
2640 case SF: return "sf";
2641 case BF: return "bf";
2642 case IT: return "it";
2643 case SL: return "sl";
2644 case EM: return "em";
2651 void operator|=(PAR_TAG & p1, PAR_TAG const & p2)
2653 p1 = static_cast<PAR_TAG>(p1 | p2);
2658 void reset(PAR_TAG & p1, PAR_TAG const & p2)
2660 p1 = static_cast<PAR_TAG>( p1 & ~p2);
2668 // Handle internal paragraph parsing -- layout already processed.
2669 void Buffer::simpleLinuxDocOnePar(ostream & os,
2671 Paragraph::depth_type /*depth*/)
2673 LyXLayout const & style = textclasslist.Style(params.textclass,
2675 string::size_type char_line_count = 5; // Heuristic choice ;-)
2677 // gets paragraph main font
2680 if (style.labeltype == LABEL_MANUAL) {
2681 font_old = style.labelfont;
2684 font_old = style.font;
2688 LyXFont::FONT_FAMILY family_type = LyXFont::ROMAN_FAMILY;
2689 LyXFont::FONT_SERIES series_type = LyXFont::MEDIUM_SERIES;
2690 LyXFont::FONT_SHAPE shape_type = LyXFont::UP_SHAPE;
2693 stack < PAR_TAG > tag_state;
2694 // parsing main loop
2695 for (Paragraph::size_type i = 0; i < par->size(); ++i) {
2697 PAR_TAG tag_close = NONE;
2698 list < PAR_TAG > tag_open;
2700 LyXFont const font = par->getFont(params, i);
2702 if (font_old.family() != font.family()) {
2703 switch (family_type) {
2704 case LyXFont::SANS_FAMILY:
2707 case LyXFont::TYPEWRITER_FAMILY:
2714 family_type = font.family();
2716 switch (family_type) {
2717 case LyXFont::SANS_FAMILY:
2718 tag_open.push_back(SF);
2720 case LyXFont::TYPEWRITER_FAMILY:
2721 tag_open.push_back(TT);
2728 if (font_old.series() != font.series()) {
2729 switch (series_type) {
2730 case LyXFont::BOLD_SERIES:
2737 series_type = font.series();
2739 switch (series_type) {
2740 case LyXFont::BOLD_SERIES:
2741 tag_open.push_back(BF);
2749 if (font_old.shape() != font.shape()) {
2750 switch (shape_type) {
2751 case LyXFont::ITALIC_SHAPE:
2754 case LyXFont::SLANTED_SHAPE:
2761 shape_type = font.shape();
2763 switch (shape_type) {
2764 case LyXFont::ITALIC_SHAPE:
2765 tag_open.push_back(IT);
2767 case LyXFont::SLANTED_SHAPE:
2768 tag_open.push_back(SL);
2775 if (font_old.emph() != font.emph()) {
2776 if (font.emph() == LyXFont::ON) {
2777 tag_open.push_back(EM);
2786 list < PAR_TAG > temp;
2787 while(!tag_state.empty() && tag_close ) {
2788 PAR_TAG k = tag_state.top();
2790 os << "</" << tag_name(k) << ">";
2797 for(list< PAR_TAG >::const_iterator j = temp.begin();
2798 j != temp.end(); ++j) {
2800 os << "<" << tag_name(*j) << ">";
2803 for(list< PAR_TAG >::const_iterator j = tag_open.begin();
2804 j != tag_open.end(); ++j) {
2806 os << "<" << tag_name(*j) << ">";
2809 char c = par->getChar(i);
2811 if (c == Paragraph::META_INSET) {
2812 Inset * inset = par->getInset(i);
2813 inset->linuxdoc(this, os);
2820 font.latex() == LyXFont::ON ||
2822 style.latexparam() == "CDATA") {
2823 // "TeX"-Mode on == > SGML-Mode on.
2829 if (par->linuxDocConvertChar(c, sgml_string)
2830 && !style.free_spacing) {
2831 // in freespacing mode, spaces are
2832 // non-breaking characters
2833 if (desc_on) {// if char is ' ' then...
2836 linux_doc_line_break(os, char_line_count, 6);
2840 linux_doc_line_break(os, char_line_count, 1);
2845 char_line_count += sgml_string.length();
2851 while (!tag_state.empty()) {
2852 os << "</" << tag_name(tag_state.top()) << ">";
2856 // resets description flag correctly
2858 // <tag> not closed...
2859 linux_doc_line_break(os, char_line_count, 6);
2865 // Print an error message.
2866 void Buffer::linuxDocError(Paragraph * par, int pos,
2867 string const & message)
2869 // insert an error marker in text
2870 InsetError * new_inset = new InsetError(message);
2871 par->insertInset(pos, new_inset);
2875 void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
2877 ofstream ofs(fname.c_str());
2879 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2883 Paragraph * par = paragraph;
2885 niceFile = nice; // this will be used by Insetincludes.
2887 LyXTextClass const & tclass =
2888 textclasslist.TextClass(params.textclass);
2890 LaTeXFeatures features(params, tclass.numLayouts());
2895 string top_element = textclasslist.LatexnameOfClass(params.textclass);
2898 string sgml_includedfiles = features.getIncludedFiles(fname);
2900 ofs << "<!doctype " << top_element
2901 << " public \"-//OASIS//DTD DocBook V3.1//EN\"";
2903 if (params.preamble.empty() && sgml_includedfiles.empty())
2906 ofs << "\n [ " << params.preamble
2907 << sgml_includedfiles << " \n]>\n\n";
2910 string top = top_element;
2912 top += params.language->code();
2915 if (!params.options.empty()) {
2917 top += params.options;
2919 sgmlOpenTag(ofs, 0, top);
2921 ofs << "<!-- DocBook file was created by " << LYX_DOCVERSION
2922 << "\n See http://www.lyx.org/ for more information -->\n";
2924 vector<string> environment_stack(10);
2925 vector<string> environment_inner(10);
2926 vector<string> command_stack(10);
2928 bool command_flag = false;
2929 Paragraph::depth_type command_depth = 0;
2930 Paragraph::depth_type command_base = 0;
2931 Paragraph::depth_type cmd_depth = 0;
2932 Paragraph::depth_type depth = 0; // paragraph depth
2935 string command_name;
2941 int desc_on = 0; // description mode
2943 LyXLayout const & style =
2944 textclasslist.Style(params.textclass,
2947 // environment tag closing
2948 for (; depth > par->params().depth(); --depth) {
2949 if (environment_inner[depth] != "!-- --") {
2950 item_name = "listitem";
2951 sgmlCloseTag(ofs, command_depth + depth,
2953 if (environment_inner[depth] == "varlistentry")
2954 sgmlCloseTag(ofs, depth+command_depth,
2955 environment_inner[depth]);
2957 sgmlCloseTag(ofs, depth + command_depth,
2958 environment_stack[depth]);
2959 environment_stack[depth].erase();
2960 environment_inner[depth].erase();
2963 if (depth == par->params().depth()
2964 && environment_stack[depth] != style.latexname()
2965 && !environment_stack[depth].empty()) {
2966 if (environment_inner[depth] != "!-- --") {
2967 item_name= "listitem";
2968 sgmlCloseTag(ofs, command_depth+depth,
2970 if (environment_inner[depth] == "varlistentry")
2972 depth + command_depth,
2973 environment_inner[depth]);
2976 sgmlCloseTag(ofs, depth + command_depth,
2977 environment_stack[depth]);
2979 environment_stack[depth].erase();
2980 environment_inner[depth].erase();
2983 // Write opening SGML tags.
2984 switch (style.latextype) {
2985 case LATEX_PARAGRAPH:
2986 sgmlOpenTag(ofs, depth + command_depth,
2992 linuxDocError(par, 0,
2993 _("Error : Wrong depth for "
2994 "LatexType Command.\n"));
2996 command_name = style.latexname();
2998 sgmlparam = style.latexparam();
2999 c_params = split(sgmlparam, c_depth,'|');
3001 cmd_depth = lyx::atoi(c_depth);
3004 if (cmd_depth < command_base) {
3005 for (Paragraph::depth_type j = command_depth; j >= command_base; --j)
3006 sgmlCloseTag(ofs, j, command_stack[j]);
3007 command_depth = command_base = cmd_depth;
3008 } else if (cmd_depth <= command_depth) {
3009 for (int j = command_depth; j >= int(cmd_depth); --j)
3010 sgmlCloseTag(ofs, j, command_stack[j]);
3011 command_depth = cmd_depth;
3013 command_depth = cmd_depth;
3015 command_depth = command_base = cmd_depth;
3016 command_flag = true;
3018 if (command_stack.size() == command_depth + 1)
3019 command_stack.push_back(string());
3020 command_stack[command_depth] = command_name;
3022 // treat label as a special case for
3023 // more WYSIWYM handling.
3024 if (par->getChar(0) == Paragraph::META_INSET) {
3025 Inset * inset = par->getInset(0);
3026 Inset::Code lyx_code = inset->lyxCode();
3027 if (lyx_code == Inset::LABEL_CODE){
3028 command_name += " id=\"";
3029 command_name += (static_cast<InsetCommand *>(inset))->getContents();
3030 command_name += "\"";
3035 sgmlOpenTag(ofs, depth + command_depth, command_name);
3036 if (c_params.empty())
3037 item_name = "title";
3039 item_name = c_params;
3040 sgmlOpenTag(ofs, depth + 1 + command_depth, item_name);
3043 case LATEX_ENVIRONMENT:
3044 case LATEX_ITEM_ENVIRONMENT:
3045 if (depth < par->params().depth()) {
3046 depth = par->params().depth();
3047 environment_stack[depth].erase();
3050 if (environment_stack[depth] != style.latexname()) {
3051 if(environment_stack.size() == depth + 1) {
3052 environment_stack.push_back("!-- --");
3053 environment_inner.push_back("!-- --");
3055 environment_stack[depth] = style.latexname();
3056 environment_inner[depth] = "!-- --";
3057 sgmlOpenTag(ofs, depth + command_depth,
3058 environment_stack[depth]);
3060 if (environment_inner[depth] != "!-- --") {
3061 item_name= "listitem";
3063 command_depth + depth,
3065 if (environment_inner[depth] == "varlistentry")
3067 depth + command_depth,
3068 environment_inner[depth]);
3072 if (style.latextype == LATEX_ENVIRONMENT) {
3073 if (!style.latexparam().empty()) {
3074 if(style.latexparam() == "CDATA")
3077 sgmlOpenTag(ofs, depth + command_depth,
3078 style.latexparam());
3083 desc_on = (style.labeltype == LABEL_MANUAL);
3086 environment_inner[depth]= "varlistentry";
3088 environment_inner[depth]= "listitem";
3090 sgmlOpenTag(ofs, depth + 1 + command_depth,
3091 environment_inner[depth]);
3095 sgmlOpenTag(ofs, depth + 1 + command_depth,
3099 sgmlOpenTag(ofs, depth + 1 + command_depth,
3104 sgmlOpenTag(ofs, depth + command_depth,
3110 simpleDocBookOnePar(ofs, extra_par, par, desc_on,
3111 depth + 1 + command_depth);
3115 // write closing SGML tags
3116 switch (style.latextype) {
3118 if (c_params.empty())
3122 sgmlCloseTag(ofs, depth + command_depth, end_tag);
3124 case LATEX_ENVIRONMENT:
3125 if (!style.latexparam().empty()) {
3126 if(style.latexparam() == "CDATA")
3129 sgmlCloseTag(ofs, depth + command_depth,
3130 style.latexparam());
3133 case LATEX_ITEM_ENVIRONMENT:
3134 if (desc_on == 1) break;
3136 sgmlCloseTag(ofs, depth + 1 + command_depth, end_tag);
3138 case LATEX_PARAGRAPH:
3139 sgmlCloseTag(ofs, depth + command_depth, style.latexname());
3142 sgmlCloseTag(ofs, depth + command_depth, style.latexname());
3148 for (int d = depth; d >= 0; --d) {
3149 if (!environment_stack[depth].empty()) {
3150 if (environment_inner[depth] != "!-- --") {
3151 item_name = "listitem";
3152 sgmlCloseTag(ofs, command_depth + depth,
3154 if (environment_inner[depth] == "varlistentry")
3155 sgmlCloseTag(ofs, depth + command_depth,
3156 environment_inner[depth]);
3159 sgmlCloseTag(ofs, depth + command_depth,
3160 environment_stack[depth]);
3164 for (int j = command_depth; j >= 0 ; --j)
3165 if (!command_stack[j].empty())
3166 sgmlCloseTag(ofs, j, command_stack[j]);
3169 sgmlCloseTag(ofs, 0, top_element);
3172 // How to check for successful close
3176 void Buffer::simpleDocBookOnePar(ostream & os, string & extra,
3177 Paragraph * par, int & desc_on,
3178 Paragraph::depth_type depth) const
3180 bool emph_flag = false;
3182 LyXLayout const & style = textclasslist.Style(params.textclass,
3185 LyXFont font_old = style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
3187 int char_line_count = depth;
3188 //if (!style.free_spacing)
3189 // os << string(depth,' ');
3191 // parsing main loop
3192 for (Paragraph::size_type i = 0;
3193 i < par->size(); ++i) {
3194 LyXFont font = par->getFont(params, i);
3196 // handle <emphasis> tag
3197 if (font_old.emph() != font.emph()) {
3198 if (font.emph() == LyXFont::ON) {
3202 os << "</emphasis>";
3207 char c = par->getChar(i);
3209 if (c == Paragraph::META_INSET) {
3210 Inset * inset = par->getInset(i);
3211 std::ostringstream ost;
3212 inset->docBook(this, ost);
3213 string tmp_out = ost.str().c_str();
3216 // This code needs some explanation:
3217 // Two insets are treated specially
3218 // label if it is the first element in a command paragraph
3220 // graphics inside tables or figure floats can't go on
3221 // title (the equivalente in latex for this case is caption
3222 // and title should come first
3225 if (desc_on!= 3 || i!= 0) {
3226 if (!tmp_out.empty() && tmp_out[0] == '@') {
3228 extra += frontStrip(tmp_out, '@');
3230 os << frontStrip(tmp_out, '@');
3236 } else if (font.latex() == LyXFont::ON) {
3237 // "TeX"-Mode on ==> SGML-Mode on.
3244 if (par->linuxDocConvertChar(c, sgml_string)
3245 && !style.free_spacing) { // in freespacing
3247 // non-breaking characters
3251 os << "\n</term><listitem><para>";
3264 os << "</emphasis>";
3267 // resets description flag correctly
3269 // <term> not closed...
3272 if(style.free_spacing) os << '\n';
3276 // This should be enabled when the Chktex class is implemented. (Asger)
3277 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
3278 // Other flags: -wall -v0 -x
3279 int Buffer::runChktex()
3281 if (!users->text) return 0;
3283 users->owner()->prohibitInput();
3285 // get LaTeX-Filename
3286 string const name = getLatexName();
3287 string path = OnlyPath(filename);
3289 string const org_path = path;
3290 if (lyxrc.use_tempdir || (IsDirWriteable(path) < 1)) {
3294 Path p(path); // path to LaTeX file
3295 users->owner()->message(_("Running chktex..."));
3297 // Remove all error insets
3298 bool const removedErrorInsets = users->removeAutoInsets();
3300 // Generate the LaTeX file if neccessary
3301 makeLaTeXFile(name, org_path, false);
3304 Chktex chktex(lyxrc.chktex_command, name, filepath);
3305 int res = chktex.run(terr); // run chktex
3308 WriteAlert(_("chktex did not work!"),
3309 _("Could not run with file:"), name);
3310 } else if (res > 0) {
3311 // Insert all errors as errors boxes
3312 users->insertErrors(terr);
3315 // if we removed error insets before we ran chktex or if we inserted
3316 // error insets after we ran chktex, this must be run:
3317 if (removedErrorInsets || res){
3319 users->fitCursor(users->text);
3321 users->owner()->allowInput();
3327 void Buffer::validate(LaTeXFeatures & features) const
3329 Paragraph * par = paragraph;
3330 LyXTextClass const & tclass =
3331 textclasslist.TextClass(params.textclass);
3333 // AMS Style is at document level
3335 features.amsstyle = (params.use_amsmath ||
3336 tclass.provides(LyXTextClass::amsmath));
3339 // We don't use "lyxerr.debug" because of speed. (Asger)
3340 if (lyxerr.debugging(Debug::LATEX))
3341 lyxerr << "Paragraph: " << par << endl;
3343 // Now just follow the list of paragraphs and run
3344 // validate on each of them.
3345 par->validate(features);
3347 // and then the next paragraph
3351 // the bullet shapes are buffer level not paragraph level
3352 // so they are tested here
3353 for (int i = 0; i < 4; ++i) {
3354 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
3355 int const font = params.user_defined_bullets[i].getFont();
3357 int const c = params
3358 .user_defined_bullets[i]
3365 features.latexsym = true;
3367 } else if (font == 1) {
3368 features.amssymb = true;
3369 } else if ((font >= 2 && font <= 5)) {
3370 features.pifont = true;
3375 if (lyxerr.debugging(Debug::LATEX)) {
3376 features.showStruct();
3381 void Buffer::setPaperStuff()
3383 params.papersize = BufferParams::PAPER_DEFAULT;
3384 char const c1 = params.paperpackage;
3385 if (c1 == BufferParams::PACKAGE_NONE) {
3386 char const c2 = params.papersize2;
3387 if (c2 == BufferParams::VM_PAPER_USLETTER)
3388 params.papersize = BufferParams::PAPER_USLETTER;
3389 else if (c2 == BufferParams::VM_PAPER_USLEGAL)
3390 params.papersize = BufferParams::PAPER_LEGALPAPER;
3391 else if (c2 == BufferParams::VM_PAPER_USEXECUTIVE)
3392 params.papersize = BufferParams::PAPER_EXECUTIVEPAPER;
3393 else if (c2 == BufferParams::VM_PAPER_A3)
3394 params.papersize = BufferParams::PAPER_A3PAPER;
3395 else if (c2 == BufferParams::VM_PAPER_A4)
3396 params.papersize = BufferParams::PAPER_A4PAPER;
3397 else if (c2 == BufferParams::VM_PAPER_A5)
3398 params.papersize = BufferParams::PAPER_A5PAPER;
3399 else if ((c2 == BufferParams::VM_PAPER_B3) || (c2 == BufferParams::VM_PAPER_B4) ||
3400 (c2 == BufferParams::VM_PAPER_B5))
3401 params.papersize = BufferParams::PAPER_B5PAPER;
3402 } else if ((c1 == BufferParams::PACKAGE_A4) || (c1 == BufferParams::PACKAGE_A4WIDE) ||
3403 (c1 == BufferParams::PACKAGE_WIDEMARGINSA4))
3404 params.papersize = BufferParams::PAPER_A4PAPER;
3408 // This function should be in Buffer because it's a buffer's property (ale)
3409 string const Buffer::getIncludeonlyList(char delim)
3412 for (inset_iterator it = inset_iterator_begin();
3413 it != inset_iterator_end(); ++it) {
3414 if ((*it)->lyxCode() == Inset::INCLUDE_CODE) {
3415 InsetInclude * insetinc =
3416 static_cast<InsetInclude *>(*it);
3417 if (insetinc->isIncludeOnly()) {
3420 lst += insetinc->getRelFileBaseName();
3424 lyxerr[Debug::INFO] << "Includeonly(" << lst << ')' << endl;
3429 vector<string> const Buffer::getLabelList()
3431 /// if this is a child document and the parent is already loaded
3432 /// Use the parent's list instead [ale990407]
3433 if (!params.parentname.empty()
3434 && bufferlist.exists(params.parentname)) {
3435 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3437 return tmp->getLabelList();
3440 vector<string> label_list;
3441 for (inset_iterator it = inset_iterator_begin();
3442 it != inset_iterator_end(); ++it) {
3443 vector<string> const l = (*it)->getLabelList();
3444 label_list.insert(label_list.end(), l.begin(), l.end());
3450 Buffer::Lists const Buffer::getLists() const
3453 Paragraph * par = paragraph;
3455 LyXTextClassList::size_type cap;
3456 boost::tie(found, cap) = textclasslist
3457 .NumberOfLayout(params.textclass, "Caption");
3460 char const labeltype =
3461 textclasslist.Style(params.textclass,
3462 par->getLayout()).labeltype;
3464 if (labeltype >= LABEL_COUNTER_CHAPTER
3465 && labeltype <= LABEL_COUNTER_CHAPTER + params.tocdepth) {
3466 // insert this into the table of contents
3467 SingleList & item = l["TOC"];
3470 textclasslist.TextClass(params.textclass).maxcounter());
3471 item.push_back(TocItem(par, depth, par->asString(this, true)));
3473 // For each paragrph, traverse its insets and look for
3477 Paragraph::inset_iterator it =
3478 par->inset_iterator_begin();
3479 Paragraph::inset_iterator end =
3480 par->inset_iterator_end();
3482 for (; it != end; ++it) {
3483 if ((*it)->lyxCode() == Inset::FLOAT_CODE) {
3485 static_cast<InsetFloat*>(*it);
3487 string const type = il->type();
3489 // Now find the caption in the float...
3490 // We now tranverse the paragraphs of
3492 Paragraph * tmp = il->inset.paragraph();
3494 if (tmp->layout == cap) {
3495 SingleList & item = l[type];
3497 tostr(item.size()+1) + ". " + tmp->asString(this, false);
3498 item.push_back(TocItem(tmp, 0 , str));
3505 lyxerr << "caption not found" << endl;
3514 // This is also a buffer property (ale)
3515 vector<pair<string, string> > const Buffer::getBibkeyList()
3517 /// if this is a child document and the parent is already loaded
3518 /// Use the parent's list instead [ale990412]
3519 if (!params.parentname.empty() && bufferlist.exists(params.parentname)) {
3520 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3522 return tmp->getBibkeyList();
3525 vector<pair<string, string> > keys;
3526 Paragraph * par = paragraph;
3529 keys.push_back(pair<string, string>(par->bibkey->getContents(),
3530 par->asString(this, false)));
3534 // Might be either using bibtex or a child has bibliography
3536 for (inset_iterator it = inset_iterator_begin();
3537 it != inset_iterator_end(); ++it) {
3538 // Search for Bibtex or Include inset
3539 if ((*it)->lyxCode() == Inset::BIBTEX_CODE) {
3540 vector<pair<string,string> > tmp =
3541 static_cast<InsetBibtex*>(*it)->getKeys(this);
3542 keys.insert(keys.end(), tmp.begin(), tmp.end());
3543 } else if ((*it)->lyxCode() == Inset::INCLUDE_CODE) {
3544 vector<pair<string,string> > const tmp =
3545 static_cast<InsetInclude*>(*it)->getKeys();
3546 keys.insert(keys.end(), tmp.begin(), tmp.end());
3555 bool Buffer::isDepClean(string const & name) const
3557 DEPCLEAN * item = dep_clean;
3558 while (item && item->master != name)
3560 if (!item) return true;
3565 void Buffer::markDepClean(string const & name)
3568 dep_clean = new DEPCLEAN;
3569 dep_clean->clean = true;
3570 dep_clean->master = name;
3571 dep_clean->next = 0;
3573 DEPCLEAN * item = dep_clean;
3574 while (item && item->master != name)
3579 item = new DEPCLEAN;
3581 item->master = name;
3588 bool Buffer::dispatch(string const & command)
3590 // Split command string into command and argument
3592 string line = frontStrip(command);
3593 string const arg = strip(frontStrip(split(line, cmd, ' ')));
3595 return dispatch(lyxaction.LookupFunc(cmd), arg);
3599 bool Buffer::dispatch(int action, string const & argument)
3601 bool dispatched = true;
3604 Exporter::Export(this, argument, false);
3614 void Buffer::resizeInsets(BufferView * bv)
3616 /// then remove all LyXText in text-insets
3617 Paragraph * par = paragraph;
3618 for (; par; par = par->next()) {
3619 par->resizeInsetsLyXText(bv);
3624 void Buffer::redraw()
3627 users->fitCursor(users->text);
3631 void Buffer::changeLanguage(Language const * from, Language const * to)
3634 Paragraph * par = paragraph;
3636 par->changeLanguage(params, from, to);
3642 bool Buffer::isMultiLingual()
3644 Paragraph * par = paragraph;
3646 if (par->isMultiLingual(params))
3654 Buffer::inset_iterator::inset_iterator(Paragraph * paragraph,
3655 Paragraph::size_type pos)
3658 it = par->InsetIterator(pos);
3659 if (it == par->inset_iterator_end()) {
3666 void Buffer::inset_iterator::setParagraph()
3669 it = par->inset_iterator_begin();
3670 if (it != par->inset_iterator_end())
3675 // We maintain an invariant that whenever par = 0 then it = 0
3679 Inset * Buffer::getInsetFromID(int id_arg) const
3681 for (inset_iterator it = inset_const_iterator_begin();
3682 it != inset_const_iterator_end(); ++it)
3684 if ((*it)->id() == id_arg)
3686 Inset * in = (*it)->getInsetFromID(id_arg);
3694 Paragraph * Buffer::getParFromID(int id) const
3696 if (id < 0) return 0;
3697 Paragraph * par = paragraph;
3699 if (par->id() == id) {
3702 Paragraph * tmp = par->getParFromID(id);