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/insetnote.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/insettabular.h"
79 #include "insets/insettheorem.h"
80 #include "insets/insetlist.h"
82 #include "insets/insetcaption.h"
83 #include "insets/insetfloatlist.h"
84 #include "support/textutils.h"
85 #include "support/filetools.h"
86 #include "support/path.h"
87 #include "support/os.h"
92 #include "LaTeXFeatures.h"
93 #include "support/syscall.h"
94 #include "support/lyxlib.h"
95 #include "support/FileInfo.h"
96 #include "support/lyxmanip.h"
100 #include "lyx_gui_misc.h" // WarnReadonly()
101 #include "frontends/Dialogs.h"
102 #include "encoding.h"
103 #include "exporter.h"
104 #include "Lsstream.h"
105 #include "converter.h"
106 #include "BufferView.h"
107 #include "ParagraphParameters.h"
108 #include "iterators.h"
118 using std::make_pair;
126 // all these externs should eventually be removed.
127 extern BufferList bufferlist;
129 extern LyXAction lyxaction;
133 const int LYX_FORMAT = 220;
137 extern int tex_code_break_column;
140 Buffer::Buffer(string const & file, bool ronly)
142 lyxerr[Debug::INFO] << "Buffer::Buffer()" << endl;
144 filepath = OnlyPath(file);
153 if (read_only || (lyxrc.use_tempdir)) {
154 tmppath = CreateBufferTmpDir();
155 } else tmppath.erase();
161 lyxerr[Debug::INFO] << "Buffer::~Buffer()" << endl;
162 // here the buffer should take care that it is
163 // saved properly, before it goes into the void.
165 // make sure that views using this buffer
170 if (!tmppath.empty()) {
171 DestroyBufferTmpDir(tmppath);
174 Paragraph * par = paragraph;
177 tmppar = par->next();
185 string const Buffer::getLatexName(bool no_path) const
187 string name = ChangeExtension(MakeLatexName(filename), ".tex");
189 return OnlyFilename(name);
195 pair<Buffer::LogType, string> const Buffer::getLogName(void) const
197 string const filename = getLatexName(false);
199 if (filename.empty())
200 return make_pair(Buffer::latexlog, string());
202 string path = OnlyPath(filename);
204 if (lyxrc.use_tempdir || !IsDirWriteable(path))
207 string const fname = AddName(path,
208 OnlyFilename(ChangeExtension(filename,
211 AddName(path, OnlyFilename(
212 ChangeExtension(filename,
213 formats.extension("literate") + ".out")));
215 // If no Latex log or Build log is newer, show Build log
217 FileInfo const f_fi(fname);
218 FileInfo const b_fi(bname);
221 (!f_fi.exist() || f_fi.getModificationTime() < b_fi.getModificationTime())) {
222 lyxerr[Debug::FILES] << "Log name calculated as : " << bname << endl;
223 return make_pair(Buffer::buildlog, bname);
225 lyxerr[Debug::FILES] << "Log name calculated as : " << fname << endl;
226 return make_pair(Buffer::latexlog, fname);
230 void Buffer::setReadonly(bool flag)
232 if (read_only != flag) {
235 users->owner()->getDialogs()->updateBufferDependent(false);
238 WarnReadonly(filename);
243 /// Update window titles of all users
244 // Should work on a list
245 void Buffer::updateTitles() const
247 if (users) users->owner()->updateWindowTitle();
251 /// Reset autosave timer of all users
252 // Should work on a list
253 void Buffer::resetAutosaveTimers() const
255 if (users) users->owner()->resetAutosaveTimer();
259 void Buffer::setFileName(string const & newfile)
261 filename = MakeAbsPath(newfile);
262 filepath = OnlyPath(filename);
263 setReadonly(IsFileWriteable(filename) == 0);
268 // We'll remove this later. (Lgb)
271 string last_inset_read;
273 #ifndef NO_COMPABILITY
276 ErtComp() : active(false), in_tabular(false) {
283 std::stack<ErtComp> ert_stack;
287 #warning And _why_ is this here? (Lgb)
293 // candidate for move to BufferView
294 // (at least some parts in the beginning of the func)
297 // changed to be public and have one parameter
298 // if par = 0 normal behavior
299 // else insert behavior
300 // Returns false if "\the_end" is not read for formats >= 2.13. (Asger)
301 bool Buffer::readLyXformat2(LyXLex & lex, Paragraph * par)
304 #ifndef NO_COMPABILITY
305 ert_comp.contents.erase();
306 ert_comp.active = false;
307 ert_comp.in_tabular = false;
310 Paragraph::depth_type depth = 0;
311 bool the_end_read = false;
313 Paragraph * first_par = 0;
314 LyXFont font(LyXFont::ALL_INHERIT, params.language);
315 if (file_format < 216 && params.language->lang() == "hebrew")
316 font.setLanguage(default_language);
321 // We are inserting into an existing document
322 users->text->breakParagraph(users);
323 first_par = users->text->firstParagraph();
326 // We don't want to adopt the parameters from the
327 // document we insert, so we skip until the text begins:
330 string const pretoken = lex.getString();
331 if (pretoken == "\\layout") {
332 lex.pushToken(pretoken);
340 string const token = lex.getString();
342 if (token.empty()) continue;
344 lyxerr[Debug::PARSER] << "Handling token: `"
345 << token << "'" << endl;
348 parseSingleLyXformat2Token(lex, par, first_par,
356 paragraph = first_par;
358 if (unknown_layouts > 0) {
359 string s = _("Couldn't set the layout for ");
360 if (unknown_layouts == 1) {
361 s += _("one paragraph");
363 s += tostr(unknown_layouts);
364 s += _(" paragraphs");
366 WriteAlert(_("Textclass Loading Error!"), s,
367 _("When reading " + fileName()));
374 #ifndef NO_COMPABILITY
375 void Buffer::insertErtContents(Paragraph * par, int & pos,
376 LyXFont const & font, bool set_inactive)
378 if (!ert_comp.contents.empty()) {
379 lyxerr[Debug::INSETS] << "ERT contents:\n"
380 << ert_comp.contents << endl;
381 Inset * inset = new InsetERT(ert_comp.contents, true);
382 par->insertInset(pos++, inset, font);
383 ert_comp.contents.erase();
386 ert_comp.active = false;
393 Buffer::parseSingleLyXformat2Token(LyXLex & lex, Paragraph *& par,
394 Paragraph *& first_par,
395 string const & token, int & pos,
396 Paragraph::depth_type & depth,
400 bool the_end_read = false;
401 #ifndef NO_COMPABILITY
402 #ifndef NO_PEXTRA_REALLY
403 // This is super temporary but is needed to get the compability
404 // mode for minipages work correctly together with new tabulars.
405 static int call_depth;
407 bool checkminipage = false;
408 static Paragraph * minipar;
409 static Paragraph * parBeforeMinipage;
412 if (token[0] != '\\') {
413 #ifndef NO_COMPABILITY
414 if (ert_comp.active) {
415 ert_comp.contents += token;
418 for (string::const_iterator cit = token.begin();
419 cit != token.end(); ++cit) {
420 par->insertChar(pos, (*cit), font);
423 #ifndef NO_COMPABILITY
426 } else if (token == "\\i") {
427 Inset * inset = new InsetLatexAccent;
428 inset->read(this, lex);
429 par->insertInset(pos, inset, font);
431 } else if (token == "\\layout") {
432 #ifndef NO_COMPABILITY
433 ert_comp.in_tabular = false;
435 insertErtContents(par, pos, font);
438 string const layoutname = lex.getString();
439 pair<bool, LyXTextClass::LayoutList::size_type> pp
440 = textclasslist.NumberOfLayout(params.textclass,
443 #ifndef NO_COMPABILITY
444 if (compare_no_case(layoutname, "latex") == 0) {
445 ert_comp.active = true;
449 // The is the compability reading of layout caption.
450 // It can be removed in LyX version 1.3.0. (Lgb)
451 if (compare_no_case(layoutname, "caption") == 0) {
452 // We expect that the par we are now working on is
453 // really inside a InsetText inside a InsetFloat.
454 // We also know that captions can only be
455 // one paragraph. (Lgb)
457 // We should now read until the next "\layout"
459 // This is probably not good enough, what if the
460 // caption is the last par in the document (Lgb)
461 istream & ist = lex.getStream();
467 if (prefixIs(line, "\\layout")) {
471 if (prefixIs(line, "\\begin_inset"))
473 if (prefixIs(line, "\\end_inset")) {
484 // Now we should have the whole layout in ss
485 // we should now be able to give this to the
487 ss << "\\end_inset\n";
489 // This seems like a bug in stringstream.
490 // We really should be able to use ss
492 istringstream is(ss.str());
494 tmplex.setStream(is);
495 Inset * inset = new InsetCaption;
496 inset->Read(this, tmplex);
497 par->InsertInset(pos, inset, font);
504 par = new Paragraph(par);
508 par->layout = pp.second;
509 #ifndef NO_COMPABILITY
510 } else if (ert_comp.active) {
515 // use default layout "Standard" (0)
518 string const s = _("Layout had to be changed from\n")
519 + layoutname + _(" to ")
520 + textclasslist.NameOfLayout(params.textclass, par->layout);
521 InsetError * new_inset = new InsetError(s);
522 par->insertInset(0, new_inset);
524 // Test whether the layout is obsolete.
525 LyXLayout const & layout =
526 textclasslist.Style(params.textclass,
528 if (!layout.obsoleted_by().empty())
529 par->layout = textclasslist
530 .NumberOfLayout(params.textclass,
531 layout.obsoleted_by())
533 par->params().depth(depth);
534 font = LyXFont(LyXFont::ALL_INHERIT, params.language);
535 if (file_format < 216
536 && params.language->lang() == "hebrew")
537 font.setLanguage(default_language);
542 #ifndef NO_COMPABILITY
543 } else if (token == "\\begin_float") {
544 insertErtContents(par, pos, font);
545 //insertErtContents(par, pos, font, false);
546 //ert_stack.push(ert_comp);
547 //ert_comp = ErtComp();
549 // This is the compability reader. It can be removed in
550 // LyX version 1.3.0. (Lgb)
552 string const tmptok = lex.getString();
553 //lyxerr << "old float: " << tmptok << endl;
556 stringstream old_float;
558 if (tmptok == "footnote") {
559 inset = new InsetFoot;
560 old_float << "collapsed true\n";
561 } else if (tmptok == "margin") {
562 inset = new InsetMarginal;
563 old_float << "collapsed true\n";
564 } else if (tmptok == "fig") {
565 inset = new InsetFloat("figure");
566 old_float << "placement htbp\n"
568 << "collapsed false\n";
569 } else if (tmptok == "tab") {
570 inset = new InsetFloat("table");
571 old_float << "placement htbp\n"
573 << "collapsed false\n";
574 } else if (tmptok == "alg") {
575 inset = new InsetFloat("algorithm");
576 old_float << "placement htbp\n"
578 << "collapsed false\n";
579 } else if (tmptok == "wide-fig") {
580 inset = new InsetFloat("figure");
581 //InsetFloat * tmp = new InsetFloat("figure");
584 old_float << "placement htbp\n"
586 << "collapsed false\n";
587 } else if (tmptok == "wide-tab") {
588 inset = new InsetFloat("table");
589 //InsetFloat * tmp = new InsetFloat("table");
592 old_float << "placement htbp\n"
594 << "collapsed false\n";
598 #ifndef NO_PEXTRA_REALLY
601 return false; // no end read yet
604 // Here we need to check for \end_deeper and handle that
605 // before we do the footnote parsing.
606 // This _is_ a hack! (Lgb)
609 string const tmp = lex.getString();
610 if (tmp == "\\end_deeper") {
611 //lyxerr << "\\end_deeper caught!" << endl;
613 lex.printError("\\end_deeper: "
614 "depth is already null");
619 old_float << tmp << ' ';
624 old_float << lex.getLongString("\\end_float")
625 << "\n\\end_inset\n";
626 //lyxerr << "Float Body:\n" << old_float.str() << endl;
627 // That this does not work seems like a bug
628 // in stringstream. (Lgb)
629 istringstream istr(old_float.str());
631 nylex.setStream(istr);
632 inset->read(this, nylex);
633 par->insertInset(pos, inset, font);
635 insertErtContents(par, pos, font);
637 } else if (token == "\\begin_deeper") {
639 } else if (token == "\\end_deeper") {
641 lex.printError("\\end_deeper: "
642 "depth is already null");
646 } else if (token == "\\begin_preamble") {
647 params.readPreamble(lex);
648 } else if (token == "\\textclass") {
650 pair<bool, LyXTextClassList::size_type> pp =
651 textclasslist.NumberOfClass(lex.getString());
653 params.textclass = pp.second;
655 WriteAlert(string(_("Textclass error")),
656 string(_("The document uses an unknown textclass \"")) +
657 lex.getString() + string("\"."),
658 string(_("LyX will not be able to produce output correctly.")));
659 params.textclass = 0;
661 if (!textclasslist.Load(params.textclass)) {
662 // if the textclass wasn't loaded properly
663 // we need to either substitute another
664 // or stop loading the file.
665 // I can substitute but I don't see how I can
666 // stop loading... ideas?? ARRae980418
667 WriteAlert(_("Textclass Loading Error!"),
668 string(_("Can't load textclass ")) +
669 textclasslist.NameOfClass(params.textclass),
670 _("-- substituting default"));
671 params.textclass = 0;
673 } else if (token == "\\options") {
675 params.options = lex.getString();
676 } else if (token == "\\language") {
677 params.readLanguage(lex);
678 } else if (token == "\\fontencoding") {
680 } else if (token == "\\inputencoding") {
682 params.inputenc = lex.getString();
683 } else if (token == "\\graphics") {
684 params.readGraphicsDriver(lex);
685 } else if (token == "\\fontscheme") {
687 params.fonts = lex.getString();
688 } else if (token == "\\noindent") {
689 par->params().noindent(true);
690 } else if (token == "\\fill_top") {
691 par->params().spaceTop(VSpace(VSpace::VFILL));
692 } else if (token == "\\fill_bottom") {
693 par->params().spaceBottom(VSpace(VSpace::VFILL));
694 } else if (token == "\\line_top") {
695 par->params().lineTop(true);
696 } else if (token == "\\line_bottom") {
697 par->params().lineBottom(true);
698 } else if (token == "\\pagebreak_top") {
699 par->params().pagebreakTop(true);
700 } else if (token == "\\pagebreak_bottom") {
701 par->params().pagebreakBottom(true);
702 } else if (token == "\\start_of_appendix") {
703 par->params().startOfAppendix(true);
704 } else if (token == "\\paragraph_separation") {
705 int tmpret = lex.findToken(string_paragraph_separation);
706 if (tmpret == -1) ++tmpret;
707 if (tmpret != LYX_LAYOUT_DEFAULT)
708 params.paragraph_separation =
709 static_cast<BufferParams::PARSEP>(tmpret);
710 } else if (token == "\\defskip") {
712 params.defskip = VSpace(lex.getString());
713 } else if (token == "\\epsfig") { // obsolete
714 // Indeed it is obsolete, but we HAVE to be backwards
715 // compatible until 0.14, because otherwise all figures
716 // in existing documents are irretrivably lost. (Asger)
717 params.readGraphicsDriver(lex);
718 } else if (token == "\\quotes_language") {
719 int tmpret = lex.findToken(string_quotes_language);
720 if (tmpret == -1) ++tmpret;
721 if (tmpret != LYX_LAYOUT_DEFAULT) {
722 InsetQuotes::quote_language tmpl =
723 InsetQuotes::EnglishQ;
726 tmpl = InsetQuotes::EnglishQ;
729 tmpl = InsetQuotes::SwedishQ;
732 tmpl = InsetQuotes::GermanQ;
735 tmpl = InsetQuotes::PolishQ;
738 tmpl = InsetQuotes::FrenchQ;
741 tmpl = InsetQuotes::DanishQ;
744 params.quotes_language = tmpl;
746 } else if (token == "\\quotes_times") {
748 switch (lex.getInteger()) {
750 params.quotes_times = InsetQuotes::SingleQ;
753 params.quotes_times = InsetQuotes::DoubleQ;
756 } else if (token == "\\papersize") {
757 int tmpret = lex.findToken(string_papersize);
761 params.papersize2 = tmpret;
762 } else if (token == "\\paperpackage") {
763 int tmpret = lex.findToken(string_paperpackages);
766 params.paperpackage = BufferParams::PACKAGE_NONE;
768 params.paperpackage = tmpret;
769 } else if (token == "\\use_geometry") {
771 params.use_geometry = lex.getInteger();
772 } else if (token == "\\use_amsmath") {
774 params.use_amsmath = lex.getInteger();
775 } else if (token == "\\use_natbib") {
777 params.use_natbib = lex.getInteger();
778 } else if (token == "\\use_numerical_citations") {
780 params.use_numerical_citations = lex.getInteger();
781 } else if (token == "\\paperorientation") {
782 int tmpret = lex.findToken(string_orientation);
783 if (tmpret == -1) ++tmpret;
784 if (tmpret != LYX_LAYOUT_DEFAULT)
785 params.orientation = static_cast<BufferParams::PAPER_ORIENTATION>(tmpret);
786 } else if (token == "\\paperwidth") {
788 params.paperwidth = lex.getString();
789 } else if (token == "\\paperheight") {
791 params.paperheight = lex.getString();
792 } else if (token == "\\leftmargin") {
794 params.leftmargin = lex.getString();
795 } else if (token == "\\topmargin") {
797 params.topmargin = lex.getString();
798 } else if (token == "\\rightmargin") {
800 params.rightmargin = lex.getString();
801 } else if (token == "\\bottommargin") {
803 params.bottommargin = lex.getString();
804 } else if (token == "\\headheight") {
806 params.headheight = lex.getString();
807 } else if (token == "\\headsep") {
809 params.headsep = lex.getString();
810 } else if (token == "\\footskip") {
812 params.footskip = lex.getString();
813 } else if (token == "\\paperfontsize") {
815 params.fontsize = strip(lex.getString());
816 } else if (token == "\\papercolumns") {
818 params.columns = lex.getInteger();
819 } else if (token == "\\papersides") {
821 switch (lex.getInteger()) {
823 case 1: params.sides = LyXTextClass::OneSide; break;
824 case 2: params.sides = LyXTextClass::TwoSides; break;
826 } else if (token == "\\paperpagestyle") {
828 params.pagestyle = strip(lex.getString());
829 } else if (token == "\\bullet") {
831 int const index = lex.getInteger();
833 int temp_int = lex.getInteger();
834 params.user_defined_bullets[index].setFont(temp_int);
835 params.temp_bullets[index].setFont(temp_int);
837 temp_int = lex.getInteger();
838 params.user_defined_bullets[index].setCharacter(temp_int);
839 params.temp_bullets[index].setCharacter(temp_int);
841 temp_int = lex.getInteger();
842 params.user_defined_bullets[index].setSize(temp_int);
843 params.temp_bullets[index].setSize(temp_int);
845 string const temp_str = lex.getString();
846 if (temp_str != "\\end_bullet") {
847 // this element isn't really necessary for
848 // parsing but is easier for humans
849 // to understand bullets. Put it back and
850 // set a debug message?
851 lex.printError("\\end_bullet expected, got" + temp_str);
852 //how can I put it back?
854 } else if (token == "\\bulletLaTeX") {
856 int const index = lex.getInteger();
858 string temp_str = lex.getString();
860 while (temp_str != "\\end_bullet") {
861 // this loop structure is needed when user
862 // enters an empty string since the first
863 // thing returned will be the \\end_bullet
865 // if the LaTeX entry has spaces. Each element
866 // therefore needs to be read in turn
869 temp_str = lex.getString();
871 params.user_defined_bullets[index].setText(sum_str);
872 params.temp_bullets[index].setText(sum_str);
873 } else if (token == "\\secnumdepth") {
875 params.secnumdepth = lex.getInteger();
876 } else if (token == "\\tocdepth") {
878 params.tocdepth = lex.getInteger();
879 } else if (token == "\\spacing") {
881 string const tmp = strip(lex.getString());
882 Spacing::Space tmp_space = Spacing::Default;
884 if (tmp == "single") {
885 tmp_space = Spacing::Single;
886 } else if (tmp == "onehalf") {
887 tmp_space = Spacing::Onehalf;
888 } else if (tmp == "double") {
889 tmp_space = Spacing::Double;
890 } else if (tmp == "other") {
892 tmp_space = Spacing::Other;
893 tmp_val = lex.getFloat();
895 lex.printError("Unknown spacing token: '$$Token'");
897 // Small hack so that files written with klyx will be
900 par->params().spacing(Spacing(tmp_space, tmp_val));
902 params.spacing.set(tmp_space, tmp_val);
904 } else if (token == "\\paragraph_spacing") {
906 string const tmp = strip(lex.getString());
907 if (tmp == "single") {
908 par->params().spacing(Spacing(Spacing::Single));
909 } else if (tmp == "onehalf") {
910 par->params().spacing(Spacing(Spacing::Onehalf));
911 } else if (tmp == "double") {
912 par->params().spacing(Spacing(Spacing::Double));
913 } else if (tmp == "other") {
915 par->params().spacing(Spacing(Spacing::Other,
918 lex.printError("Unknown spacing token: '$$Token'");
920 } else if (token == "\\float_placement") {
922 params.float_placement = lex.getString();
923 } else if (token == "\\family") {
925 font.setLyXFamily(lex.getString());
926 } else if (token == "\\series") {
928 font.setLyXSeries(lex.getString());
929 } else if (token == "\\shape") {
931 font.setLyXShape(lex.getString());
932 } else if (token == "\\size") {
934 font.setLyXSize(lex.getString());
935 #ifndef NO_COMPABILITY
936 } else if (token == "\\latex") {
938 string const tok = lex.getString();
939 if (tok == "no_latex") {
941 insertErtContents(par, pos, font);
942 } else if (tok == "latex") {
943 ert_comp.active = true;
944 } else if (tok == "default") {
946 insertErtContents(par, pos, font);
948 lex.printError("Unknown LaTeX font flag "
952 } else if (token == "\\lang") {
954 string const tok = lex.getString();
955 Language const * lang = languages.getLanguage(tok);
957 font.setLanguage(lang);
959 font.setLanguage(params.language);
960 lex.printError("Unknown language `$$Token'");
962 } else if (token == "\\numeric") {
964 font.setNumber(font.setLyXMisc(lex.getString()));
965 } else if (token == "\\emph") {
967 font.setEmph(font.setLyXMisc(lex.getString()));
968 } else if (token == "\\bar") {
970 string const tok = lex.getString();
971 // This is dirty, but gone with LyX3. (Asger)
973 font.setUnderbar(LyXFont::ON);
974 else if (tok == "no")
975 font.setUnderbar(LyXFont::OFF);
976 else if (tok == "default")
977 font.setUnderbar(LyXFont::INHERIT);
979 lex.printError("Unknown bar font flag "
981 } else if (token == "\\noun") {
983 font.setNoun(font.setLyXMisc(lex.getString()));
984 } else if (token == "\\color") {
986 font.setLyXColor(lex.getString());
987 } else if (token == "\\align") {
988 int tmpret = lex.findToken(string_align);
989 if (tmpret == -1) ++tmpret;
990 if (tmpret != LYX_LAYOUT_DEFAULT) { // tmpret != 99 ???
991 int const tmpret2 = int(pow(2.0, tmpret));
992 //lyxerr << "Tmpret2 = " << tmpret2 << endl;
993 par->params().align(LyXAlignment(tmpret2));
995 } else if (token == "\\added_space_top") {
997 par->params().spaceTop(VSpace(lex.getString()));
998 } else if (token == "\\added_space_bottom") {
1000 par->params().spaceBottom(VSpace(lex.getString()));
1001 #ifndef NO_COMPABILITY
1002 #ifndef NO_PEXTRA_REALLY
1003 } else if (token == "\\pextra_type") {
1005 par->params().pextraType(lex.getInteger());
1006 } else if (token == "\\pextra_width") {
1008 par->params().pextraWidth(lex.getString());
1009 } else if (token == "\\pextra_widthp") {
1011 par->params().pextraWidthp(lex.getString());
1012 } else if (token == "\\pextra_alignment") {
1014 par->params().pextraAlignment(lex.getInteger());
1015 } else if (token == "\\pextra_hfill") {
1017 par->params().pextraHfill(lex.getInteger());
1018 } else if (token == "\\pextra_start_minipage") {
1020 par->params().pextraStartMinipage(lex.getInteger());
1023 } else if (token == "\\labelwidthstring") {
1025 par->params().labelWidthString(lex.getString());
1026 // do not delete this token, it is still needed!
1027 } else if (token == "\\end_inset") {
1028 lyxerr << "Solitary \\end_inset. Missing \\begin_inset?.\n"
1029 << "Last inset read was: " << last_inset_read
1031 // Simply ignore this. The insets do not have
1033 // But insets should read it, it is a part of
1034 // the inset isn't it? Lgb.
1035 } else if (token == "\\begin_inset") {
1036 #ifndef NO_COMPABILITY
1037 insertErtContents(par, pos, font, false);
1038 ert_stack.push(ert_comp);
1039 ert_comp = ErtComp();
1041 readInset(lex, par, pos, font);
1042 #ifndef NO_COMPABILITY
1043 ert_comp = ert_stack.top();
1045 insertErtContents(par, pos, font);
1047 } else if (token == "\\SpecialChar") {
1048 LyXLayout const & layout =
1049 textclasslist.Style(params.textclass,
1052 // Insets don't make sense in a free-spacing context! ---Kayvan
1053 if (layout.free_spacing) {
1056 string next_token = lex.getString();
1057 if (next_token == "\\-") {
1058 par->insertChar(pos, '-', font);
1059 } else if (next_token == "\\protected_separator"
1060 || next_token == "~") {
1061 par->insertChar(pos, ' ', font);
1063 lex.printError("Token `$$Token' "
1065 "paragraph layout!");
1070 Inset * inset = new InsetSpecialChar;
1071 inset->read(this, lex);
1072 par->insertInset(pos, inset, font);
1075 } else if (token == "\\newline") {
1076 #ifndef NO_COMPABILITY
1077 if (!ert_comp.in_tabular && ert_comp.active) {
1078 ert_comp.contents += char(Paragraph::META_NEWLINE);
1080 // Since we cannot know it this is only a regular
1081 // newline or a tabular cell delimter we have to
1082 // handle the ERT here.
1083 insertErtContents(par, pos, font, false);
1085 par->insertChar(pos, Paragraph::META_NEWLINE, font);
1089 par->insertChar(pos, Paragraph::META_NEWLINE, font);
1092 } else if (token == "\\LyXTable") {
1093 #ifndef NO_COMPABILITY
1094 ert_comp.in_tabular = true;
1096 Inset * inset = new InsetTabular(*this);
1097 inset->read(this, lex);
1098 par->insertInset(pos, inset, font);
1100 } else if (token == "\\hfill") {
1101 par->insertChar(pos, Paragraph::META_HFILL, font);
1103 } else if (token == "\\protected_separator") { // obsolete
1104 // This is a backward compability thingie. (Lgb)
1105 // Remove it later some time...introduced with fileformat
1107 LyXLayout const & layout =
1108 textclasslist.Style(params.textclass,
1111 if (layout.free_spacing) {
1112 par->insertChar(pos, ' ', font);
1114 Inset * inset = new InsetSpecialChar(InsetSpecialChar::PROTECTED_SEPARATOR);
1115 par->insertInset(pos, inset, font);
1118 } else if (token == "\\bibitem") { // ale970302
1120 InsetCommandParams p("bibitem", "dummy");
1121 par->bibkey = new InsetBibKey(p);
1123 par->bibkey->read(this, lex);
1124 } else if (token == "\\backslash") {
1125 #ifndef NO_COMPABILITY
1126 if (ert_comp.active) {
1127 ert_comp.contents += "\\";
1130 par->insertChar(pos, '\\', font);
1132 #ifndef NO_COMPABILITY
1135 } else if (token == "\\the_end") {
1136 #ifndef NO_COMPABILITY
1137 // If we still have some ert active here we have to insert
1138 // it so we don't loose it. (Lgb)
1139 insertErtContents(par, pos, font);
1141 the_end_read = true;
1142 #ifndef NO_COMPABILITY
1143 #ifndef NO_PEXTRA_REALLY
1144 minipar = parBeforeMinipage = 0;
1148 #ifndef NO_COMPABILITY
1149 if (ert_comp.active) {
1150 ert_comp.contents += token;
1153 // This should be insurance for the future: (Asger)
1154 lex.printError("Unknown token `$$Token'. "
1155 "Inserting as text.");
1156 string::const_iterator cit = token.begin();
1157 string::const_iterator end = token.end();
1158 for (; cit != end; ++cit) {
1159 par->insertChar(pos, (*cit), font);
1162 #ifndef NO_COMPABILITY
1167 #ifndef NO_COMPABILITY
1168 #ifndef NO_PEXTRA_REALLY
1169 // I wonder if we could use this blanket fix for all the
1170 // checkminipage cases...
1171 if (par && par->size()) {
1172 // It is possible that this will check to often,
1173 // but that should not be an correctness issue.
1174 // Only a speed issue.
1175 checkminipage = true;
1178 // now check if we have a minipage paragraph as at this
1179 // point we already read all the necessary data!
1180 // this cannot be done in layout because there we did
1181 // not read yet the paragraph PEXTRA-params (Jug)
1183 // BEGIN pextra_minipage compability
1184 // This should be removed in 1.3.x (Lgb)
1186 // This compability code is not perfect. In a couple
1187 // of rand cases it fails. When the minipage par is
1188 // the first par in the document, and when there are
1189 // none or only one regular paragraphs after the
1190 // minipage. Currently I am not investing any effort
1191 // in fixing those cases.
1193 //lyxerr << "Call depth: " << call_depth << endl;
1194 if (checkminipage && (call_depth == 1)) {
1195 checkminipage = false;
1196 if (minipar && (minipar != par) &&
1197 (par->params().pextraType()==Paragraph::PEXTRA_MINIPAGE))
1199 lyxerr << "minipages in a row" << endl;
1200 if (par->params().pextraStartMinipage()) {
1201 lyxerr << "start new minipage" << endl;
1202 // minipages in a row
1203 par->previous()->next(0);
1206 Paragraph * tmp = minipar;
1208 tmp->params().pextraType(0);
1209 tmp->params().pextraWidth(string());
1210 tmp->params().pextraWidthp(string());
1211 tmp->params().pextraAlignment(0);
1212 tmp->params().pextraHfill(false);
1213 tmp->params().pextraStartMinipage(false);
1216 // create a new paragraph to insert the
1217 // minipages in the following case
1218 if (par->params().pextraStartMinipage() &&
1219 !par->params().pextraHfill())
1221 Paragraph * p = new Paragraph;
1223 p->previous(parBeforeMinipage);
1224 parBeforeMinipage->next(p);
1226 p->params().depth(parBeforeMinipage->params().depth());
1227 parBeforeMinipage = p;
1229 InsetMinipage * mini = new InsetMinipage;
1230 mini->pos(static_cast<InsetMinipage::Position>(par->params().pextraAlignment()));
1231 mini->width(par->params().pextraWidth());
1232 if (!par->params().pextraWidthp().empty()) {
1233 lyxerr << "WP:" << mini->width() << endl;
1234 mini->width(tostr(par->params().pextraWidthp())+"%");
1236 mini->inset.paragraph(par);
1237 // Insert the minipage last in the
1238 // previous paragraph.
1239 if (par->params().pextraHfill()) {
1240 parBeforeMinipage->insertChar
1241 (parBeforeMinipage->size(), Paragraph::META_HFILL);
1243 parBeforeMinipage->insertInset
1244 (parBeforeMinipage->size(), mini);
1248 lyxerr << "new minipage par" << endl;
1249 //nothing to do just continue reading
1252 } else if (minipar && (minipar != par)) {
1253 lyxerr << "last minipage par read" << endl;
1254 // The last paragraph read was not part of a
1255 // minipage but the par linked list is...
1256 // So we need to remove the last par from the
1258 if (par->previous())
1259 par->previous()->next(0);
1260 par->previous(parBeforeMinipage);
1261 parBeforeMinipage->next(par);
1262 Paragraph * tmp = minipar;
1264 tmp->params().pextraType(0);
1265 tmp->params().pextraWidth(string());
1266 tmp->params().pextraWidthp(string());
1267 tmp->params().pextraAlignment(0);
1268 tmp->params().pextraHfill(false);
1269 tmp->params().pextraStartMinipage(false);
1272 depth = parBeforeMinipage->params().depth();
1273 minipar = parBeforeMinipage = 0;
1274 } else if (!minipar &&
1275 (par->params().pextraType() == Paragraph::PEXTRA_MINIPAGE))
1277 // par is the first paragraph in a minipage
1278 lyxerr << "begin minipage" << endl;
1279 // To minimize problems for
1280 // the users we will insert
1281 // the first minipage in
1282 // a sequence of minipages
1283 // in its own paragraph.
1284 Paragraph * p = new Paragraph;
1286 p->previous(par->previous());
1288 p->params().depth(depth);
1289 par->params().depth(0);
1291 if (par->previous())
1292 par->previous()->next(p);
1294 parBeforeMinipage = p;
1296 if (!first_par || (first_par == par))
1299 InsetMinipage * mini = new InsetMinipage;
1300 mini->pos(static_cast<InsetMinipage::Position>(minipar->params().pextraAlignment()));
1301 mini->width(minipar->params().pextraWidth());
1302 if (!par->params().pextraWidthp().empty()) {
1303 lyxerr << "WP:" << mini->width() << endl;
1304 mini->width(tostr(par->params().pextraWidthp())+"%");
1306 mini->inset.paragraph(minipar);
1308 // Insert the minipage last in the
1309 // previous paragraph.
1310 if (minipar->params().pextraHfill()) {
1311 parBeforeMinipage->insertChar
1312 (parBeforeMinipage->size(),Paragraph::META_HFILL);
1314 parBeforeMinipage->insertInset
1315 (parBeforeMinipage->size(), mini);
1318 // End of pextra_minipage compability
1322 return the_end_read;
1325 // needed to insert the selection
1326 void Buffer::insertStringAsLines(Paragraph *& par, Paragraph::size_type & pos,
1327 LyXFont const & fn,string const & str) const
1329 LyXLayout const & layout = textclasslist.Style(params.textclass,
1333 (void)par->checkInsertChar(font);
1334 // insert the string, don't insert doublespace
1335 bool space_inserted = true;
1336 for(string::const_iterator cit = str.begin();
1337 cit != str.end(); ++cit) {
1339 if (par->size() || layout.keepempty) {
1340 par->breakParagraph(params, pos,
1341 layout.isEnvironment());
1344 space_inserted = true;
1348 // do not insert consecutive spaces if !free_spacing
1349 } else if ((*cit == ' ' || *cit == '\t') &&
1350 space_inserted && !layout.free_spacing)
1353 } else if (*cit == '\t') {
1354 if (!layout.free_spacing) {
1355 // tabs are like spaces here
1356 par->insertChar(pos, ' ', font);
1358 space_inserted = true;
1360 const Paragraph::size_type nb = 8 - pos % 8;
1361 for (Paragraph::size_type a = 0;
1363 par->insertChar(pos, ' ', font);
1366 space_inserted = true;
1368 } else if (!IsPrintable(*cit)) {
1369 // Ignore unprintables
1372 // just insert the character
1373 par->insertChar(pos, *cit, font);
1375 space_inserted = (*cit == ' ');
1382 void Buffer::readInset(LyXLex & lex, Paragraph *& par,
1383 int & pos, LyXFont & font)
1385 // consistency check
1386 if (lex.getString() != "\\begin_inset") {
1387 lyxerr << "Buffer::readInset: Consistency check failed."
1394 string const tmptok = lex.getString();
1395 last_inset_read = tmptok;
1397 // test the different insets
1398 if (tmptok == "LatexCommand") {
1399 InsetCommandParams inscmd;
1402 string const cmdName = inscmd.getCmdName();
1404 // This strange command allows LyX to recognize "natbib" style
1405 // citations: citet, citep, Citet etc.
1406 if (compare_no_case(cmdName, "cite", 4) == 0) {
1407 inset = new InsetCitation(inscmd);
1408 } else if (cmdName == "bibitem") {
1409 lex.printError("Wrong place for bibitem");
1410 inset = new InsetBibKey(inscmd);
1411 } else if (cmdName == "BibTeX") {
1412 inset = new InsetBibtex(inscmd);
1413 } else if (cmdName == "index") {
1414 inset = new InsetIndex(inscmd);
1415 } else if (cmdName == "include") {
1416 inset = new InsetInclude(inscmd, *this);
1417 } else if (cmdName == "label") {
1418 inset = new InsetLabel(inscmd);
1419 } else if (cmdName == "url"
1420 || cmdName == "htmlurl") {
1421 inset = new InsetUrl(inscmd);
1422 } else if (cmdName == "ref"
1423 || cmdName == "pageref"
1424 || cmdName == "vref"
1425 || cmdName == "vpageref"
1426 || cmdName == "prettyref") {
1427 if (!inscmd.getOptions().empty()
1428 || !inscmd.getContents().empty()) {
1429 inset = new InsetRef(inscmd, *this);
1431 } else if (cmdName == "tableofcontents") {
1432 inset = new InsetTOC(inscmd);
1433 } else if (cmdName == "listofalgorithms") {
1434 inset = new InsetFloatList("algorithm");
1435 } else if (cmdName == "listoffigures") {
1436 inset = new InsetFloatList("figure");
1437 } else if (cmdName == "listoftables") {
1438 inset = new InsetFloatList("table");
1439 } else if (cmdName == "printindex") {
1440 inset = new InsetPrintIndex(inscmd);
1441 } else if (cmdName == "lyxparent") {
1442 inset = new InsetParent(inscmd, *this);
1445 bool alreadyread = false;
1446 if (tmptok == "Quotes") {
1447 inset = new InsetQuotes;
1448 } else if (tmptok == "External") {
1449 inset = new InsetExternal;
1450 } else if (tmptok == "FormulaMacro") {
1451 inset = new InsetFormulaMacro;
1452 } else if (tmptok == "Formula") {
1453 inset = new InsetFormula;
1454 } else if (tmptok == "Figure") { // Backward compatibility
1455 inset = new InsetFig(100, 100, *this);
1456 //inset = new InsetGraphics;
1457 } else if (tmptok == "Graphics") {
1458 inset = new InsetGraphics;
1459 } else if (tmptok == "Info") {// backwards compatibility
1460 inset = new InsetNote(this,
1461 lex.getLongString("\\end_inset"),
1464 } else if (tmptok == "Note") {
1465 inset = new InsetNote;
1466 } else if (tmptok == "Include") {
1467 InsetCommandParams p( "Include" );
1468 inset = new InsetInclude(p, *this);
1469 } else if (tmptok == "ERT") {
1470 inset = new InsetERT;
1471 } else if (tmptok == "Tabular") {
1472 inset = new InsetTabular(*this);
1473 } else if (tmptok == "Text") {
1474 inset = new InsetText;
1475 } else if (tmptok == "Foot") {
1476 inset = new InsetFoot;
1477 } else if (tmptok == "Marginal") {
1478 inset = new InsetMarginal;
1479 } else if (tmptok == "Minipage") {
1480 inset = new InsetMinipage;
1481 } else if (tmptok == "Float") {
1483 string tmptok = lex.getString();
1484 inset = new InsetFloat(tmptok);
1486 } else if (tmptok == "List") {
1487 inset = new InsetList;
1488 } else if (tmptok == "Theorem") {
1489 inset = new InsetList;
1491 } else if (tmptok == "Caption") {
1492 inset = new InsetCaption;
1493 } else if (tmptok == "FloatList") {
1494 inset = new InsetFloatList;
1497 if (inset && !alreadyread) inset->read(this, lex);
1501 par->insertInset(pos, inset, font);
1507 bool Buffer::readFile(LyXLex & lex, Paragraph * par)
1511 string const token(lex.getString());
1512 if (token == "\\lyxformat") { // the first token _must_ be...
1514 string tmp_format = lex.getString();
1515 //lyxerr << "LyX Format: `" << tmp_format << "'" << endl;
1516 // if present remove ".," from string.
1517 string::size_type dot = tmp_format.find_first_of(".,");
1518 //lyxerr << " dot found at " << dot << endl;
1519 if (dot != string::npos)
1520 tmp_format.erase(dot, 1);
1521 file_format = strToInt(tmp_format);
1522 if (file_format == LYX_FORMAT) {
1524 } else if (file_format > LYX_FORMAT) {
1526 WriteAlert(_("Warning!"),
1527 _("LyX file format is newer that what"),
1528 _("is supported in this LyX version. Expect some problems."));
1530 } else if (file_format < LYX_FORMAT) {
1532 if (file_format < 200) {
1533 WriteAlert(_("ERROR!"),
1534 _("Old LyX file format found. "
1535 "Use LyX 0.10.x to read this!"));
1539 bool the_end = readLyXformat2(lex, par);
1540 params.setPaperStuff();
1541 // the_end was added in 213
1542 if (file_format < 213)
1546 WriteAlert(_("Warning!"),
1547 _("Reading of document is not complete"),
1548 _("Maybe the document is truncated"));
1550 } else { // "\\lyxformat" not found
1551 WriteAlert(_("ERROR!"), _("Not a LyX file!"));
1554 WriteAlert(_("ERROR!"), _("Unable to read file!"));
1559 // Should probably be moved to somewhere else: BufferView? LyXView?
1560 bool Buffer::save() const
1562 // We don't need autosaves in the immediate future. (Asger)
1563 resetAutosaveTimers();
1567 if (lyxrc.make_backup) {
1568 s = fileName() + '~';
1569 if (!lyxrc.backupdir_path.empty())
1570 s = AddName(lyxrc.backupdir_path,
1571 subst(os::slashify_path(s),'/','!'));
1573 // Rename is the wrong way of making a backup,
1574 // this is the correct way.
1575 /* truss cp fil fil2:
1576 lstat("LyXVC3.lyx", 0xEFFFF898) Err#2 ENOENT
1577 stat("LyXVC.lyx", 0xEFFFF688) = 0
1578 open("LyXVC.lyx", O_RDONLY) = 3
1579 open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
1580 fstat(4, 0xEFFFF508) = 0
1581 fstat(3, 0xEFFFF508) = 0
1582 read(3, " # T h i s f i l e w".., 8192) = 5579
1583 write(4, " # T h i s f i l e w".., 5579) = 5579
1584 read(3, 0xEFFFD4A0, 8192) = 0
1587 chmod("LyXVC3.lyx", 0100644) = 0
1588 lseek(0, 0, SEEK_CUR) = 46440
1592 // Should probably have some more error checking here.
1593 // Should be cleaned up in 0.13, at least a bit.
1594 // Doing it this way, also makes the inodes stay the same.
1595 // This is still not a very good solution, in particular we
1596 // might loose the owner of the backup.
1597 FileInfo finfo(fileName());
1598 if (finfo.exist()) {
1599 mode_t fmode = finfo.getMode();
1600 struct utimbuf times = {
1601 finfo.getAccessTime(),
1602 finfo.getModificationTime() };
1604 ifstream ifs(fileName().c_str());
1605 ofstream ofs(s.c_str(), ios::out|ios::trunc);
1610 ::chmod(s.c_str(), fmode);
1612 if (::utime(s.c_str(), ×)) {
1613 lyxerr << "utime error." << endl;
1616 lyxerr << "LyX was not able to make "
1617 "backup copy. Beware." << endl;
1622 if (writeFile(fileName(), false)) {
1624 removeAutosaveFile(fileName());
1626 // Saving failed, so backup is not backup
1627 if (lyxrc.make_backup) {
1628 lyx::rename(s, fileName());
1636 // Returns false if unsuccesful
1637 bool Buffer::writeFile(string const & fname, bool flag) const
1639 // if flag is false writeFile will not create any GUI
1640 // warnings, only cerr.
1641 // Needed for autosave in background or panic save (Matthias 120496)
1643 if (read_only && (fname == filename)) {
1644 // Here we should come with a question if we should
1645 // perform the write anyway.
1647 lyxerr << _("Error! Document is read-only: ")
1650 WriteAlert(_("Error! Document is read-only: "),
1655 FileInfo finfo(fname);
1656 if (finfo.exist() && !finfo.writable()) {
1657 // Here we should come with a question if we should
1658 // try to do the save anyway. (i.e. do a chmod first)
1660 lyxerr << _("Error! Cannot write file: ")
1663 WriteFSAlert(_("Error! Cannot write file: "),
1668 ofstream ofs(fname.c_str());
1671 lyxerr << _("Error! Cannot open file: ")
1674 WriteFSAlert(_("Error! Cannot open file: "),
1680 // Use the standard "C" locale for file output.
1681 ofs.imbue(std::locale::classic());
1684 // The top of the file should not be written by params.
1686 // write out a comment in the top of the file
1687 ofs << '#' << lyx_docversion
1688 << " created this file. For more info see http://www.lyx.org/\n"
1689 << "\\lyxformat " << LYX_FORMAT << "\n";
1691 // now write out the buffer paramters.
1692 params.writeFile(ofs);
1694 Paragraph::depth_type depth = 0;
1696 // this will write out all the paragraphs
1697 // using recursive descent.
1698 paragraph->writeFile(this, ofs, params, depth);
1700 // Write marker that shows file is complete
1701 ofs << "\n\\the_end" << endl;
1705 // how to check if close went ok?
1706 // Following is an attempt... (BE 20001011)
1708 // good() returns false if any error occured, including some
1709 // formatting error.
1710 // bad() returns true if something bad happened in the buffer,
1711 // which should include file system full errors.
1718 lyxerr << "Buffer::writeFile: BAD ERROR!" << endl;
1720 lyxerr << "Buffer::writeFile: NOT SO BAD ERROR!"
1730 string const Buffer::asciiParagraph(Paragraph const * par,
1731 unsigned int linelen) const
1733 ostringstream buffer;
1734 Paragraph::depth_type depth = 0;
1736 Paragraph::depth_type ltype_depth = 0;
1737 string::size_type currlinelen = 0;
1738 bool ref_printed = false;
1742 if (!par->previous()) {
1743 // begins or ends a deeper area ?
1744 if (depth != par->params().depth()) {
1745 if (par->params().depth() > depth) {
1746 while (par->params().depth() > depth) {
1750 while (par->params().depth() < depth) {
1756 // First write the layout
1757 string const tmp = textclasslist.NameOfLayout(params.textclass, par->layout);
1758 if (tmp == "Itemize") {
1760 ltype_depth = depth + 1;
1761 } else if (tmp == "Enumerate") {
1763 ltype_depth = depth + 1;
1764 } else if (contains(tmp, "ection")) {
1766 ltype_depth = depth + 1;
1767 } else if (contains(tmp, "aragraph")) {
1769 ltype_depth = depth + 1;
1770 } else if (tmp == "Description") {
1772 ltype_depth = depth + 1;
1773 } else if (tmp == "Abstract") {
1776 } else if (tmp == "Bibliography") {
1784 /* maybe some vertical spaces */
1786 /* the labelwidthstring used in lists */
1790 /* some pagebreaks? */
1794 /* what about the alignment */
1796 lyxerr << "Should this ever happen?" << endl;
1799 for (Paragraph::size_type i = 0; i < par->size(); ++i) {
1800 if (!i && !noparbreak) {
1803 for (Paragraph::depth_type j = 0; j < depth; ++j)
1805 currlinelen = depth * 2;
1808 case 4: // (Sub)Paragraph
1809 case 5: // Description
1813 buffer << "Abstract\n\n";
1815 buffer << "Abstract: ";
1817 case 7: // Bibliography
1820 buffer << "References\n\n";
1822 buffer << "References: ";
1827 buffer << par->params().labelString() << " ";
1830 if (ltype_depth > depth) {
1831 for (Paragraph::depth_type j = ltype_depth - 1;
1834 currlinelen += (ltype_depth-depth)*2;
1838 char c = par->getUChar(params, i);
1842 case Paragraph::META_INSET:
1844 Inset const * inset = par->getInset(i);
1846 if (!inset->ascii(this, buffer)) {
1849 rsplit(buffer.str().c_str(),
1851 currlinelen += s.length();
1853 // to be sure it breaks paragraph
1854 currlinelen += linelen;
1860 case Paragraph::META_NEWLINE:
1863 for (Paragraph::depth_type j = 0;
1867 currlinelen = depth * 2;
1868 if (ltype_depth > depth) {
1869 for (Paragraph::depth_type j = ltype_depth;
1872 currlinelen += (ltype_depth - depth) * 2;
1876 case Paragraph::META_HFILL:
1881 if ((linelen > 0) && (currlinelen > (linelen - 10)) &&
1882 (c == ' ') && ((i + 2) < par->size()))
1885 for (Paragraph::depth_type j = 0;
1888 currlinelen = depth * 2;
1889 if (ltype_depth > depth) {
1890 for (Paragraph::depth_type j = ltype_depth;
1893 currlinelen += (ltype_depth-depth)*2;
1895 } else if (c != '\0') {
1899 lyxerr[Debug::INFO] << "writeAsciiFile: NULL char in structure." << endl;
1903 return buffer.str().c_str();
1907 void Buffer::writeFileAscii(string const & fname, int linelen)
1909 ofstream ofs(fname.c_str());
1911 WriteFSAlert(_("Error: Cannot write file:"), fname);
1914 writeFileAscii(ofs, linelen);
1918 void Buffer::writeFileAscii(ostream & ofs, int linelen)
1920 Paragraph * par = paragraph;
1922 ofs << asciiParagraph(par, linelen);
1930 void Buffer::makeLaTeXFile(string const & fname,
1931 string const & original_path,
1932 bool nice, bool only_body)
1934 lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
1936 niceFile = nice; // this will be used by Insetincludes.
1938 tex_code_break_column = lyxrc.ascii_linelen;
1940 LyXTextClass const & tclass =
1941 textclasslist.TextClass(params.textclass);
1943 ofstream ofs(fname.c_str());
1945 WriteFSAlert(_("Error: Cannot open file: "), fname);
1949 // validate the buffer.
1950 lyxerr[Debug::LATEX] << " Validating buffer..." << endl;
1951 LaTeXFeatures features(params, tclass.numLayouts());
1953 lyxerr[Debug::LATEX] << " Buffer validation done." << endl;
1956 // The starting paragraph of the coming rows is the
1957 // first paragraph of the document. (Asger)
1958 texrow.start(paragraph, 0);
1960 if (!only_body && nice) {
1961 ofs << "%% " << lyx_docversion << " created this file. "
1962 "For more info, see http://www.lyx.org/.\n"
1963 "%% Do not edit unless you really know what "
1968 lyxerr[Debug::INFO] << "lyx header finished" << endl;
1969 // There are a few differences between nice LaTeX and usual files:
1970 // usual is \batchmode and has a
1971 // special input@path to allow the including of figures
1972 // with either \input or \includegraphics (what figinsets do).
1973 // batchmode is not set if there is a tex_code_break_column.
1974 // In this case somebody is interested in the generated LaTeX,
1975 // so this is OK. input@path is set when the actual parameter
1976 // original_path is set. This is done for usual tex-file, but not
1977 // for nice-latex-file. (Matthias 250696)
1980 // code for usual, NOT nice-latex-file
1981 ofs << "\\batchmode\n"; // changed
1982 // from \nonstopmode
1985 if (!original_path.empty()) {
1986 ofs << "\\makeatletter\n"
1987 << "\\def\\input@path{{"
1988 << os::external_path(original_path) << "/}}\n"
1989 << "\\makeatother\n";
1995 ofs << "\\documentclass";
1997 ostringstream options; // the document class options.
1999 if (tokenPos(tclass.opt_fontsize(),
2000 '|', params.fontsize) >= 0) {
2001 // only write if existing in list (and not default)
2002 options << params.fontsize << "pt,";
2006 if (!params.use_geometry &&
2007 (params.paperpackage == BufferParams::PACKAGE_NONE)) {
2008 switch (params.papersize) {
2009 case BufferParams::PAPER_A4PAPER:
2010 options << "a4paper,";
2012 case BufferParams::PAPER_USLETTER:
2013 options << "letterpaper,";
2015 case BufferParams::PAPER_A5PAPER:
2016 options << "a5paper,";
2018 case BufferParams::PAPER_B5PAPER:
2019 options << "b5paper,";
2021 case BufferParams::PAPER_EXECUTIVEPAPER:
2022 options << "executivepaper,";
2024 case BufferParams::PAPER_LEGALPAPER:
2025 options << "legalpaper,";
2031 if (params.sides != tclass.sides()) {
2032 switch (params.sides) {
2033 case LyXTextClass::OneSide:
2034 options << "oneside,";
2036 case LyXTextClass::TwoSides:
2037 options << "twoside,";
2043 if (params.columns != tclass.columns()) {
2044 if (params.columns == 2)
2045 options << "twocolumn,";
2047 options << "onecolumn,";
2050 if (!params.use_geometry
2051 && params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
2052 options << "landscape,";
2054 // language should be a parameter to \documentclass
2056 ostringstream language_options;
2057 if (params.language->babel() == "hebrew"
2058 && default_language->babel() != "hebrew")
2059 // This seems necessary
2060 features.UsedLanguages.insert(default_language);
2062 if (lyxrc.language_use_babel ||
2063 params.language->lang() != lyxrc.default_language ||
2064 !features.UsedLanguages.empty()) {
2066 for (LaTeXFeatures::LanguageList::const_iterator cit =
2067 features.UsedLanguages.begin();
2068 cit != features.UsedLanguages.end(); ++cit)
2069 language_options << (*cit)->babel() << ',';
2070 language_options << params.language->babel();
2071 if (lyxrc.language_global_options)
2072 options << language_options.str() << ',';
2075 // the user-defined options
2076 if (!params.options.empty()) {
2077 options << params.options << ',';
2080 string strOptions(options.str().c_str());
2081 if (!strOptions.empty()){
2082 strOptions = strip(strOptions, ',');
2083 ofs << '[' << strOptions << ']';
2087 << textclasslist.LatexnameOfClass(params.textclass)
2090 // end of \documentclass defs
2092 // font selection must be done before loading fontenc.sty
2093 // The ae package is not needed when using OT1 font encoding.
2094 if (params.fonts != "default" &&
2095 (params.fonts != "ae" || lyxrc.fontenc != "default")) {
2096 ofs << "\\usepackage{" << params.fonts << "}\n";
2098 if (params.fonts == "ae") {
2099 ofs << "\\usepackage{aecompl}\n";
2103 // this one is not per buffer
2104 if (lyxrc.fontenc != "default") {
2105 ofs << "\\usepackage[" << lyxrc.fontenc
2110 if (params.inputenc == "auto") {
2111 string const doc_encoding =
2112 params.language->encoding()->LatexName();
2114 // Create a list with all the input encodings used
2116 set<string> encodings;
2117 for (LaTeXFeatures::LanguageList::const_iterator it =
2118 features.UsedLanguages.begin();
2119 it != features.UsedLanguages.end(); ++it)
2120 if ((*it)->encoding()->LatexName() != doc_encoding)
2121 encodings.insert((*it)->encoding()->LatexName());
2123 ofs << "\\usepackage[";
2124 std::copy(encodings.begin(), encodings.end(),
2125 std::ostream_iterator<string>(ofs, ","));
2126 ofs << doc_encoding << "]{inputenc}\n";
2128 } else if (params.inputenc != "default") {
2129 ofs << "\\usepackage[" << params.inputenc
2134 // At the very beginning the text parameters.
2135 if (params.paperpackage != BufferParams::PACKAGE_NONE) {
2136 switch (params.paperpackage) {
2137 case BufferParams::PACKAGE_A4:
2138 ofs << "\\usepackage{a4}\n";
2141 case BufferParams::PACKAGE_A4WIDE:
2142 ofs << "\\usepackage{a4wide}\n";
2145 case BufferParams::PACKAGE_WIDEMARGINSA4:
2146 ofs << "\\usepackage[widemargins]{a4}\n";
2151 if (params.use_geometry) {
2152 ofs << "\\usepackage{geometry}\n";
2154 ofs << "\\geometry{verbose";
2155 if (params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
2156 ofs << ",landscape";
2157 switch (params.papersize2) {
2158 case BufferParams::VM_PAPER_CUSTOM:
2159 if (!params.paperwidth.empty())
2160 ofs << ",paperwidth="
2161 << params.paperwidth;
2162 if (!params.paperheight.empty())
2163 ofs << ",paperheight="
2164 << params.paperheight;
2166 case BufferParams::VM_PAPER_USLETTER:
2167 ofs << ",letterpaper";
2169 case BufferParams::VM_PAPER_USLEGAL:
2170 ofs << ",legalpaper";
2172 case BufferParams::VM_PAPER_USEXECUTIVE:
2173 ofs << ",executivepaper";
2175 case BufferParams::VM_PAPER_A3:
2178 case BufferParams::VM_PAPER_A4:
2181 case BufferParams::VM_PAPER_A5:
2184 case BufferParams::VM_PAPER_B3:
2187 case BufferParams::VM_PAPER_B4:
2190 case BufferParams::VM_PAPER_B5:
2194 // default papersize ie BufferParams::VM_PAPER_DEFAULT
2195 switch (lyxrc.default_papersize) {
2196 case BufferParams::PAPER_DEFAULT: // keep compiler happy
2197 case BufferParams::PAPER_USLETTER:
2198 ofs << ",letterpaper";
2200 case BufferParams::PAPER_LEGALPAPER:
2201 ofs << ",legalpaper";
2203 case BufferParams::PAPER_EXECUTIVEPAPER:
2204 ofs << ",executivepaper";
2206 case BufferParams::PAPER_A3PAPER:
2209 case BufferParams::PAPER_A4PAPER:
2212 case BufferParams::PAPER_A5PAPER:
2215 case BufferParams::PAPER_B5PAPER:
2220 if (!params.topmargin.empty())
2221 ofs << ",tmargin=" << params.topmargin;
2222 if (!params.bottommargin.empty())
2223 ofs << ",bmargin=" << params.bottommargin;
2224 if (!params.leftmargin.empty())
2225 ofs << ",lmargin=" << params.leftmargin;
2226 if (!params.rightmargin.empty())
2227 ofs << ",rmargin=" << params.rightmargin;
2228 if (!params.headheight.empty())
2229 ofs << ",headheight=" << params.headheight;
2230 if (!params.headsep.empty())
2231 ofs << ",headsep=" << params.headsep;
2232 if (!params.footskip.empty())
2233 ofs << ",footskip=" << params.footskip;
2237 if (features.amsstyle
2238 && !tclass.provides(LyXTextClass::amsmath)) {
2239 ofs << "\\usepackage{amsmath}\n";
2243 if (tokenPos(tclass.opt_pagestyle(),
2244 '|', params.pagestyle) >= 0) {
2245 if (params.pagestyle == "fancy") {
2246 ofs << "\\usepackage{fancyhdr}\n";
2249 ofs << "\\pagestyle{" << params.pagestyle << "}\n";
2253 if (params.secnumdepth != tclass.secnumdepth()) {
2254 ofs << "\\setcounter{secnumdepth}{"
2255 << params.secnumdepth
2259 if (params.tocdepth != tclass.tocdepth()) {
2260 ofs << "\\setcounter{tocdepth}{"
2266 if (params.paragraph_separation) {
2267 switch (params.defskip.kind()) {
2268 case VSpace::SMALLSKIP:
2269 ofs << "\\setlength\\parskip{\\smallskipamount}\n";
2271 case VSpace::MEDSKIP:
2272 ofs << "\\setlength\\parskip{\\medskipamount}\n";
2274 case VSpace::BIGSKIP:
2275 ofs << "\\setlength\\parskip{\\bigskipamount}\n";
2277 case VSpace::LENGTH:
2278 ofs << "\\setlength\\parskip{"
2279 << params.defskip.length().asLatexString()
2282 default: // should never happen // Then delete it.
2283 ofs << "\\setlength\\parskip{\\medskipamount}\n";
2288 ofs << "\\setlength\\parindent{0pt}\n";
2292 // Now insert the LyX specific LaTeX commands...
2294 // The optional packages;
2295 string preamble(features.getPackages());
2297 // this might be useful...
2298 preamble += "\n\\makeatletter\n";
2300 // Some macros LyX will need
2301 string tmppreamble(features.getMacros());
2303 if (!tmppreamble.empty()) {
2304 preamble += "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2305 "LyX specific LaTeX commands.\n"
2306 + tmppreamble + '\n';
2309 // the text class specific preamble
2310 tmppreamble = features.getTClassPreamble();
2311 if (!tmppreamble.empty()) {
2312 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2313 "Textclass specific LaTeX commands.\n"
2314 + tmppreamble + '\n';
2317 /* the user-defined preamble */
2318 if (!params.preamble.empty()) {
2319 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2320 "User specified LaTeX commands.\n"
2321 + params.preamble + '\n';
2324 preamble += "\\makeatother\n";
2326 // Itemize bullet settings need to be last in case the user
2327 // defines their own bullets that use a package included
2328 // in the user-defined preamble -- ARRae
2329 // Actually it has to be done much later than that
2330 // since some packages like frenchb make modifications
2331 // at \begin{document} time -- JMarc
2333 for (int i = 0; i < 4; ++i) {
2334 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
2335 if (bullets_def.empty())
2336 bullets_def="\\AtBeginDocument{\n";
2337 bullets_def += " \\renewcommand{\\labelitemi";
2339 // `i' is one less than the item to modify
2346 bullets_def += "ii";
2352 bullets_def += "}{" +
2353 params.user_defined_bullets[i].getText()
2358 if (!bullets_def.empty())
2359 preamble += bullets_def + "}\n\n";
2361 for (int j = countChar(preamble, '\n'); j-- ;) {
2367 // We try to load babel late, in case it interferes
2368 // with other packages.
2370 string tmp = lyxrc.language_package;
2371 if (!lyxrc.language_global_options
2372 && tmp == "\\usepackage{babel}")
2373 tmp = string("\\usepackage[") +
2374 language_options.str().c_str() +
2381 ofs << "\\begin{document}\n";
2384 lyxerr[Debug::INFO] << "preamble finished, now the body." << endl;
2386 if (!lyxrc.language_auto_begin) {
2387 ofs << subst(lyxrc.language_command_begin, "$$lang",
2388 params.language->babel())
2393 latexParagraphs(ofs, paragraph, 0, texrow);
2395 // add this just in case after all the paragraphs
2399 if (!lyxrc.language_auto_end) {
2400 ofs << subst(lyxrc.language_command_end, "$$lang",
2401 params.language->babel())
2407 ofs << "\\end{document}\n";
2410 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
2412 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
2416 // Just to be sure. (Asger)
2419 // tex_code_break_column's value is used to decide
2420 // if we are in batchmode or not (within mathed_write()
2421 // in math_write.C) so we must set it to a non-zero
2422 // value when we leave otherwise we save incorrect .lyx files.
2423 tex_code_break_column = lyxrc.ascii_linelen;
2427 lyxerr << "File was not closed properly." << endl;
2430 lyxerr[Debug::INFO] << "Finished making latex file." << endl;
2435 // LaTeX all paragraphs from par to endpar, if endpar == 0 then to the end
2437 void Buffer::latexParagraphs(ostream & ofs, Paragraph * par,
2438 Paragraph * endpar, TexRow & texrow) const
2440 bool was_title = false;
2441 bool already_title = false;
2444 while (par != endpar) {
2445 LyXLayout const & layout =
2446 textclasslist.Style(params.textclass,
2449 if (layout.intitle) {
2450 if (already_title) {
2451 lyxerr <<"Error in latexParagraphs: You"
2452 " should not mix title layouts"
2453 " with normal ones." << endl;
2456 } else if (was_title && !already_title) {
2457 ofs << "\\maketitle\n";
2459 already_title = true;
2463 if (layout.isEnvironment()) {
2464 par = par->TeXEnvironment(this, params, ofs, texrow);
2466 par = par->TeXOnePar(this, params, ofs, texrow, false);
2469 // It might be that we only have a title in this document
2470 if (was_title && !already_title) {
2471 ofs << "\\maketitle\n";
2477 bool Buffer::isLatex() const
2479 return textclasslist.TextClass(params.textclass).outputType() == LATEX;
2483 bool Buffer::isLinuxDoc() const
2485 return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC;
2489 bool Buffer::isLiterate() const
2491 return textclasslist.TextClass(params.textclass).outputType() == LITERATE;
2495 bool Buffer::isDocBook() const
2497 return textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2501 bool Buffer::isSGML() const
2503 return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC ||
2504 textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2508 void Buffer::sgmlOpenTag(ostream & os, Paragraph::depth_type depth,
2509 string const & latexname) const
2511 if (!latexname.empty() && latexname != "!-- --")
2512 //os << "<!-- " << depth << " -->" << "<" << latexname << ">";
2513 os << string(depth, ' ') << "<" << latexname << ">\n";
2517 void Buffer::sgmlCloseTag(ostream & os, Paragraph::depth_type depth,
2518 string const & latexname) const
2520 if (!latexname.empty() && latexname != "!-- --")
2521 //os << "<!-- " << depth << " -->" << "</" << latexname << ">\n";
2522 os << string(depth, ' ') << "</" << latexname << ">\n";
2526 void Buffer::makeLinuxDocFile(string const & fname, bool nice, bool body_only)
2528 ofstream ofs(fname.c_str());
2531 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2535 niceFile = nice; // this will be used by included files.
2537 LyXTextClass const & tclass =
2538 textclasslist.TextClass(params.textclass);
2540 LaTeXFeatures features(params, tclass.numLayouts());
2545 string top_element = textclasslist.LatexnameOfClass(params.textclass);
2548 ofs << "<!doctype linuxdoc system";
2550 string preamble = params.preamble;
2551 preamble += features.getIncludedFiles(fname);
2552 preamble += features.getLyXSGMLEntities();
2554 if (!preamble.empty()) {
2555 ofs << " [ " << preamble << " ]";
2559 if (params.options.empty())
2560 sgmlOpenTag(ofs, 0, top_element);
2562 string top = top_element;
2564 top += params.options;
2565 sgmlOpenTag(ofs, 0, top);
2569 ofs << "<!-- " << lyx_docversion
2570 << " created this file. For more info see http://www.lyx.org/"
2573 Paragraph::depth_type depth = 0; // paragraph depth
2574 Paragraph * par = paragraph;
2576 vector<string> environment_stack(5);
2579 LyXLayout const & style =
2580 textclasslist.Style(params.textclass,
2583 // treat <toc> as a special case for compatibility with old code
2584 if (par->getChar(0) == Paragraph::META_INSET) {
2585 Inset * inset = par->getInset(0);
2586 Inset::Code lyx_code = inset->lyxCode();
2587 if (lyx_code == Inset::TOC_CODE){
2588 string const temp = "toc";
2589 sgmlOpenTag(ofs, depth, temp);
2596 // environment tag closing
2597 for (; depth > par->params().depth(); --depth) {
2598 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2599 environment_stack[depth].erase();
2602 // write opening SGML tags
2603 switch (style.latextype) {
2604 case LATEX_PARAGRAPH:
2605 if (depth == par->params().depth()
2606 && !environment_stack[depth].empty()) {
2607 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2608 environment_stack[depth].erase();
2614 sgmlOpenTag(ofs, depth, style.latexname());
2620 _("Error : Wrong depth for"
2621 " LatexType Command.\n"));
2623 if (!environment_stack[depth].empty()){
2624 sgmlCloseTag(ofs, depth,
2625 environment_stack[depth]);
2629 environment_stack[depth].erase();
2630 sgmlOpenTag(ofs, depth, style.latexname());
2633 case LATEX_ENVIRONMENT:
2634 case LATEX_ITEM_ENVIRONMENT:
2635 if (depth == par->params().depth()
2636 && environment_stack[depth] != style.latexname()) {
2637 sgmlCloseTag(ofs, depth,
2638 environment_stack[depth]);
2639 environment_stack[depth].erase();
2641 if (depth < par->params().depth()) {
2642 depth = par->params().depth();
2643 environment_stack[depth].erase();
2645 if (environment_stack[depth] != style.latexname()) {
2647 sgmlOpenTag(ofs, depth, "p");
2649 sgmlOpenTag(ofs, depth, style.latexname());
2651 if (environment_stack.size() == depth + 1)
2652 environment_stack.push_back("!-- --");
2653 environment_stack[depth] = style.latexname();
2656 if (style.latexparam() == "CDATA")
2659 if (style.latextype == LATEX_ENVIRONMENT) break;
2661 if (style.labeltype == LABEL_MANUAL)
2666 sgmlOpenTag(ofs, depth + 1, item_name);
2669 sgmlOpenTag(ofs, depth, style.latexname());
2673 simpleLinuxDocOnePar(ofs, par, depth);
2678 // write closing SGML tags
2679 switch (style.latextype) {
2682 case LATEX_ENVIRONMENT:
2683 case LATEX_ITEM_ENVIRONMENT:
2684 if (style.latexparam() == "CDATA")
2688 sgmlCloseTag(ofs, depth, style.latexname());
2694 for (int i=depth; i >= 0; --i)
2695 sgmlCloseTag(ofs, depth, environment_stack[i]);
2699 sgmlCloseTag(ofs, 0, top_element);
2703 // How to check for successful close
2707 // checks, if newcol chars should be put into this line
2708 // writes newline, if necessary.
2711 void linux_doc_line_break(ostream & os, string::size_type & colcount,
2712 string::size_type newcol)
2715 if (colcount > lyxrc.ascii_linelen) {
2717 colcount = newcol; // assume write after this call
2732 string tag_name(PAR_TAG const & pt) {
2734 case NONE: return "!-- --";
2735 case TT: return "tt";
2736 case SF: return "sf";
2737 case BF: return "bf";
2738 case IT: return "it";
2739 case SL: return "sl";
2740 case EM: return "em";
2747 void operator|=(PAR_TAG & p1, PAR_TAG const & p2)
2749 p1 = static_cast<PAR_TAG>(p1 | p2);
2754 void reset(PAR_TAG & p1, PAR_TAG const & p2)
2756 p1 = static_cast<PAR_TAG>( p1 & ~p2);
2762 // Handle internal paragraph parsing -- layout already processed.
2763 void Buffer::simpleLinuxDocOnePar(ostream & os,
2765 Paragraph::depth_type /*depth*/)
2767 LyXLayout const & style = textclasslist.Style(params.textclass,
2769 string::size_type char_line_count = 5; // Heuristic choice ;-)
2771 // gets paragraph main font
2774 if (style.labeltype == LABEL_MANUAL) {
2775 font_old = style.labelfont;
2778 font_old = style.font;
2782 LyXFont::FONT_FAMILY family_type = LyXFont::ROMAN_FAMILY;
2783 LyXFont::FONT_SERIES series_type = LyXFont::MEDIUM_SERIES;
2784 LyXFont::FONT_SHAPE shape_type = LyXFont::UP_SHAPE;
2787 stack<PAR_TAG> tag_state;
2788 // parsing main loop
2789 for (Paragraph::size_type i = 0; i < par->size(); ++i) {
2791 PAR_TAG tag_close = NONE;
2792 list < PAR_TAG > tag_open;
2794 LyXFont const font = par->getFont(params, i);
2796 if (font_old.family() != font.family()) {
2797 switch (family_type) {
2798 case LyXFont::SANS_FAMILY:
2801 case LyXFont::TYPEWRITER_FAMILY:
2808 family_type = font.family();
2810 switch (family_type) {
2811 case LyXFont::SANS_FAMILY:
2812 tag_open.push_back(SF);
2814 case LyXFont::TYPEWRITER_FAMILY:
2815 tag_open.push_back(TT);
2822 if (font_old.series() != font.series()) {
2823 switch (series_type) {
2824 case LyXFont::BOLD_SERIES:
2831 series_type = font.series();
2833 switch (series_type) {
2834 case LyXFont::BOLD_SERIES:
2835 tag_open.push_back(BF);
2843 if (font_old.shape() != font.shape()) {
2844 switch (shape_type) {
2845 case LyXFont::ITALIC_SHAPE:
2848 case LyXFont::SLANTED_SHAPE:
2855 shape_type = font.shape();
2857 switch (shape_type) {
2858 case LyXFont::ITALIC_SHAPE:
2859 tag_open.push_back(IT);
2861 case LyXFont::SLANTED_SHAPE:
2862 tag_open.push_back(SL);
2869 if (font_old.emph() != font.emph()) {
2870 if (font.emph() == LyXFont::ON) {
2871 tag_open.push_back(EM);
2880 list < PAR_TAG > temp;
2881 while(!tag_state.empty() && tag_close ) {
2882 PAR_TAG k = tag_state.top();
2884 os << "</" << tag_name(k) << ">";
2891 for(list< PAR_TAG >::const_iterator j = temp.begin();
2892 j != temp.end(); ++j) {
2894 os << "<" << tag_name(*j) << ">";
2897 for(list< PAR_TAG >::const_iterator j = tag_open.begin();
2898 j != tag_open.end(); ++j) {
2900 os << "<" << tag_name(*j) << ">";
2903 char c = par->getChar(i);
2905 if (c == Paragraph::META_INSET) {
2906 Inset * inset = par->getInset(i);
2907 inset->linuxdoc(this, os);
2912 if (style.latexparam() == "CDATA") {
2913 // "TeX"-Mode on == > SGML-Mode on.
2919 if (par->linuxDocConvertChar(c, sgml_string)
2920 && !style.free_spacing) {
2921 // in freespacing mode, spaces are
2922 // non-breaking characters
2923 if (desc_on) {// if char is ' ' then...
2926 linux_doc_line_break(os, char_line_count, 6);
2930 linux_doc_line_break(os, char_line_count, 1);
2935 char_line_count += sgml_string.length();
2941 while (!tag_state.empty()) {
2942 os << "</" << tag_name(tag_state.top()) << ">";
2946 // resets description flag correctly
2948 // <tag> not closed...
2949 linux_doc_line_break(os, char_line_count, 6);
2955 // Print an error message.
2956 void Buffer::sgmlError(Paragraph * par, int pos,
2957 string const & message) const
2959 // insert an error marker in text
2960 InsetError * new_inset = new InsetError(message);
2961 par->insertInset(pos, new_inset);
2965 void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
2967 ofstream ofs(fname.c_str());
2969 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2973 Paragraph * par = paragraph;
2975 niceFile = nice; // this will be used by Insetincludes.
2977 LyXTextClass const & tclass =
2978 textclasslist.TextClass(params.textclass);
2980 LaTeXFeatures features(params, tclass.numLayouts());
2985 string top_element = textclasslist.LatexnameOfClass(params.textclass);
2988 ofs << "<!DOCTYPE " << top_element
2989 << " PUBLIC \"-//OASIS//DTD DocBook V4.1//EN\"";
2991 string preamble = params.preamble;
2992 preamble += features.getIncludedFiles(fname);
2993 preamble += features.getLyXSGMLEntities();
2995 if (!preamble.empty()) {
2996 ofs << "\n [ " << preamble << " ]";
3001 string top = top_element;
3003 top += params.language->code();
3006 if (!params.options.empty()) {
3008 top += params.options;
3010 sgmlOpenTag(ofs, 0, top);
3012 ofs << "<!-- DocBook file was created by " << lyx_docversion
3013 << "\n See http://www.lyx.org/ for more information -->\n";
3015 vector<string> environment_stack(10);
3016 vector<string> environment_inner(10);
3017 vector<string> command_stack(10);
3019 bool command_flag = false;
3020 Paragraph::depth_type command_depth = 0;
3021 Paragraph::depth_type command_base = 0;
3022 Paragraph::depth_type cmd_depth = 0;
3023 Paragraph::depth_type depth = 0; // paragraph depth
3026 string command_name;
3032 int desc_on = 0; // description mode
3034 LyXLayout const & style =
3035 textclasslist.Style(params.textclass,
3038 // environment tag closing
3039 for (; depth > par->params().depth(); --depth) {
3040 if (environment_inner[depth] != "!-- --") {
3041 item_name = "listitem";
3042 sgmlCloseTag(ofs, command_depth + depth,
3044 if (environment_inner[depth] == "varlistentry")
3045 sgmlCloseTag(ofs, depth+command_depth,
3046 environment_inner[depth]);
3048 sgmlCloseTag(ofs, depth + command_depth,
3049 environment_stack[depth]);
3050 environment_stack[depth].erase();
3051 environment_inner[depth].erase();
3054 if (depth == par->params().depth()
3055 && environment_stack[depth] != style.latexname()
3056 && !environment_stack[depth].empty()) {
3057 if (environment_inner[depth] != "!-- --") {
3058 item_name= "listitem";
3059 sgmlCloseTag(ofs, command_depth+depth,
3061 if (environment_inner[depth] == "varlistentry")
3063 depth + command_depth,
3064 environment_inner[depth]);
3067 sgmlCloseTag(ofs, depth + command_depth,
3068 environment_stack[depth]);
3070 environment_stack[depth].erase();
3071 environment_inner[depth].erase();
3074 // Write opening SGML tags.
3075 switch (style.latextype) {
3076 case LATEX_PARAGRAPH:
3077 sgmlOpenTag(ofs, depth + command_depth,
3084 _("Error : Wrong depth for "
3085 "LatexType Command.\n"));
3087 command_name = style.latexname();
3089 sgmlparam = style.latexparam();
3090 c_params = split(sgmlparam, c_depth,'|');
3092 cmd_depth = lyx::atoi(c_depth);
3095 if (cmd_depth < command_base) {
3096 for (Paragraph::depth_type j = command_depth; j >= command_base; --j)
3097 sgmlCloseTag(ofs, j, command_stack[j]);
3098 command_depth = command_base = cmd_depth;
3099 } else if (cmd_depth <= command_depth) {
3100 for (int j = command_depth; j >= int(cmd_depth); --j)
3101 sgmlCloseTag(ofs, j, command_stack[j]);
3102 command_depth = cmd_depth;
3104 command_depth = cmd_depth;
3106 command_depth = command_base = cmd_depth;
3107 command_flag = true;
3109 if (command_stack.size() == command_depth + 1)
3110 command_stack.push_back(string());
3111 command_stack[command_depth] = command_name;
3113 // treat label as a special case for
3114 // more WYSIWYM handling.
3115 if (par->getChar(0) == Paragraph::META_INSET) {
3116 Inset * inset = par->getInset(0);
3117 Inset::Code lyx_code = inset->lyxCode();
3118 if (lyx_code == Inset::LABEL_CODE){
3119 command_name += " id=\"";
3120 command_name += (static_cast<InsetCommand *>(inset))->getContents();
3121 command_name += "\"";
3126 sgmlOpenTag(ofs, depth + command_depth, command_name);
3127 if (c_params.empty())
3128 item_name = "title";
3130 item_name = c_params;
3131 sgmlOpenTag(ofs, depth + 1 + command_depth, item_name);
3134 case LATEX_ENVIRONMENT:
3135 case LATEX_ITEM_ENVIRONMENT:
3136 if (depth < par->params().depth()) {
3137 depth = par->params().depth();
3138 environment_stack[depth].erase();
3141 if (environment_stack[depth] != style.latexname()) {
3142 if(environment_stack.size() == depth + 1) {
3143 environment_stack.push_back("!-- --");
3144 environment_inner.push_back("!-- --");
3146 environment_stack[depth] = style.latexname();
3147 environment_inner[depth] = "!-- --";
3148 sgmlOpenTag(ofs, depth + command_depth,
3149 environment_stack[depth]);
3151 if (environment_inner[depth] != "!-- --") {
3152 item_name= "listitem";
3154 command_depth + depth,
3156 if (environment_inner[depth] == "varlistentry")
3158 depth + command_depth,
3159 environment_inner[depth]);
3163 if (style.latextype == LATEX_ENVIRONMENT) {
3164 if (!style.latexparam().empty()) {
3165 if(style.latexparam() == "CDATA")
3168 sgmlOpenTag(ofs, depth + command_depth,
3169 style.latexparam());
3174 desc_on = (style.labeltype == LABEL_MANUAL);
3177 environment_inner[depth]= "varlistentry";
3179 environment_inner[depth]= "listitem";
3181 sgmlOpenTag(ofs, depth + 1 + command_depth,
3182 environment_inner[depth]);
3186 sgmlOpenTag(ofs, depth + 1 + command_depth,
3190 sgmlOpenTag(ofs, depth + 1 + command_depth,
3195 sgmlOpenTag(ofs, depth + command_depth,
3201 simpleDocBookOnePar(ofs, extra_par, par, desc_on,
3202 depth + 1 + command_depth);
3206 // write closing SGML tags
3207 switch (style.latextype) {
3209 if (c_params.empty())
3213 sgmlCloseTag(ofs, depth + command_depth, end_tag);
3215 case LATEX_ENVIRONMENT:
3216 if (!style.latexparam().empty()) {
3217 if(style.latexparam() == "CDATA")
3220 sgmlCloseTag(ofs, depth + command_depth,
3221 style.latexparam());
3224 case LATEX_ITEM_ENVIRONMENT:
3225 if (desc_on == 1) break;
3227 sgmlCloseTag(ofs, depth + 1 + command_depth, end_tag);
3229 case LATEX_PARAGRAPH:
3230 sgmlCloseTag(ofs, depth + command_depth, style.latexname());
3233 sgmlCloseTag(ofs, depth + command_depth, style.latexname());
3239 for (int d = depth; d >= 0; --d) {
3240 if (!environment_stack[depth].empty()) {
3241 if (environment_inner[depth] != "!-- --") {
3242 item_name = "listitem";
3243 sgmlCloseTag(ofs, command_depth + depth,
3245 if (environment_inner[depth] == "varlistentry")
3246 sgmlCloseTag(ofs, depth + command_depth,
3247 environment_inner[depth]);
3250 sgmlCloseTag(ofs, depth + command_depth,
3251 environment_stack[depth]);
3255 for (int j = command_depth; j >= 0 ; --j)
3256 if (!command_stack[j].empty())
3257 sgmlCloseTag(ofs, j, command_stack[j]);
3260 sgmlCloseTag(ofs, 0, top_element);
3263 // How to check for successful close
3267 void Buffer::simpleDocBookOnePar(ostream & os, string & extra,
3268 Paragraph * par, int & desc_on,
3269 Paragraph::depth_type depth) const
3271 bool emph_flag = false;
3273 LyXLayout const & style = textclasslist.Style(params.textclass,
3276 LyXFont font_old = style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
3278 int char_line_count = depth;
3279 //if (!style.free_spacing)
3280 // os << string(depth,' ');
3282 // parsing main loop
3283 for (Paragraph::size_type i = 0;
3284 i < par->size(); ++i) {
3285 LyXFont font = par->getFont(params, i);
3287 // handle <emphasis> tag
3288 if (font_old.emph() != font.emph()) {
3289 if (font.emph() == LyXFont::ON) {
3293 os << "</emphasis>";
3298 char c = par->getChar(i);
3300 if (c == Paragraph::META_INSET) {
3301 Inset * inset = par->getInset(i);
3303 inset->docbook(this, ost);
3304 string tmp_out = ost.str().c_str();
3307 // This code needs some explanation:
3308 // Two insets are treated specially
3309 // label if it is the first element in a command paragraph
3311 // graphics inside tables or figure floats can't go on
3312 // title (the equivalente in latex for this case is caption
3313 // and title should come first
3316 if (desc_on!= 3 || i!= 0) {
3317 if (!tmp_out.empty() && tmp_out[0] == '@') {
3319 extra += frontStrip(tmp_out, '@');
3321 os << frontStrip(tmp_out, '@');
3328 par->linuxDocConvertChar(c, sgml_string);
3330 if (style.pass_thru) {
3332 } else if(style.free_spacing || c != ' ') {
3334 } else if (desc_on ==1) {
3336 os << "\n</term><listitem><para>";
3346 os << "</emphasis>";
3349 // resets description flag correctly
3351 // <term> not closed...
3354 if(style.free_spacing) os << '\n';
3358 // This should be enabled when the Chktex class is implemented. (Asger)
3359 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
3360 // Other flags: -wall -v0 -x
3361 int Buffer::runChktex()
3363 if (!users->text) return 0;
3365 users->owner()->prohibitInput();
3367 // get LaTeX-Filename
3368 string const name = getLatexName();
3369 string path = OnlyPath(filename);
3371 string const org_path = path;
3372 if (lyxrc.use_tempdir || !IsDirWriteable(path)) {
3376 Path p(path); // path to LaTeX file
3377 users->owner()->message(_("Running chktex..."));
3379 // Remove all error insets
3380 bool const removedErrorInsets = users->removeAutoInsets();
3382 // Generate the LaTeX file if neccessary
3383 makeLaTeXFile(name, org_path, false);
3386 Chktex chktex(lyxrc.chktex_command, name, filepath);
3387 int res = chktex.run(terr); // run chktex
3390 WriteAlert(_("chktex did not work!"),
3391 _("Could not run with file:"), name);
3392 } else if (res > 0) {
3393 // Insert all errors as errors boxes
3394 users->insertErrors(terr);
3397 // if we removed error insets before we ran chktex or if we inserted
3398 // error insets after we ran chktex, this must be run:
3399 if (removedErrorInsets || res){
3403 users->owner()->allowInput();
3409 void Buffer::validate(LaTeXFeatures & features) const
3411 Paragraph * par = paragraph;
3412 LyXTextClass const & tclass =
3413 textclasslist.TextClass(params.textclass);
3415 // AMS Style is at document level
3416 features.amsstyle = (params.use_amsmath ||
3417 tclass.provides(LyXTextClass::amsmath));
3420 // We don't use "lyxerr.debug" because of speed. (Asger)
3421 if (lyxerr.debugging(Debug::LATEX))
3422 lyxerr << "Paragraph: " << par << endl;
3424 // Now just follow the list of paragraphs and run
3425 // validate on each of them.
3426 par->validate(features);
3428 // and then the next paragraph
3432 // the bullet shapes are buffer level not paragraph level
3433 // so they are tested here
3434 for (int i = 0; i < 4; ++i) {
3435 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
3436 int const font = params.user_defined_bullets[i].getFont();
3438 int const c = params
3439 .user_defined_bullets[i]
3446 features.latexsym = true;
3448 } else if (font == 1) {
3449 features.amssymb = true;
3450 } else if ((font >= 2 && font <= 5)) {
3451 features.pifont = true;
3456 if (lyxerr.debugging(Debug::LATEX)) {
3457 features.showStruct();
3462 // This function should be in Buffer because it's a buffer's property (ale)
3463 string const Buffer::getIncludeonlyList(char delim)
3466 for (inset_iterator it = inset_iterator_begin();
3467 it != inset_iterator_end(); ++it) {
3468 if ((*it)->lyxCode() == Inset::INCLUDE_CODE) {
3469 InsetInclude * insetinc =
3470 static_cast<InsetInclude *>(*it);
3471 if (insetinc->isIncludeOnly()) {
3474 lst += insetinc->getRelFileBaseName();
3478 lyxerr[Debug::INFO] << "Includeonly(" << lst << ')' << endl;
3483 vector<string> const Buffer::getLabelList()
3485 /// if this is a child document and the parent is already loaded
3486 /// Use the parent's list instead [ale990407]
3487 if (!params.parentname.empty()
3488 && bufferlist.exists(params.parentname)) {
3489 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3491 return tmp->getLabelList();
3494 vector<string> label_list;
3495 for (inset_iterator it = inset_iterator_begin();
3496 it != inset_iterator_end(); ++it) {
3497 vector<string> const l = (*it)->getLabelList();
3498 label_list.insert(label_list.end(), l.begin(), l.end());
3504 Buffer::Lists const Buffer::getLists() const
3507 Paragraph * par = paragraph;
3510 std::pair<bool, LyXTextClassList::size_type> const tmp =
3511 textclasslist.NumberOfLayout(params.textclass, "Caption");
3512 bool const found = tmp.first;
3513 LyXTextClassList::size_type const cap = tmp.second;
3516 // This is the prefered way to to this, but boost::tie can break
3519 LyXTextClassList::size_type cap;
3520 boost::tie(found, cap) = textclasslist
3521 .NumberOfLayout(params.textclass, "Caption");
3525 char const labeltype =
3526 textclasslist.Style(params.textclass,
3527 par->getLayout()).labeltype;
3529 if (labeltype >= LABEL_COUNTER_CHAPTER
3530 && labeltype <= LABEL_COUNTER_CHAPTER + params.tocdepth) {
3531 // insert this into the table of contents
3532 SingleList & item = l["TOC"];
3535 textclasslist.TextClass(params.textclass).maxcounter());
3536 item.push_back(TocItem(par, depth, par->asString(this, true)));
3538 // For each paragrph, traverse its insets and look for
3542 Paragraph::inset_iterator it =
3543 par->inset_iterator_begin();
3544 Paragraph::inset_iterator end =
3545 par->inset_iterator_end();
3547 for (; it != end; ++it) {
3548 if ((*it)->lyxCode() == Inset::FLOAT_CODE) {
3550 static_cast<InsetFloat*>(*it);
3552 string const type = il->type();
3554 // Now find the caption in the float...
3555 // We now tranverse the paragraphs of
3557 Paragraph * tmp = il->inset.paragraph();
3559 if (tmp->layout == cap) {
3560 SingleList & item = l[type];
3562 tostr(item.size()+1) + ". " + tmp->asString(this, false);
3563 item.push_back(TocItem(tmp, 0 , str));
3570 lyxerr << "caption not found" << endl;
3579 // This is also a buffer property (ale)
3580 vector<pair<string, string> > const Buffer::getBibkeyList()
3582 /// if this is a child document and the parent is already loaded
3583 /// Use the parent's list instead [ale990412]
3584 if (!params.parentname.empty() && bufferlist.exists(params.parentname)) {
3585 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3587 return tmp->getBibkeyList();
3590 vector<pair<string, string> > keys;
3591 Paragraph * par = paragraph;
3594 keys.push_back(pair<string, string>(par->bibkey->getContents(),
3595 par->asString(this, false)));
3599 // Might be either using bibtex or a child has bibliography
3601 for (inset_iterator it = inset_iterator_begin();
3602 it != inset_iterator_end(); ++it) {
3603 // Search for Bibtex or Include inset
3604 if ((*it)->lyxCode() == Inset::BIBTEX_CODE) {
3605 vector<pair<string,string> > tmp =
3606 static_cast<InsetBibtex*>(*it)->getKeys(this);
3607 keys.insert(keys.end(), tmp.begin(), tmp.end());
3608 } else if ((*it)->lyxCode() == Inset::INCLUDE_CODE) {
3609 vector<pair<string,string> > const tmp =
3610 static_cast<InsetInclude*>(*it)->getKeys();
3611 keys.insert(keys.end(), tmp.begin(), tmp.end());
3620 bool Buffer::isDepClean(string const & name) const
3622 DEPCLEAN * item = dep_clean;
3623 while (item && item->master != name)
3625 if (!item) return true;
3630 void Buffer::markDepClean(string const & name)
3633 dep_clean = new DEPCLEAN;
3634 dep_clean->clean = true;
3635 dep_clean->master = name;
3636 dep_clean->next = 0;
3638 DEPCLEAN * item = dep_clean;
3639 while (item && item->master != name)
3644 item = new DEPCLEAN;
3646 item->master = name;
3653 bool Buffer::dispatch(string const & command)
3655 // Split command string into command and argument
3657 string line = frontStrip(command);
3658 string const arg = strip(frontStrip(split(line, cmd, ' ')));
3660 return dispatch(lyxaction.LookupFunc(cmd), arg);
3664 bool Buffer::dispatch(int action, string const & argument)
3666 bool dispatched = true;
3669 Exporter::Export(this, argument, false);
3679 void Buffer::resizeInsets(BufferView * bv)
3681 /// then remove all LyXText in text-insets
3682 Paragraph * par = paragraph;
3683 for (; par; par = par->next()) {
3684 par->resizeInsetsLyXText(bv);
3689 void Buffer::redraw()
3696 void Buffer::changeLanguage(Language const * from, Language const * to)
3699 ParIterator end = par_iterator_end();
3700 for (ParIterator it = par_iterator_begin(); it != end; ++it)
3701 (*it)->changeLanguage(params, from, to);
3705 bool Buffer::isMultiLingual()
3707 ParIterator end = par_iterator_end();
3708 for (ParIterator it = par_iterator_begin(); it != end; ++it)
3709 if ((*it)->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);
3774 ParIterator Buffer::par_iterator_begin()
3776 return ParIterator(paragraph);
3780 ParIterator Buffer::par_iterator_end()
3782 return ParIterator();