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 * ======================================================
18 #pragma implementation
22 #include "bufferlist.h"
24 #include "LyXAction.h"
27 #include "tex-strings.h"
29 #include "bufferview_funcs.h"
36 #include "LaTeXFeatures.h"
43 #include "converter.h"
44 #include "BufferView.h"
45 #include "ParagraphParameters.h"
46 #include "iterators.h"
47 #include "lyxtextclasslist.h"
49 #include "mathed/formulamacro.h"
50 #include "mathed/formula.h"
52 #include "insets/inset.h"
53 #include "insets/inseterror.h"
54 #include "insets/insetlabel.h"
55 #include "insets/insetref.h"
56 #include "insets/inseturl.h"
57 #include "insets/insetnote.h"
58 #include "insets/insetquotes.h"
59 #include "insets/insetlatexaccent.h"
60 #include "insets/insetbib.h"
61 #include "insets/insetcite.h"
62 #include "insets/insetexternal.h"
63 #include "insets/insetindex.h"
64 #include "insets/insetinclude.h"
65 #include "insets/insettoc.h"
66 #include "insets/insetparent.h"
67 #include "insets/insetspecialchar.h"
68 #include "insets/insettext.h"
69 #include "insets/insetert.h"
70 #include "insets/insetgraphics.h"
71 #include "insets/insetfoot.h"
72 #include "insets/insetmarginal.h"
73 #include "insets/insetminipage.h"
74 #include "insets/insetfloat.h"
75 #include "insets/insettabular.h"
77 #include "insets/insettheorem.h"
78 #include "insets/insetlist.h"
80 #include "insets/insetcaption.h"
81 #include "insets/insetfloatlist.h"
83 #include "frontends/Dialogs.h"
84 #include "frontends/Alert.h"
86 #include "support/textutils.h"
87 #include "support/filetools.h"
88 #include "support/path.h"
89 #include "support/os.h"
90 #include "support/lyxlib.h"
91 #include "support/FileInfo.h"
92 #include "support/lyxmanip.h"
93 #include "support/lyxalgo.h" // for lyx::count
105 #include <sys/types.h>
122 using std::make_pair;
131 using lyx::textclass_type;
133 // all these externs should eventually be removed.
134 extern BufferList bufferlist;
136 extern LyXAction lyxaction;
140 const int LYX_FORMAT = 220;
144 extern int tex_code_break_column;
147 Buffer::Buffer(string const & file, bool ronly)
148 : paragraph(0), niceFile(true), lyx_clean(true), bak_clean(true),
149 unnamed(false), dep_clean(0), read_only(ronly),
150 filename_(file), users(0)
152 lyxerr[Debug::INFO] << "Buffer::Buffer()" << endl;
154 filepath_ = OnlyPath(file);
159 // read_only = ronly;
163 if (read_only || lyxrc.use_tempdir) {
164 tmppath = CreateBufferTmpDir();
173 lyxerr[Debug::INFO] << "Buffer::~Buffer()" << endl;
174 // here the buffer should take care that it is
175 // saved properly, before it goes into the void.
177 // make sure that views using this buffer
182 if (!tmppath.empty()) {
183 DestroyBufferTmpDir(tmppath);
186 Paragraph * par = paragraph;
189 tmppar = par->next();
197 string const Buffer::getLatexName(bool no_path) const
199 string const name = ChangeExtension(MakeLatexName(fileName()), ".tex");
201 return OnlyFilename(name);
207 pair<Buffer::LogType, string> const Buffer::getLogName(void) const
209 string const filename = getLatexName(false);
211 if (filename.empty())
212 return make_pair(Buffer::latexlog, string());
214 string path = OnlyPath(filename);
216 if (lyxrc.use_tempdir || !IsDirWriteable(path))
219 string const fname = AddName(path,
220 OnlyFilename(ChangeExtension(filename,
223 AddName(path, OnlyFilename(
224 ChangeExtension(filename,
225 formats.extension("literate") + ".out")));
227 // If no Latex log or Build log is newer, show Build log
229 FileInfo const f_fi(fname);
230 FileInfo const b_fi(bname);
233 (!f_fi.exist() || f_fi.getModificationTime() < b_fi.getModificationTime())) {
234 lyxerr[Debug::FILES] << "Log name calculated as : " << bname << endl;
235 return make_pair(Buffer::buildlog, bname);
237 lyxerr[Debug::FILES] << "Log name calculated as : " << fname << endl;
238 return make_pair(Buffer::latexlog, fname);
242 void Buffer::setReadonly(bool flag)
244 if (read_only != flag) {
247 users->owner()->getDialogs()->updateBufferDependent(false);
252 /// Update window titles of all users
253 // Should work on a list
254 void Buffer::updateTitles() const
257 users->owner()->updateWindowTitle();
261 /// Reset autosave timer of all users
262 // Should work on a list
263 void Buffer::resetAutosaveTimers() const
266 users->owner()->resetAutosaveTimer();
270 void Buffer::setFileName(string const & newfile)
272 filename_ = MakeAbsPath(newfile);
273 filepath_ = OnlyPath(filename_);
274 setReadonly(IsFileWriteable(filename_) == 0);
279 // We'll remove this later. (Lgb)
282 string last_inset_read;
284 #ifndef NO_COMPABILITY
287 ErtComp() : active(false), in_tabular(false) {
295 std::stack<ErtComp> ert_stack;
300 #warning And _why_ is this here? (Lgb)
308 // candidate for move to BufferView
309 // (at least some parts in the beginning of the func)
312 // changed to be public and have one parameter
313 // if par = 0 normal behavior
314 // else insert behavior
315 // Returns false if "\the_end" is not read for formats >= 2.13. (Asger)
316 bool Buffer::readLyXformat2(LyXLex & lex, Paragraph * par)
320 #ifndef NO_COMPABILITY
321 ert_comp.contents.erase();
322 ert_comp.active = false;
323 ert_comp.in_tabular = false;
326 Paragraph::depth_type depth = 0;
327 bool the_end_read = false;
329 Paragraph * first_par = 0;
330 LyXFont font(LyXFont::ALL_INHERIT, params.language);
331 if (file_format < 216 && params.language->lang() == "hebrew")
332 font.setLanguage(default_language);
337 // We are inserting into an existing document
338 users->text->breakParagraph(users);
339 first_par = users->text->ownerParagraph();
342 // We don't want to adopt the parameters from the
343 // document we insert, so we skip until the text begins:
346 string const pretoken = lex.getString();
347 if (pretoken == "\\layout") {
348 lex.pushToken(pretoken);
356 string const token = lex.getString();
358 if (token.empty()) continue;
360 lyxerr[Debug::PARSER] << "Handling token: `"
361 << token << "'" << endl;
364 parseSingleLyXformat2Token(lex, par, first_par,
372 paragraph = first_par;
374 if (unknown_layouts > 0) {
375 string s = _("Couldn't set the layout for ");
376 if (unknown_layouts == 1) {
377 s += _("one paragraph");
379 s += tostr(unknown_layouts);
380 s += _(" paragraphs");
382 Alert::alert(_("Textclass Loading Error!"), s,
383 _("When reading " + fileName()));
386 if (unknown_tokens > 0) {
387 string s = _("Encountered ");
388 if (unknown_tokens == 1) {
389 s += _("one unknown token");
391 s += tostr(unknown_tokens);
392 s += _(" unknown tokens");
394 Alert::alert(_("Textclass Loading Error!"), s,
395 _("When reading " + fileName()));
402 #ifndef NO_COMPABILITY
403 void Buffer::insertErtContents(Paragraph * par, int & pos, bool set_inactive)
405 if (!ert_comp.contents.empty()) {
406 lyxerr[Debug::INSETS] << "ERT contents:\n'"
407 << ert_comp.contents << "'" << endl;
408 Inset * inset = new InsetERT(params, params.language,
409 ert_comp.contents, true);
410 par->insertInset(pos++, inset, ert_comp.font);
411 ert_comp.contents.erase();
414 ert_comp.active = false;
421 Buffer::parseSingleLyXformat2Token(LyXLex & lex, Paragraph *& par,
422 Paragraph *& first_par,
423 string const & token, int & pos,
424 Paragraph::depth_type & depth,
428 bool the_end_read = false;
429 #ifndef NO_COMPABILITY
430 #ifndef NO_PEXTRA_REALLY
431 // This is super temporary but is needed to get the compability
432 // mode for minipages work correctly together with new tabulars.
433 static int call_depth;
435 bool checkminipage = false;
436 static Paragraph * minipar = 0;
437 static Paragraph * parBeforeMinipage;
440 if (token[0] != '\\') {
441 #ifndef NO_COMPABILITY
442 if (ert_comp.active) {
443 ert_comp.contents += token;
446 for (string::const_iterator cit = token.begin();
447 cit != token.end(); ++cit) {
448 par->insertChar(pos, (*cit), font);
451 #ifndef NO_COMPABILITY
454 } else if (token == "\\i") {
455 Inset * inset = new InsetLatexAccent;
456 inset->read(this, lex);
457 par->insertInset(pos, inset, font);
459 } else if (token == "\\layout") {
460 #ifndef NO_COMPABILITY
461 ert_comp.in_tabular = false;
463 insertErtContents(par, pos);
466 string layoutname = lex.getString();
468 LyXTextClass const & tclass = textclasslist[params.textclass];
470 if (layoutname.empty()) {
471 layoutname = tclass.defaultLayoutName();
474 bool hasLayout = tclass.hasLayout(layoutname);
476 lyxerr << "Layout '" << layoutname << "' does not"
477 << " exist in textclass '" << tclass.name()
479 lyxerr << "Trying to use default layout instead."
481 layoutname = tclass.defaultLayoutName();
484 #ifndef NO_COMPABILITY
485 if (compare_no_case(layoutname, "latex") == 0) {
486 ert_comp.active = true;
487 ert_comp.font = font;
491 // The is the compability reading of layout caption.
492 // It can be removed in LyX version 1.3.0. (Lgb)
493 if (compare_no_case(layoutname, "caption") == 0) {
494 // We expect that the par we are now working on is
495 // really inside a InsetText inside a InsetFloat.
496 // We also know that captions can only be
497 // one paragraph. (Lgb)
499 // We should now read until the next "\layout"
501 // This is probably not good enough, what if the
502 // caption is the last par in the document (Lgb)
503 istream & ist = lex.getStream();
509 if (prefixIs(line, "\\layout")) {
513 if (prefixIs(line, "\\begin_inset"))
515 if (prefixIs(line, "\\end_inset")) {
526 // Now we should have the whole layout in ss
527 // we should now be able to give this to the
529 ss << "\\end_inset\n";
531 // This seems like a bug in stringstream.
532 // We really should be able to use ss
534 istringstream is(ss.str());
536 tmplex.setStream(is);
537 Inset * inset = new InsetCaption;
538 inset->Read(this, tmplex);
539 par->InsertInset(pos, inset, font);
546 par = new Paragraph(par);
549 par->layout(layoutname);
550 // Test whether the layout is obsolete.
551 LyXLayout const & layout =
552 textclasslist[params.textclass][par->layout()];
553 if (!layout.obsoleted_by().empty())
554 par->layout(layout.obsoleted_by());
555 par->params().depth(depth);
556 font = LyXFont(LyXFont::ALL_INHERIT, params.language);
557 if (file_format < 216
558 && params.language->lang() == "hebrew")
559 font.setLanguage(default_language);
564 #ifndef NO_COMPABILITY
565 } else if (token == "\\begin_float") {
566 insertErtContents(par, pos);
567 //insertErtContents(par, pos, false);
568 //ert_stack.push(ert_comp);
569 //ert_comp = ErtComp();
571 // This is the compability reader. It can be removed in
572 // LyX version 1.3.0. (Lgb)
574 string const tmptok = lex.getString();
575 //lyxerr << "old float: " << tmptok << endl;
578 stringstream old_float;
580 if (tmptok == "footnote") {
581 inset = new InsetFoot(params);
582 old_float << "collapsed true\n";
583 } else if (tmptok == "margin") {
584 inset = new InsetMarginal(params);
585 old_float << "collapsed true\n";
586 } else if (tmptok == "fig") {
587 inset = new InsetFloat(params, "figure");
588 old_float << "placement htbp\n"
590 << "collapsed false\n";
591 } else if (tmptok == "tab") {
592 inset = new InsetFloat(params, "table");
593 old_float << "placement htbp\n"
595 << "collapsed false\n";
596 } else if (tmptok == "alg") {
597 inset = new InsetFloat(params, "algorithm");
598 old_float << "placement htbp\n"
600 << "collapsed false\n";
601 } else if (tmptok == "wide-fig") {
602 inset = new InsetFloat(params, "figure");
603 //InsetFloat * tmp = new InsetFloat("figure");
606 old_float << "placement htbp\n"
608 << "collapsed false\n";
609 } else if (tmptok == "wide-tab") {
610 inset = new InsetFloat(params, "table");
611 //InsetFloat * tmp = new InsetFloat("table");
614 old_float << "placement htbp\n"
616 << "collapsed false\n";
620 #ifndef NO_PEXTRA_REALLY
623 return false; // no end read yet
626 // Here we need to check for \end_deeper and handle that
627 // before we do the footnote parsing.
628 // This _is_ a hack! (Lgb)
631 string const tmp = lex.getString();
632 if (tmp == "\\end_deeper") {
633 //lyxerr << "\\end_deeper caught!" << endl;
635 lex.printError("\\end_deeper: "
636 "depth is already null");
641 old_float << tmp << ' ';
646 old_float << lex.getLongString("\\end_float")
647 << "\n\\end_inset\n";
648 //lyxerr << "Float Body:\n" << old_float.str() << endl;
649 // That this does not work seems like a bug
650 // in stringstream. (Lgb)
651 istringstream istr(old_float.str());
653 nylex.setStream(istr);
654 inset->read(this, nylex);
655 par->insertInset(pos, inset, font);
657 insertErtContents(par, pos);
659 } else if (token == "\\begin_deeper") {
661 } else if (token == "\\end_deeper") {
663 lex.printError("\\end_deeper: "
664 "depth is already null");
668 } else if (token == "\\begin_preamble") {
669 params.readPreamble(lex);
670 } else if (token == "\\textclass") {
672 pair<bool, textclass_type> pp =
673 textclasslist.NumberOfClass(lex.getString());
675 params.textclass = pp.second;
677 Alert::alert(string(_("Textclass error")),
678 string(_("The document uses an unknown textclass \"")) +
679 lex.getString() + string("\"."),
680 string(_("LyX will not be able to produce output correctly.")));
681 params.textclass = 0;
683 if (!textclasslist[params.textclass].load()) {
684 // if the textclass wasn't loaded properly
685 // we need to either substitute another
686 // or stop loading the file.
687 // I can substitute but I don't see how I can
688 // stop loading... ideas?? ARRae980418
689 Alert::alert(_("Textclass Loading Error!"),
690 string(_("Can't load textclass ")) +
691 textclasslist[params.textclass].name(),
692 _("-- substituting default"));
693 params.textclass = 0;
695 } else if (token == "\\options") {
697 params.options = lex.getString();
698 } else if (token == "\\language") {
699 params.readLanguage(lex);
700 } else if (token == "\\fontencoding") {
702 } else if (token == "\\inputencoding") {
704 params.inputenc = lex.getString();
705 } else if (token == "\\graphics") {
706 params.readGraphicsDriver(lex);
707 } else if (token == "\\fontscheme") {
709 params.fonts = lex.getString();
710 } else if (token == "\\noindent") {
711 par->params().noindent(true);
712 } else if (token == "\\fill_top") {
713 par->params().spaceTop(VSpace(VSpace::VFILL));
714 } else if (token == "\\fill_bottom") {
715 par->params().spaceBottom(VSpace(VSpace::VFILL));
716 } else if (token == "\\line_top") {
717 par->params().lineTop(true);
718 } else if (token == "\\line_bottom") {
719 par->params().lineBottom(true);
720 } else if (token == "\\pagebreak_top") {
721 par->params().pagebreakTop(true);
722 } else if (token == "\\pagebreak_bottom") {
723 par->params().pagebreakBottom(true);
724 } else if (token == "\\start_of_appendix") {
725 par->params().startOfAppendix(true);
726 } else if (token == "\\paragraph_separation") {
727 int tmpret = lex.findToken(string_paragraph_separation);
730 if (tmpret != LYX_LAYOUT_DEFAULT)
731 params.paragraph_separation =
732 static_cast<BufferParams::PARSEP>(tmpret);
733 } else if (token == "\\defskip") {
735 params.defskip = VSpace(lex.getString());
736 #ifndef NO_COMPABILITY
737 } else if (token == "\\epsfig") { // obsolete
738 // Indeed it is obsolete, but we HAVE to be backwards
739 // compatible until 0.14, because otherwise all figures
740 // in existing documents are irretrivably lost. (Asger)
741 params.readGraphicsDriver(lex);
743 } else if (token == "\\quotes_language") {
744 int tmpret = lex.findToken(string_quotes_language);
747 if (tmpret != LYX_LAYOUT_DEFAULT) {
748 InsetQuotes::quote_language tmpl =
749 InsetQuotes::EnglishQ;
752 tmpl = InsetQuotes::EnglishQ;
755 tmpl = InsetQuotes::SwedishQ;
758 tmpl = InsetQuotes::GermanQ;
761 tmpl = InsetQuotes::PolishQ;
764 tmpl = InsetQuotes::FrenchQ;
767 tmpl = InsetQuotes::DanishQ;
770 params.quotes_language = tmpl;
772 } else if (token == "\\quotes_times") {
774 switch (lex.getInteger()) {
776 params.quotes_times = InsetQuotes::SingleQ;
779 params.quotes_times = InsetQuotes::DoubleQ;
782 } else if (token == "\\papersize") {
783 int tmpret = lex.findToken(string_papersize);
787 params.papersize2 = tmpret;
788 } else if (token == "\\paperpackage") {
789 int tmpret = lex.findToken(string_paperpackages);
792 params.paperpackage = BufferParams::PACKAGE_NONE;
794 params.paperpackage = tmpret;
795 } else if (token == "\\use_geometry") {
797 params.use_geometry = lex.getInteger();
798 } else if (token == "\\use_amsmath") {
800 params.use_amsmath = lex.getInteger();
801 } else if (token == "\\use_natbib") {
803 params.use_natbib = lex.getInteger();
804 } else if (token == "\\use_numerical_citations") {
806 params.use_numerical_citations = lex.getInteger();
807 } else if (token == "\\paperorientation") {
808 int tmpret = lex.findToken(string_orientation);
811 if (tmpret != LYX_LAYOUT_DEFAULT)
812 params.orientation = static_cast<BufferParams::PAPER_ORIENTATION>(tmpret);
813 } else if (token == "\\paperwidth") {
815 params.paperwidth = lex.getString();
816 } else if (token == "\\paperheight") {
818 params.paperheight = lex.getString();
819 } else if (token == "\\leftmargin") {
821 params.leftmargin = lex.getString();
822 } else if (token == "\\topmargin") {
824 params.topmargin = lex.getString();
825 } else if (token == "\\rightmargin") {
827 params.rightmargin = lex.getString();
828 } else if (token == "\\bottommargin") {
830 params.bottommargin = lex.getString();
831 } else if (token == "\\headheight") {
833 params.headheight = lex.getString();
834 } else if (token == "\\headsep") {
836 params.headsep = lex.getString();
837 } else if (token == "\\footskip") {
839 params.footskip = lex.getString();
840 } else if (token == "\\paperfontsize") {
842 params.fontsize = strip(lex.getString());
843 } else if (token == "\\papercolumns") {
845 params.columns = lex.getInteger();
846 } else if (token == "\\papersides") {
848 switch (lex.getInteger()) {
850 case 1: params.sides = LyXTextClass::OneSide; break;
851 case 2: params.sides = LyXTextClass::TwoSides; break;
853 } else if (token == "\\paperpagestyle") {
855 params.pagestyle = strip(lex.getString());
856 } else if (token == "\\bullet") {
858 int const index = lex.getInteger();
860 int temp_int = lex.getInteger();
861 params.user_defined_bullets[index].setFont(temp_int);
862 params.temp_bullets[index].setFont(temp_int);
864 temp_int = lex.getInteger();
865 params.user_defined_bullets[index].setCharacter(temp_int);
866 params.temp_bullets[index].setCharacter(temp_int);
868 temp_int = lex.getInteger();
869 params.user_defined_bullets[index].setSize(temp_int);
870 params.temp_bullets[index].setSize(temp_int);
872 string const temp_str = lex.getString();
873 if (temp_str != "\\end_bullet") {
874 // this element isn't really necessary for
875 // parsing but is easier for humans
876 // to understand bullets. Put it back and
877 // set a debug message?
878 lex.printError("\\end_bullet expected, got" + temp_str);
879 //how can I put it back?
881 } else if (token == "\\bulletLaTeX") {
882 // The bullet class should be able to read this.
884 int const index = lex.getInteger();
886 string temp_str = lex.getString();
888 while (temp_str != "\\end_bullet") {
889 // this loop structure is needed when user
890 // enters an empty string since the first
891 // thing returned will be the \\end_bullet
893 // if the LaTeX entry has spaces. Each element
894 // therefore needs to be read in turn
897 temp_str = lex.getString();
900 params.user_defined_bullets[index].setText(sum_str);
901 params.temp_bullets[index].setText(sum_str);
902 } else if (token == "\\secnumdepth") {
904 params.secnumdepth = lex.getInteger();
905 } else if (token == "\\tocdepth") {
907 params.tocdepth = lex.getInteger();
908 } else if (token == "\\spacing") {
910 string const tmp = strip(lex.getString());
911 Spacing::Space tmp_space = Spacing::Default;
913 if (tmp == "single") {
914 tmp_space = Spacing::Single;
915 } else if (tmp == "onehalf") {
916 tmp_space = Spacing::Onehalf;
917 } else if (tmp == "double") {
918 tmp_space = Spacing::Double;
919 } else if (tmp == "other") {
921 tmp_space = Spacing::Other;
922 tmp_val = lex.getFloat();
924 lex.printError("Unknown spacing token: '$$Token'");
926 // Small hack so that files written with klyx will be
929 par->params().spacing(Spacing(tmp_space, tmp_val));
931 params.spacing.set(tmp_space, tmp_val);
933 } else if (token == "\\paragraph_spacing") {
935 string const tmp = strip(lex.getString());
936 if (tmp == "single") {
937 par->params().spacing(Spacing(Spacing::Single));
938 } else if (tmp == "onehalf") {
939 par->params().spacing(Spacing(Spacing::Onehalf));
940 } else if (tmp == "double") {
941 par->params().spacing(Spacing(Spacing::Double));
942 } else if (tmp == "other") {
944 par->params().spacing(Spacing(Spacing::Other,
947 lex.printError("Unknown spacing token: '$$Token'");
949 } else if (token == "\\float_placement") {
951 params.float_placement = lex.getString();
952 } else if (token == "\\family") {
954 font.setLyXFamily(lex.getString());
955 } else if (token == "\\series") {
957 font.setLyXSeries(lex.getString());
958 } else if (token == "\\shape") {
960 font.setLyXShape(lex.getString());
961 } else if (token == "\\size") {
963 font.setLyXSize(lex.getString());
964 #ifndef NO_COMPABILITY
965 } else if (token == "\\latex") {
967 string const tok = lex.getString();
968 if (tok == "no_latex") {
970 insertErtContents(par, pos);
971 } else if (tok == "latex") {
972 ert_comp.active = true;
973 ert_comp.font = font;
974 } else if (tok == "default") {
976 insertErtContents(par, pos);
978 lex.printError("Unknown LaTeX font flag "
982 } else if (token == "\\lang") {
984 string const tok = lex.getString();
985 Language const * lang = languages.getLanguage(tok);
987 font.setLanguage(lang);
989 font.setLanguage(params.language);
990 lex.printError("Unknown language `$$Token'");
992 } else if (token == "\\numeric") {
994 font.setNumber(font.setLyXMisc(lex.getString()));
995 } else if (token == "\\emph") {
997 font.setEmph(font.setLyXMisc(lex.getString()));
998 } else if (token == "\\bar") {
1000 string const tok = lex.getString();
1001 // This is dirty, but gone with LyX3. (Asger)
1003 font.setUnderbar(LyXFont::ON);
1004 else if (tok == "no")
1005 font.setUnderbar(LyXFont::OFF);
1006 else if (tok == "default")
1007 font.setUnderbar(LyXFont::INHERIT);
1009 lex.printError("Unknown bar font flag "
1011 } else if (token == "\\noun") {
1013 font.setNoun(font.setLyXMisc(lex.getString()));
1014 } else if (token == "\\color") {
1016 font.setLyXColor(lex.getString());
1017 } else if (token == "\\align") {
1018 int tmpret = lex.findToken(string_align);
1019 if (tmpret == -1) ++tmpret;
1020 if (tmpret != LYX_LAYOUT_DEFAULT) { // tmpret != 99 ???
1021 int const tmpret2 = int(pow(2.0, tmpret));
1022 //lyxerr << "Tmpret2 = " << tmpret2 << endl;
1023 par->params().align(LyXAlignment(tmpret2));
1025 } else if (token == "\\added_space_top") {
1027 VSpace value = VSpace(lex.getString());
1028 if ((value.length().len().value() != 0) ||
1029 (value.kind() != VSpace::LENGTH))
1030 par->params().spaceTop(value);
1031 } else if (token == "\\added_space_bottom") {
1033 VSpace value = VSpace(lex.getString());
1034 if ((value.length().len().value() != 0) ||
1035 (value.kind() != VSpace::LENGTH))
1036 par->params().spaceBottom(value);
1037 #ifndef NO_COMPABILITY
1038 #ifndef NO_PEXTRA_REALLY
1039 } else if (token == "\\pextra_type") {
1041 par->params().pextraType(lex.getInteger());
1042 } else if (token == "\\pextra_width") {
1044 par->params().pextraWidth(lex.getString());
1045 } else if (token == "\\pextra_widthp") {
1047 par->params().pextraWidthp(lex.getString());
1048 } else if (token == "\\pextra_alignment") {
1050 par->params().pextraAlignment(lex.getInteger());
1051 } else if (token == "\\pextra_hfill") {
1053 par->params().pextraHfill(lex.getInteger());
1054 } else if (token == "\\pextra_start_minipage") {
1056 par->params().pextraStartMinipage(lex.getInteger());
1059 } else if (token == "\\labelwidthstring") {
1061 par->params().labelWidthString(lex.getString());
1062 // do not delete this token, it is still needed!
1063 } else if (token == "\\end_inset") {
1064 lyxerr << "Solitary \\end_inset. Missing \\begin_inset?.\n"
1065 << "Last inset read was: " << last_inset_read
1067 // Simply ignore this. The insets do not have
1069 // But insets should read it, it is a part of
1070 // the inset isn't it? Lgb.
1071 } else if (token == "\\begin_inset") {
1072 #ifndef NO_COMPABILITY
1073 insertErtContents(par, pos, false);
1074 ert_stack.push(ert_comp);
1075 ert_comp = ErtComp();
1077 readInset(lex, par, pos, font);
1078 #ifndef NO_COMPABILITY
1079 ert_comp = ert_stack.top();
1081 insertErtContents(par, pos);
1083 } else if (token == "\\SpecialChar") {
1084 LyXLayout const & layout =
1085 textclasslist[params.textclass][par->layout()];
1087 // Insets don't make sense in a free-spacing context! ---Kayvan
1088 if (layout.free_spacing || par->isFreeSpacing()) {
1091 string next_token = lex.getString();
1092 if (next_token == "\\-") {
1093 par->insertChar(pos, '-', font);
1094 } else if (next_token == "\\protected_separator"
1095 || next_token == "~") {
1096 par->insertChar(pos, ' ', font);
1098 lex.printError("Token `$$Token' "
1100 "paragraph layout!");
1105 Inset * inset = new InsetSpecialChar;
1106 inset->read(this, lex);
1107 par->insertInset(pos, inset, font);
1110 } else if (token == "\\newline") {
1111 #ifndef NO_COMPABILITY
1112 if (!ert_comp.in_tabular && ert_comp.active) {
1113 ert_comp.contents += char(Paragraph::META_NEWLINE);
1115 // Since we cannot know it this is only a regular
1116 // newline or a tabular cell delimter we have to
1117 // handle the ERT here.
1118 insertErtContents(par, pos, false);
1120 par->insertChar(pos, Paragraph::META_NEWLINE, font);
1124 par->insertChar(pos, Paragraph::META_NEWLINE, font);
1127 } else if (token == "\\LyXTable") {
1128 #ifndef NO_COMPABILITY
1129 ert_comp.in_tabular = true;
1131 Inset * inset = new InsetTabular(*this);
1132 inset->read(this, lex);
1133 par->insertInset(pos, inset, font);
1135 } else if (token == "\\hfill") {
1136 par->insertChar(pos, Paragraph::META_HFILL, font);
1138 } else if (token == "\\protected_separator") { // obsolete
1139 // This is a backward compability thingie. (Lgb)
1140 // Remove it later some time...introduced with fileformat
1142 LyXLayout const & layout =
1143 textclasslist[params.textclass][par->layout()];
1145 if (layout.free_spacing || par->isFreeSpacing()) {
1146 par->insertChar(pos, ' ', font);
1148 Inset * inset = new InsetSpecialChar(InsetSpecialChar::PROTECTED_SEPARATOR);
1149 par->insertInset(pos, inset, font);
1152 } else if (token == "\\bibitem") { // ale970302
1154 InsetCommandParams p("bibitem", "dummy");
1155 par->bibkey = new InsetBibKey(p);
1157 par->bibkey->read(this, lex);
1158 } else if (token == "\\backslash") {
1159 #ifndef NO_COMPABILITY
1160 if (ert_comp.active) {
1161 ert_comp.contents += "\\";
1164 par->insertChar(pos, '\\', font);
1166 #ifndef NO_COMPABILITY
1169 } else if (token == "\\the_end") {
1170 #ifndef NO_COMPABILITY
1171 // If we still have some ert active here we have to insert
1172 // it so we don't loose it. (Lgb)
1173 insertErtContents(par, pos);
1175 the_end_read = true;
1176 #ifndef NO_COMPABILITY
1177 #ifndef NO_PEXTRA_REALLY
1180 minipar = parBeforeMinipage = 0;
1184 #ifndef NO_COMPABILITY
1185 if (ert_comp.active) {
1186 ert_comp.contents += token;
1189 // This should be insurance for the future: (Asger)
1192 string const s = _("Unknown token: ") + token
1193 + " " + lex.text() + "\n";
1195 InsetError * new_inset = new InsetError(s);
1196 par->insertInset(pos, new_inset, LyXFont(LyXFont::ALL_INHERIT,
1199 #ifndef NO_COMPABILITY
1204 #ifndef NO_COMPABILITY
1205 #ifndef NO_PEXTRA_REALLY
1206 // I wonder if we could use this blanket fix for all the
1207 // checkminipage cases...
1208 // don't forget about ert paragraphs and compatibility read for'em
1209 if (par && (par->size() || !ert_comp.contents.empty())) {
1210 // It is possible that this will check to often,
1211 // but that should not be an correctness issue.
1212 // Only a speed issue.
1213 checkminipage = true;
1216 // now check if we have a minipage paragraph as at this
1217 // point we already read all the necessary data!
1218 // this cannot be done in layout because there we did
1219 // not read yet the paragraph PEXTRA-params (Jug)
1221 // BEGIN pextra_minipage compability
1222 // This should be removed in 1.3.x (Lgb)
1223 // I don't think we should remove this so fast (Jug)
1225 // This compability code is not perfect. In a couple
1226 // of rand cases it fails. When the minipage par is
1227 // the first par in the document, and when there are
1228 // none or only one regular paragraphs after the
1229 // minipage. Currently I am not investing any effort
1230 // in fixing those cases.
1232 //lyxerr << "Call depth: " << call_depth << endl;
1233 if (checkminipage && (call_depth == 1)) {
1234 checkminipage = false;
1235 if (minipar && (minipar != par) &&
1236 (par->params().pextraType() == Paragraph::PEXTRA_MINIPAGE))
1238 lyxerr << "minipages in a row" << endl;
1239 if (par->params().pextraStartMinipage()) {
1240 lyxerr << "start new minipage" << endl;
1241 // minipages in a row
1242 par->previous()->next(0);
1245 Paragraph * tmp = minipar;
1247 tmp->params().pextraType(0);
1248 tmp->params().pextraWidth(string());
1249 tmp->params().pextraWidthp(string());
1250 tmp->params().pextraAlignment(0);
1251 tmp->params().pextraHfill(false);
1252 tmp->params().pextraStartMinipage(false);
1255 // create a new paragraph to insert the
1256 // minipages in the following case
1257 if (par->params().pextraStartMinipage() &&
1258 !par->params().pextraHfill()) {
1259 Paragraph * p = new Paragraph;
1260 p->layout(textclasslist[params.textclass].defaultLayoutName());
1262 p->previous(parBeforeMinipage);
1263 parBeforeMinipage->next(p);
1265 p->params().depth(parBeforeMinipage->params().depth());
1266 parBeforeMinipage = p;
1268 InsetMinipage * mini = new InsetMinipage(params);
1269 mini->pos(static_cast<InsetMinipage::Position>(par->params().pextraAlignment()));
1270 mini->pageWidth(LyXLength(par->params().pextraWidth()));
1271 if (!par->params().pextraWidthp().empty()) {
1272 lyxerr << "WP:" << mini->pageWidth().asString() << endl;
1273 mini->pageWidth(LyXLength((par->params().pextraWidthp())+"p%"));
1275 Paragraph * op = mini->firstParagraph();
1276 mini->inset.paragraph(par);
1278 // and free the old ones!
1281 Paragraph * pp = op->next();
1285 // Insert the minipage last in the
1286 // previous paragraph.
1287 if (par->params().pextraHfill()) {
1288 parBeforeMinipage->insertChar
1289 (parBeforeMinipage->size(), Paragraph::META_HFILL);
1291 parBeforeMinipage->insertInset
1292 (parBeforeMinipage->size(), mini);
1296 lyxerr << "new minipage par" << endl;
1297 //nothing to do just continue reading
1300 } else if (minipar && (minipar != par)) {
1301 lyxerr << "last minipage par read" << endl;
1302 // The last paragraph read was not part of a
1303 // minipage but the par linked list is...
1304 // So we need to remove the last par from the
1306 if (par->previous())
1307 par->previous()->next(0);
1308 par->previous(parBeforeMinipage);
1309 parBeforeMinipage->next(par);
1310 Paragraph * tmp = minipar;
1312 tmp->params().pextraType(0);
1313 tmp->params().pextraWidth(string());
1314 tmp->params().pextraWidthp(string());
1315 tmp->params().pextraAlignment(0);
1316 tmp->params().pextraHfill(false);
1317 tmp->params().pextraStartMinipage(false);
1320 depth = parBeforeMinipage->params().depth();
1321 // and set this depth on the par as it has not been set already
1322 par->params().depth(depth);
1323 minipar = parBeforeMinipage = 0;
1324 } else if (!minipar &&
1325 (par->params().pextraType() == Paragraph::PEXTRA_MINIPAGE))
1327 // par is the first paragraph in a minipage
1328 lyxerr << "begin minipage" << endl;
1329 // To minimize problems for
1330 // the users we will insert
1331 // the first minipage in
1332 // a sequence of minipages
1333 // in its own paragraph.
1334 Paragraph * p = new Paragraph;
1335 p->layout(textclasslist[params.textclass].defaultLayoutName());
1336 p->previous(par->previous());
1338 p->params().depth(depth);
1339 par->params().depth(0);
1341 if (par->previous())
1342 par->previous()->next(p);
1344 parBeforeMinipage = p;
1346 if (!first_par || (first_par == par))
1349 InsetMinipage * mini = new InsetMinipage(params);
1350 mini->pos(static_cast<InsetMinipage::Position>(minipar->params().pextraAlignment()));
1351 mini->pageWidth(LyXLength(minipar->params().pextraWidth()));
1352 if (!par->params().pextraWidthp().empty()) {
1353 lyxerr << "WP:" << mini->pageWidth().asString() << endl;
1354 mini->pageWidth(LyXLength((par->params().pextraWidthp())+"p%"));
1357 Paragraph * op = mini->firstParagraph();
1358 mini->inset.paragraph(minipar);
1360 // and free the old ones!
1363 Paragraph * pp = op->next();
1368 // Insert the minipage last in the
1369 // previous paragraph.
1370 if (minipar->params().pextraHfill()) {
1371 parBeforeMinipage->insertChar
1372 (parBeforeMinipage->size(),Paragraph::META_HFILL);
1374 parBeforeMinipage->insertInset
1375 (parBeforeMinipage->size(), mini);
1378 // End of pextra_minipage compability
1382 return the_end_read;
1385 // needed to insert the selection
1386 void Buffer::insertStringAsLines(Paragraph *& par, pos_type & pos,
1387 LyXFont const & fn,string const & str) const
1389 LyXLayout const & layout =
1390 textclasslist[params.textclass][par->layout()];
1393 par->checkInsertChar(font);
1394 // insert the string, don't insert doublespace
1395 bool space_inserted = true;
1396 for(string::const_iterator cit = str.begin();
1397 cit != str.end(); ++cit) {
1399 if (par->size() || layout.keepempty) {
1400 par->breakParagraph(params, pos,
1401 layout.isEnvironment());
1404 space_inserted = true;
1408 // do not insert consecutive spaces if !free_spacing
1409 } else if ((*cit == ' ' || *cit == '\t') &&
1410 space_inserted && !layout.free_spacing &&
1411 !par->isFreeSpacing())
1414 } else if (*cit == '\t') {
1415 if (!layout.free_spacing && !par->isFreeSpacing()) {
1416 // tabs are like spaces here
1417 par->insertChar(pos, ' ', font);
1419 space_inserted = true;
1421 const pos_type nb = 8 - pos % 8;
1422 for (pos_type a = 0; a < nb ; ++a) {
1423 par->insertChar(pos, ' ', font);
1426 space_inserted = true;
1428 } else if (!IsPrintable(*cit)) {
1429 // Ignore unprintables
1432 // just insert the character
1433 par->insertChar(pos, *cit, font);
1435 space_inserted = (*cit == ' ');
1442 void Buffer::readInset(LyXLex & lex, Paragraph *& par,
1443 int & pos, LyXFont & font)
1445 // consistency check
1446 if (lex.getString() != "\\begin_inset") {
1447 lyxerr << "Buffer::readInset: Consistency check failed."
1454 string const tmptok = lex.getString();
1455 last_inset_read = tmptok;
1457 // test the different insets
1458 if (tmptok == "LatexCommand") {
1459 InsetCommandParams inscmd;
1462 string const cmdName = inscmd.getCmdName();
1464 // This strange command allows LyX to recognize "natbib" style
1465 // citations: citet, citep, Citet etc.
1466 if (compare_no_case(cmdName, "cite", 4) == 0) {
1467 inset = new InsetCitation(inscmd);
1468 } else if (cmdName == "bibitem") {
1469 lex.printError("Wrong place for bibitem");
1470 inset = new InsetBibKey(inscmd);
1471 } else if (cmdName == "BibTeX") {
1472 inset = new InsetBibtex(inscmd);
1473 } else if (cmdName == "index") {
1474 inset = new InsetIndex(inscmd);
1475 } else if (cmdName == "include") {
1476 inset = new InsetInclude(inscmd, *this);
1477 } else if (cmdName == "label") {
1478 inset = new InsetLabel(inscmd);
1479 } else if (cmdName == "url"
1480 || cmdName == "htmlurl") {
1481 inset = new InsetUrl(inscmd);
1482 } else if (cmdName == "ref"
1483 || cmdName == "pageref"
1484 || cmdName == "vref"
1485 || cmdName == "vpageref"
1486 || cmdName == "prettyref") {
1487 if (!inscmd.getOptions().empty()
1488 || !inscmd.getContents().empty()) {
1489 inset = new InsetRef(inscmd, *this);
1491 } else if (cmdName == "tableofcontents") {
1492 inset = new InsetTOC(inscmd);
1493 } else if (cmdName == "listofalgorithms") {
1494 inset = new InsetFloatList("algorithm");
1495 } else if (cmdName == "listoffigures") {
1496 inset = new InsetFloatList("figure");
1497 } else if (cmdName == "listoftables") {
1498 inset = new InsetFloatList("table");
1499 } else if (cmdName == "printindex") {
1500 inset = new InsetPrintIndex(inscmd);
1501 } else if (cmdName == "lyxparent") {
1502 inset = new InsetParent(inscmd, *this);
1505 bool alreadyread = false;
1506 if (tmptok == "Quotes") {
1507 inset = new InsetQuotes;
1508 } else if (tmptok == "External") {
1509 inset = new InsetExternal;
1510 } else if (tmptok == "FormulaMacro") {
1511 inset = new InsetFormulaMacro;
1512 } else if (tmptok == "Formula") {
1513 inset = new InsetFormula;
1514 } else if (tmptok == "Figure") { // Backward compatibility
1515 // inset = new InsetFig(100, 100, *this);
1516 inset = new InsetGraphics;
1517 } else if (tmptok == "Graphics") {
1518 inset = new InsetGraphics;
1519 } else if (tmptok == "Info") {// backwards compatibility
1520 inset = new InsetNote(this,
1521 lex.getLongString("\\end_inset"),
1524 } else if (tmptok == "Note") {
1525 inset = new InsetNote(params);
1526 } else if (tmptok == "Include") {
1527 InsetCommandParams p("Include");
1528 inset = new InsetInclude(p, *this);
1529 } else if (tmptok == "ERT") {
1530 inset = new InsetERT(params);
1531 } else if (tmptok == "Tabular") {
1532 inset = new InsetTabular(*this);
1533 } else if (tmptok == "Text") {
1534 inset = new InsetText(params);
1535 } else if (tmptok == "Foot") {
1536 inset = new InsetFoot(params);
1537 } else if (tmptok == "Marginal") {
1538 inset = new InsetMarginal(params);
1539 } else if (tmptok == "Minipage") {
1540 inset = new InsetMinipage(params);
1541 } else if (tmptok == "Float") {
1543 string tmptok = lex.getString();
1544 inset = new InsetFloat(params, tmptok);
1546 } else if (tmptok == "List") {
1547 inset = new InsetList;
1548 } else if (tmptok == "Theorem") {
1549 inset = new InsetList;
1551 } else if (tmptok == "Caption") {
1552 inset = new InsetCaption(params);
1553 } else if (tmptok == "FloatList") {
1554 inset = new InsetFloatList;
1557 if (inset && !alreadyread) inset->read(this, lex);
1561 par->insertInset(pos, inset, font);
1567 bool Buffer::readFile(LyXLex & lex, Paragraph * par)
1571 string const token(lex.getString());
1572 if (token == "\\lyxformat") { // the first token _must_ be...
1574 string tmp_format = lex.getString();
1575 //lyxerr << "LyX Format: `" << tmp_format << "'" << endl;
1576 // if present remove ".," from string.
1577 string::size_type dot = tmp_format.find_first_of(".,");
1578 //lyxerr << " dot found at " << dot << endl;
1579 if (dot != string::npos)
1580 tmp_format.erase(dot, 1);
1581 file_format = strToInt(tmp_format);
1582 if (file_format == LYX_FORMAT) {
1584 } else if (file_format > LYX_FORMAT) {
1586 Alert::alert(_("Warning!"),
1587 _("LyX file format is newer that what"),
1588 _("is supported in this LyX version. Expect some problems."));
1590 } else if (file_format < LYX_FORMAT) {
1592 if (file_format < 200) {
1593 Alert::alert(_("ERROR!"),
1594 _("Old LyX file format found. "
1595 "Use LyX 0.10.x to read this!"));
1599 bool the_end = readLyXformat2(lex, par);
1600 params.setPaperStuff();
1601 // the_end was added in 213
1602 if (file_format < 213)
1606 Alert::alert(_("Warning!"),
1607 _("Reading of document is not complete"),
1608 _("Maybe the document is truncated"));
1611 } else { // "\\lyxformat" not found
1612 Alert::alert(_("ERROR!"), _("Not a LyX file!"));
1615 Alert::alert(_("ERROR!"), _("Unable to read file!"));
1620 // Should probably be moved to somewhere else: BufferView? LyXView?
1621 bool Buffer::save() const
1623 // We don't need autosaves in the immediate future. (Asger)
1624 resetAutosaveTimers();
1628 if (lyxrc.make_backup) {
1629 s = fileName() + '~';
1630 if (!lyxrc.backupdir_path.empty())
1631 s = AddName(lyxrc.backupdir_path,
1632 subst(os::slashify_path(s),'/','!'));
1634 // Rename is the wrong way of making a backup,
1635 // this is the correct way.
1636 /* truss cp fil fil2:
1637 lstat("LyXVC3.lyx", 0xEFFFF898) Err#2 ENOENT
1638 stat("LyXVC.lyx", 0xEFFFF688) = 0
1639 open("LyXVC.lyx", O_RDONLY) = 3
1640 open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
1641 fstat(4, 0xEFFFF508) = 0
1642 fstat(3, 0xEFFFF508) = 0
1643 read(3, " # T h i s f i l e w".., 8192) = 5579
1644 write(4, " # T h i s f i l e w".., 5579) = 5579
1645 read(3, 0xEFFFD4A0, 8192) = 0
1648 chmod("LyXVC3.lyx", 0100644) = 0
1649 lseek(0, 0, SEEK_CUR) = 46440
1653 // Should probably have some more error checking here.
1654 // Should be cleaned up in 0.13, at least a bit.
1655 // Doing it this way, also makes the inodes stay the same.
1656 // This is still not a very good solution, in particular we
1657 // might loose the owner of the backup.
1658 FileInfo finfo(fileName());
1659 if (finfo.exist()) {
1660 mode_t fmode = finfo.getMode();
1661 struct utimbuf times = {
1662 finfo.getAccessTime(),
1663 finfo.getModificationTime() };
1665 ifstream ifs(fileName().c_str());
1666 ofstream ofs(s.c_str(), ios::out|ios::trunc);
1671 ::chmod(s.c_str(), fmode);
1673 if (::utime(s.c_str(), ×)) {
1674 lyxerr << "utime error." << endl;
1677 lyxerr << "LyX was not able to make "
1678 "backup copy. Beware." << endl;
1683 if (writeFile(fileName(), false)) {
1685 removeAutosaveFile(fileName());
1687 // Saving failed, so backup is not backup
1688 if (lyxrc.make_backup) {
1689 lyx::rename(s, fileName());
1697 // Returns false if unsuccesful
1698 bool Buffer::writeFile(string const & fname, bool flag) const
1700 // if flag is false writeFile will not create any GUI
1701 // warnings, only cerr.
1702 // Needed for autosave in background or panic save (Matthias 120496)
1704 if (read_only && (fname == fileName())) {
1705 // Here we should come with a question if we should
1706 // perform the write anyway.
1708 lyxerr << _("Error! Document is read-only: ")
1711 Alert::alert(_("Error! Document is read-only: "),
1716 FileInfo finfo(fname);
1717 if (finfo.exist() && !finfo.writable()) {
1718 // Here we should come with a question if we should
1719 // try to do the save anyway. (i.e. do a chmod first)
1721 lyxerr << _("Error! Cannot write file: ")
1724 Alert::err_alert(_("Error! Cannot write file: "),
1729 ofstream ofs(fname.c_str());
1732 lyxerr << _("Error! Cannot open file: ")
1735 Alert::err_alert(_("Error! Cannot open file: "),
1741 // Use the standard "C" locale for file output.
1742 ofs.imbue(std::locale::classic());
1745 // The top of the file should not be written by params.
1747 // write out a comment in the top of the file
1748 ofs << '#' << lyx_docversion
1749 << " created this file. For more info see http://www.lyx.org/\n"
1750 << "\\lyxformat " << LYX_FORMAT << "\n";
1752 // now write out the buffer paramters.
1753 params.writeFile(ofs);
1755 Paragraph::depth_type depth = 0;
1757 // this will write out all the paragraphs
1758 // using recursive descent.
1759 paragraph->writeFile(this, ofs, params, depth);
1761 // Write marker that shows file is complete
1762 ofs << "\n\\the_end" << endl;
1766 // how to check if close went ok?
1767 // Following is an attempt... (BE 20001011)
1769 // good() returns false if any error occured, including some
1770 // formatting error.
1771 // bad() returns true if something bad happened in the buffer,
1772 // which should include file system full errors.
1779 lyxerr << "Buffer::writeFile: BAD ERROR!" << endl;
1781 lyxerr << "Buffer::writeFile: NOT SO BAD ERROR!"
1793 pair<int, string> const addDepth(int depth, int ldepth)
1797 d += (ldepth - depth) * 2;
1798 return make_pair(d, string(d, ' '));
1804 string const Buffer::asciiParagraph(Paragraph const * par,
1805 unsigned int linelen,
1806 bool noparbreak) const
1808 ostringstream buffer;
1809 Paragraph::depth_type depth = 0;
1811 Paragraph::depth_type ltype_depth = 0;
1812 bool ref_printed = false;
1813 // if (!par->previous()) {
1815 // begins or ends a deeper area ?
1816 if (depth != par->params().depth()) {
1817 if (par->params().depth() > depth) {
1818 while (par->params().depth() > depth) {
1822 while (par->params().depth() < depth) {
1828 depth = par->params().depth();
1831 // First write the layout
1832 string const & tmp = par->layout();
1833 if (compare_no_case(tmp, "itemize") == 0) {
1835 ltype_depth = depth + 1;
1836 } else if (compare_no_case(tmp, "enumerate") == 0) {
1838 ltype_depth = depth + 1;
1839 } else if (contains(lowercase(tmp), "ection")) {
1841 ltype_depth = depth + 1;
1842 } else if (contains(lowercase(tmp), "aragraph")) {
1844 ltype_depth = depth + 1;
1845 } else if (compare_no_case(tmp, "description") == 0) {
1847 ltype_depth = depth + 1;
1848 } else if (compare_no_case(tmp, "abstract") == 0) {
1851 } else if (compare_no_case(tmp, "bibliography") == 0) {
1859 /* maybe some vertical spaces */
1861 /* the labelwidthstring used in lists */
1865 /* some pagebreaks? */
1869 /* what about the alignment */
1871 // lyxerr << "Should this ever happen?" << endl;
1874 // linelen <= 0 is special and means we don't have pargraph breaks
1876 string::size_type currlinelen = 0;
1882 buffer << string(depth * 2, ' ');
1883 currlinelen += depth * 2;
1886 // we should probably change to the paragraph language in the
1887 // gettext here (if possible) so that strings are outputted in
1888 // the correct language! (20012712 Jug)
1892 case 4: // (Sub)Paragraph
1893 case 5: // Description
1897 buffer << _("Abstract") << "\n\n";
1900 string const abst = _("Abstract: ");
1902 currlinelen += abst.length();
1905 case 7: // Bibliography
1908 buffer << _("References") << "\n\n";
1911 string const refs = _("References: ");
1913 currlinelen += refs.length();
1921 string const parlab = par->params().labelString();
1922 buffer << parlab << " ";
1923 currlinelen += parlab.length() + 1;
1931 pair<int, string> p = addDepth(depth, ltype_depth);
1933 currlinelen += p.first;
1936 // this is to change the linebreak to do it by word a bit more
1937 // intelligent hopefully! (only in the case where we have a
1938 // max linelenght!) (Jug)
1942 for (pos_type i = 0; i < par->size(); ++i) {
1943 char c = par->getUChar(params, i);
1945 case Paragraph::META_INSET:
1947 Inset const * inset = par->getInset(i);
1951 currlinelen += word.length();
1954 if (inset->ascii(this, buffer, linelen)) {
1955 // to be sure it breaks paragraph
1956 currlinelen += linelen;
1962 case Paragraph::META_NEWLINE:
1964 buffer << word << "\n";
1967 pair<int, string> p = addDepth(depth,
1970 currlinelen = p.first;
1974 case Paragraph::META_HFILL:
1975 buffer << word << "\t";
1976 currlinelen += word.length() + 1;
1983 currlinelen + word.length() > linelen - 10) {
1985 pair<int, string> p =
1986 addDepth(depth, ltype_depth);
1988 currlinelen = p.first;
1991 buffer << word << ' ';
1992 currlinelen += word.length() + 1;
1999 lyxerr[Debug::INFO] <<
2000 "writeAsciiFile: NULL char in structure." << endl;
2002 if ((linelen > 0) &&
2003 (currlinelen + word.length()) > linelen)
2007 pair<int, string> p =
2008 addDepth(depth, ltype_depth);
2010 currlinelen = p.first;
2017 return buffer.str().c_str();
2021 void Buffer::writeFileAscii(string const & fname, int linelen)
2023 ofstream ofs(fname.c_str());
2025 Alert::err_alert(_("Error: Cannot write file:"), fname);
2028 writeFileAscii(ofs, linelen);
2032 void Buffer::writeFileAscii(ostream & ofs, int linelen)
2034 Paragraph * par = paragraph;
2036 ofs << asciiParagraph(par, linelen, par->previous() == 0);
2046 void Buffer::makeLaTeXFile(string const & fname,
2047 string const & original_path,
2048 bool nice, bool only_body)
2050 lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
2052 ofstream ofs(fname.c_str());
2054 Alert::err_alert(_("Error: Cannot open file: "), fname);
2058 niceFile = nice; // this will be used by Insetincludes.
2060 tex_code_break_column = lyxrc.ascii_linelen;
2062 // validate the buffer.
2063 lyxerr[Debug::LATEX] << " Validating buffer..." << endl;
2064 LaTeXFeatures features(params);
2066 lyxerr[Debug::LATEX] << " Buffer validation done." << endl;
2069 // The starting paragraph of the coming rows is the
2070 // first paragraph of the document. (Asger)
2071 texrow.start(paragraph, 0);
2073 if (!only_body && nice) {
2074 ofs << "%% " << lyx_docversion << " created this file. "
2075 "For more info, see http://www.lyx.org/.\n"
2076 "%% Do not edit unless you really know what "
2081 lyxerr[Debug::INFO] << "lyx header finished" << endl;
2082 // There are a few differences between nice LaTeX and usual files:
2083 // usual is \batchmode and has a
2084 // special input@path to allow the including of figures
2085 // with either \input or \includegraphics (what figinsets do).
2086 // batchmode is not set if there is a tex_code_break_column.
2087 // In this case somebody is interested in the generated LaTeX,
2088 // so this is OK. input@path is set when the actual parameter
2089 // original_path is set. This is done for usual tex-file, but not
2090 // for nice-latex-file. (Matthias 250696)
2093 // code for usual, NOT nice-latex-file
2094 ofs << "\\batchmode\n"; // changed
2095 // from \nonstopmode
2098 if (!original_path.empty()) {
2099 string inputpath = os::external_path(original_path);
2100 subst(inputpath, "~", "\\string~");
2101 ofs << "\\makeatletter\n"
2102 << "\\def\\input@path{{"
2103 << inputpath << "/}}\n"
2104 << "\\makeatother\n";
2110 ofs << "\\documentclass";
2112 LyXTextClass const & tclass = textclasslist[params.textclass];
2114 ostringstream options; // the document class options.
2116 if (tokenPos(tclass.opt_fontsize(),
2117 '|', params.fontsize) >= 0) {
2118 // only write if existing in list (and not default)
2119 options << params.fontsize << "pt,";
2123 if (!params.use_geometry &&
2124 (params.paperpackage == BufferParams::PACKAGE_NONE)) {
2125 switch (params.papersize) {
2126 case BufferParams::PAPER_A4PAPER:
2127 options << "a4paper,";
2129 case BufferParams::PAPER_USLETTER:
2130 options << "letterpaper,";
2132 case BufferParams::PAPER_A5PAPER:
2133 options << "a5paper,";
2135 case BufferParams::PAPER_B5PAPER:
2136 options << "b5paper,";
2138 case BufferParams::PAPER_EXECUTIVEPAPER:
2139 options << "executivepaper,";
2141 case BufferParams::PAPER_LEGALPAPER:
2142 options << "legalpaper,";
2148 if (params.sides != tclass.sides()) {
2149 switch (params.sides) {
2150 case LyXTextClass::OneSide:
2151 options << "oneside,";
2153 case LyXTextClass::TwoSides:
2154 options << "twoside,";
2160 if (params.columns != tclass.columns()) {
2161 if (params.columns == 2)
2162 options << "twocolumn,";
2164 options << "onecolumn,";
2167 if (!params.use_geometry
2168 && params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
2169 options << "landscape,";
2171 // language should be a parameter to \documentclass
2173 ostringstream language_options;
2174 if (params.language->babel() == "hebrew"
2175 && default_language->babel() != "hebrew")
2176 // This seems necessary
2177 features.useLanguage(default_language);
2179 if (lyxrc.language_use_babel ||
2180 params.language->lang() != lyxrc.default_language ||
2181 !features.hasLanguages()) {
2183 language_options << features.getLanguages();
2184 language_options << params.language->babel();
2185 if (lyxrc.language_global_options)
2186 options << language_options.str() << ',';
2189 // the user-defined options
2190 if (!params.options.empty()) {
2191 options << params.options << ',';
2194 string strOptions(options.str().c_str());
2195 if (!strOptions.empty()) {
2196 strOptions = strip(strOptions, ',');
2197 ofs << '[' << strOptions << ']';
2200 ofs << '{' << tclass.latexname() << "}\n";
2202 // end of \documentclass defs
2204 // font selection must be done before loading fontenc.sty
2205 // The ae package is not needed when using OT1 font encoding.
2206 if (params.fonts != "default" &&
2207 (params.fonts != "ae" || lyxrc.fontenc != "default")) {
2208 ofs << "\\usepackage{" << params.fonts << "}\n";
2210 if (params.fonts == "ae") {
2211 ofs << "\\usepackage{aecompl}\n";
2215 // this one is not per buffer
2216 if (lyxrc.fontenc != "default") {
2217 ofs << "\\usepackage[" << lyxrc.fontenc
2222 if (params.inputenc == "auto") {
2223 string const doc_encoding =
2224 params.language->encoding()->LatexName();
2226 // Create a list with all the input encodings used
2228 set<string> encodings = features.getEncodingSet(doc_encoding);
2230 ofs << "\\usepackage[";
2231 std::copy(encodings.begin(), encodings.end(),
2232 std::ostream_iterator<string>(ofs, ","));
2233 ofs << doc_encoding << "]{inputenc}\n";
2235 } else if (params.inputenc != "default") {
2236 ofs << "\\usepackage[" << params.inputenc
2241 // At the very beginning the text parameters.
2242 if (params.paperpackage != BufferParams::PACKAGE_NONE) {
2243 switch (params.paperpackage) {
2244 case BufferParams::PACKAGE_A4:
2245 ofs << "\\usepackage{a4}\n";
2248 case BufferParams::PACKAGE_A4WIDE:
2249 ofs << "\\usepackage{a4wide}\n";
2252 case BufferParams::PACKAGE_WIDEMARGINSA4:
2253 ofs << "\\usepackage[widemargins]{a4}\n";
2258 if (params.use_geometry) {
2259 ofs << "\\usepackage{geometry}\n";
2261 ofs << "\\geometry{verbose";
2262 if (params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
2263 ofs << ",landscape";
2264 switch (params.papersize2) {
2265 case BufferParams::VM_PAPER_CUSTOM:
2266 if (!params.paperwidth.empty())
2267 ofs << ",paperwidth="
2268 << params.paperwidth;
2269 if (!params.paperheight.empty())
2270 ofs << ",paperheight="
2271 << params.paperheight;
2273 case BufferParams::VM_PAPER_USLETTER:
2274 ofs << ",letterpaper";
2276 case BufferParams::VM_PAPER_USLEGAL:
2277 ofs << ",legalpaper";
2279 case BufferParams::VM_PAPER_USEXECUTIVE:
2280 ofs << ",executivepaper";
2282 case BufferParams::VM_PAPER_A3:
2285 case BufferParams::VM_PAPER_A4:
2288 case BufferParams::VM_PAPER_A5:
2291 case BufferParams::VM_PAPER_B3:
2294 case BufferParams::VM_PAPER_B4:
2297 case BufferParams::VM_PAPER_B5:
2301 // default papersize ie BufferParams::VM_PAPER_DEFAULT
2302 switch (lyxrc.default_papersize) {
2303 case BufferParams::PAPER_DEFAULT: // keep compiler happy
2304 case BufferParams::PAPER_USLETTER:
2305 ofs << ",letterpaper";
2307 case BufferParams::PAPER_LEGALPAPER:
2308 ofs << ",legalpaper";
2310 case BufferParams::PAPER_EXECUTIVEPAPER:
2311 ofs << ",executivepaper";
2313 case BufferParams::PAPER_A3PAPER:
2316 case BufferParams::PAPER_A4PAPER:
2319 case BufferParams::PAPER_A5PAPER:
2322 case BufferParams::PAPER_B5PAPER:
2327 if (!params.topmargin.empty())
2328 ofs << ",tmargin=" << params.topmargin;
2329 if (!params.bottommargin.empty())
2330 ofs << ",bmargin=" << params.bottommargin;
2331 if (!params.leftmargin.empty())
2332 ofs << ",lmargin=" << params.leftmargin;
2333 if (!params.rightmargin.empty())
2334 ofs << ",rmargin=" << params.rightmargin;
2335 if (!params.headheight.empty())
2336 ofs << ",headheight=" << params.headheight;
2337 if (!params.headsep.empty())
2338 ofs << ",headsep=" << params.headsep;
2339 if (!params.footskip.empty())
2340 ofs << ",footskip=" << params.footskip;
2345 if (tokenPos(tclass.opt_pagestyle(),
2346 '|', params.pagestyle) >= 0) {
2347 if (params.pagestyle == "fancy") {
2348 ofs << "\\usepackage{fancyhdr}\n";
2351 ofs << "\\pagestyle{" << params.pagestyle << "}\n";
2355 if (params.secnumdepth != tclass.secnumdepth()) {
2356 ofs << "\\setcounter{secnumdepth}{"
2357 << params.secnumdepth
2361 if (params.tocdepth != tclass.tocdepth()) {
2362 ofs << "\\setcounter{tocdepth}{"
2368 if (params.paragraph_separation) {
2369 switch (params.defskip.kind()) {
2370 case VSpace::SMALLSKIP:
2371 ofs << "\\setlength\\parskip{\\smallskipamount}\n";
2373 case VSpace::MEDSKIP:
2374 ofs << "\\setlength\\parskip{\\medskipamount}\n";
2376 case VSpace::BIGSKIP:
2377 ofs << "\\setlength\\parskip{\\bigskipamount}\n";
2379 case VSpace::LENGTH:
2380 ofs << "\\setlength\\parskip{"
2381 << params.defskip.length().asLatexString()
2384 default: // should never happen // Then delete it.
2385 ofs << "\\setlength\\parskip{\\medskipamount}\n";
2390 ofs << "\\setlength\\parindent{0pt}\n";
2394 // Now insert the LyX specific LaTeX commands...
2396 // The optional packages;
2397 string preamble(features.getPackages());
2399 // this might be useful...
2400 preamble += "\n\\makeatletter\n";
2402 // Some macros LyX will need
2403 string tmppreamble(features.getMacros());
2405 if (!tmppreamble.empty()) {
2406 preamble += "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2407 "LyX specific LaTeX commands.\n"
2408 + tmppreamble + '\n';
2411 // the text class specific preamble
2412 tmppreamble = features.getTClassPreamble();
2413 if (!tmppreamble.empty()) {
2414 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2415 "Textclass specific LaTeX commands.\n"
2416 + tmppreamble + '\n';
2419 /* the user-defined preamble */
2420 if (!params.preamble.empty()) {
2421 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2422 "User specified LaTeX commands.\n"
2423 + params.preamble + '\n';
2426 preamble += "\\makeatother\n";
2428 // Itemize bullet settings need to be last in case the user
2429 // defines their own bullets that use a package included
2430 // in the user-defined preamble -- ARRae
2431 // Actually it has to be done much later than that
2432 // since some packages like frenchb make modifications
2433 // at \begin{document} time -- JMarc
2435 for (int i = 0; i < 4; ++i) {
2436 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
2437 if (bullets_def.empty())
2438 bullets_def="\\AtBeginDocument{\n";
2439 bullets_def += " \\renewcommand{\\labelitemi";
2441 // `i' is one less than the item to modify
2448 bullets_def += "ii";
2454 bullets_def += "}{" +
2455 params.user_defined_bullets[i].getText()
2460 if (!bullets_def.empty())
2461 preamble += bullets_def + "}\n\n";
2464 int(lyx::count(preamble.begin(), preamble.end(), '\n'));
2465 for (int j = 0; j != nlines; ++j) {
2471 // We try to load babel late, in case it interferes
2472 // with other packages.
2474 string tmp = lyxrc.language_package;
2475 if (!lyxrc.language_global_options
2476 && tmp == "\\usepackage{babel}")
2477 tmp = string("\\usepackage[") +
2478 language_options.str().c_str() +
2485 ofs << "\\begin{document}\n";
2488 lyxerr[Debug::INFO] << "preamble finished, now the body." << endl;
2490 if (!lyxrc.language_auto_begin) {
2491 ofs << subst(lyxrc.language_command_begin, "$$lang",
2492 params.language->babel())
2497 latexParagraphs(ofs, paragraph, 0, texrow);
2499 // add this just in case after all the paragraphs
2503 if (!lyxrc.language_auto_end) {
2504 ofs << subst(lyxrc.language_command_end, "$$lang",
2505 params.language->babel())
2511 ofs << "\\end{document}\n";
2514 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
2516 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
2520 // Just to be sure. (Asger)
2523 // tex_code_break_column's value is used to decide
2524 // if we are in batchmode or not (within mathed_write()
2525 // in math_write.C) so we must set it to a non-zero
2526 // value when we leave otherwise we save incorrect .lyx files.
2527 tex_code_break_column = lyxrc.ascii_linelen;
2531 lyxerr << "File was not closed properly." << endl;
2534 lyxerr[Debug::INFO] << "Finished making latex file." << endl;
2535 lyxerr[Debug::INFO] << "Row count was " << texrow.rows()-1 << "." << endl;
2537 // we want this to be true outside previews (for insetexternal)
2543 // LaTeX all paragraphs from par to endpar, if endpar == 0 then to the end
2545 void Buffer::latexParagraphs(ostream & ofs, Paragraph * par,
2546 Paragraph * endpar, TexRow & texrow) const
2548 bool was_title = false;
2549 bool already_title = false;
2552 while (par != endpar) {
2553 Inset * in = par->inInset();
2554 // well we have to check if we are in an inset with unlimited
2555 // lenght (all in one row) if that is true then we don't allow
2556 // any special options in the paragraph and also we don't allow
2557 // any environment other then "Standard" to be valid!
2558 if ((in == 0) || !in->forceDefaultParagraphs(in)) {
2559 LyXLayout const & layout =
2560 textclasslist[params.textclass][par->layout()];
2562 if (layout.intitle) {
2563 if (already_title) {
2564 lyxerr <<"Error in latexParagraphs: You"
2565 " should not mix title layouts"
2566 " with normal ones." << endl;
2569 } else if (was_title && !already_title) {
2570 ofs << "\\maketitle\n";
2572 already_title = true;
2576 if (layout.isEnvironment()) {
2577 par = par->TeXEnvironment(this, params, ofs, texrow);
2579 par = par->TeXOnePar(this, params, ofs, texrow, false);
2582 par = par->TeXOnePar(this, params, ofs, texrow, false);
2585 // It might be that we only have a title in this document
2586 if (was_title && !already_title) {
2587 ofs << "\\maketitle\n";
2593 bool Buffer::isLatex() const
2595 return textclasslist[params.textclass].outputType() == LATEX;
2599 bool Buffer::isLinuxDoc() const
2601 return textclasslist[params.textclass].outputType() == LINUXDOC;
2605 bool Buffer::isLiterate() const
2607 return textclasslist[params.textclass].outputType() == LITERATE;
2611 bool Buffer::isDocBook() const
2613 return textclasslist[params.textclass].outputType() == DOCBOOK;
2617 bool Buffer::isSGML() const
2619 LyXTextClass const & tclass = textclasslist[params.textclass];
2621 return tclass.outputType() == LINUXDOC ||
2622 tclass.outputType() == DOCBOOK;
2626 void Buffer::sgmlOpenTag(ostream & os, Paragraph::depth_type,
2627 string const & latexname) const
2629 if (!latexname.empty() && latexname != "!-- --")
2630 //os << "<!-- " << depth << " -->" << "<" << latexname << ">";
2631 os << "<" << latexname << ">";
2635 void Buffer::sgmlCloseTag(ostream & os, Paragraph::depth_type,
2636 string const & latexname) const
2638 if (!latexname.empty() && latexname != "!-- --")
2639 //os << "<!-- " << depth << " -->" << "</" << latexname << ">\n";
2640 os << "</" << latexname << ">";
2644 void Buffer::makeLinuxDocFile(string const & fname, bool nice, bool body_only)
2646 ofstream ofs(fname.c_str());
2649 Alert::alert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2653 niceFile = nice; // this will be used by included files.
2655 LaTeXFeatures features(params);
2661 LyXTextClass const & tclass = textclasslist[params.textclass];
2663 string top_element = tclass.latexname();
2666 ofs << "<!doctype linuxdoc system";
2668 string preamble = params.preamble;
2669 const string name = nice ? ChangeExtension(filename_, ".sgml")
2671 preamble += features.getIncludedFiles(name);
2672 preamble += features.getLyXSGMLEntities();
2674 if (!preamble.empty()) {
2675 ofs << " [ " << preamble << " ]";
2679 if (params.options.empty())
2680 sgmlOpenTag(ofs, 0, top_element);
2682 string top = top_element;
2684 top += params.options;
2685 sgmlOpenTag(ofs, 0, top);
2689 ofs << "<!-- " << lyx_docversion
2690 << " created this file. For more info see http://www.lyx.org/"
2693 Paragraph::depth_type depth = 0; // paragraph depth
2694 Paragraph * par = paragraph;
2696 vector<string> environment_stack(5);
2699 LyXLayout const & style = tclass[par->layout()];
2701 // treat <toc> as a special case for compatibility with old code
2702 if (par->isInset(0)) {
2703 Inset * inset = par->getInset(0);
2704 Inset::Code lyx_code = inset->lyxCode();
2705 if (lyx_code == Inset::TOC_CODE) {
2706 string const temp = "toc";
2707 sgmlOpenTag(ofs, depth, temp);
2714 // environment tag closing
2715 for (; depth > par->params().depth(); --depth) {
2716 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2717 environment_stack[depth].erase();
2720 // write opening SGML tags
2721 switch (style.latextype) {
2722 case LATEX_PARAGRAPH:
2723 if (depth == par->params().depth()
2724 && !environment_stack[depth].empty()) {
2725 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2726 environment_stack[depth].erase();
2732 sgmlOpenTag(ofs, depth, style.latexname());
2738 _("Error : Wrong depth for"
2739 " LatexType Command.\n"));
2741 if (!environment_stack[depth].empty()) {
2742 sgmlCloseTag(ofs, depth,
2743 environment_stack[depth]);
2747 environment_stack[depth].erase();
2748 sgmlOpenTag(ofs, depth, style.latexname());
2751 case LATEX_ENVIRONMENT:
2752 case LATEX_ITEM_ENVIRONMENT:
2753 if (depth == par->params().depth()
2754 && environment_stack[depth] != style.latexname()) {
2755 sgmlCloseTag(ofs, depth,
2756 environment_stack[depth]);
2757 environment_stack[depth].erase();
2759 if (depth < par->params().depth()) {
2760 depth = par->params().depth();
2761 environment_stack[depth].erase();
2763 if (environment_stack[depth] != style.latexname()) {
2765 sgmlOpenTag(ofs, depth, "p");
2767 sgmlOpenTag(ofs, depth, style.latexname());
2769 if (environment_stack.size() == depth + 1)
2770 environment_stack.push_back("!-- --");
2771 environment_stack[depth] = style.latexname();
2774 if (style.latexparam() == "CDATA")
2777 if (style.latextype == LATEX_ENVIRONMENT) break;
2779 if (style.labeltype == LABEL_MANUAL)
2784 sgmlOpenTag(ofs, depth + 1, item_name);
2787 sgmlOpenTag(ofs, depth, style.latexname());
2791 simpleLinuxDocOnePar(ofs, par, depth);
2796 // write closing SGML tags
2797 switch (style.latextype) {
2800 case LATEX_ENVIRONMENT:
2801 case LATEX_ITEM_ENVIRONMENT:
2802 if (style.latexparam() == "CDATA")
2806 sgmlCloseTag(ofs, depth, style.latexname());
2812 for (int i=depth; i >= 0; --i)
2813 sgmlCloseTag(ofs, depth, environment_stack[i]);
2817 sgmlCloseTag(ofs, 0, top_element);
2821 // How to check for successful close
2823 // we want this to be true outside previews (for insetexternal)
2828 // checks, if newcol chars should be put into this line
2829 // writes newline, if necessary.
2832 void sgmlLineBreak(ostream & os, string::size_type & colcount,
2833 string::size_type newcol)
2836 if (colcount > lyxrc.ascii_linelen) {
2838 colcount = newcol; // assume write after this call
2853 string tag_name(PAR_TAG const & pt) {
2855 case NONE: return "!-- --";
2856 case TT: return "tt";
2857 case SF: return "sf";
2858 case BF: return "bf";
2859 case IT: return "it";
2860 case SL: return "sl";
2861 case EM: return "em";
2868 void operator|=(PAR_TAG & p1, PAR_TAG const & p2)
2870 p1 = static_cast<PAR_TAG>(p1 | p2);
2875 void reset(PAR_TAG & p1, PAR_TAG const & p2)
2877 p1 = static_cast<PAR_TAG>(p1 & ~p2);
2883 // Handle internal paragraph parsing -- layout already processed.
2884 void Buffer::simpleLinuxDocOnePar(ostream & os,
2886 Paragraph::depth_type /*depth*/)
2888 LyXLayout const & style =
2889 textclasslist[params.textclass][par->layout()];
2890 string::size_type char_line_count = 5; // Heuristic choice ;-)
2892 // gets paragraph main font
2895 if (style.labeltype == LABEL_MANUAL) {
2896 font_old = style.labelfont;
2899 font_old = style.font;
2903 LyXFont::FONT_FAMILY family_type = LyXFont::ROMAN_FAMILY;
2904 LyXFont::FONT_SERIES series_type = LyXFont::MEDIUM_SERIES;
2905 LyXFont::FONT_SHAPE shape_type = LyXFont::UP_SHAPE;
2908 stack<PAR_TAG> tag_state;
2909 // parsing main loop
2910 for (pos_type i = 0; i < par->size(); ++i) {
2912 PAR_TAG tag_close = NONE;
2913 list < PAR_TAG > tag_open;
2915 LyXFont const font = par->getFont(params, i);
2917 if (font_old.family() != font.family()) {
2918 switch (family_type) {
2919 case LyXFont::SANS_FAMILY:
2922 case LyXFont::TYPEWRITER_FAMILY:
2929 family_type = font.family();
2931 switch (family_type) {
2932 case LyXFont::SANS_FAMILY:
2933 tag_open.push_back(SF);
2935 case LyXFont::TYPEWRITER_FAMILY:
2936 tag_open.push_back(TT);
2943 if (font_old.series() != font.series()) {
2944 switch (series_type) {
2945 case LyXFont::BOLD_SERIES:
2952 series_type = font.series();
2954 switch (series_type) {
2955 case LyXFont::BOLD_SERIES:
2956 tag_open.push_back(BF);
2964 if (font_old.shape() != font.shape()) {
2965 switch (shape_type) {
2966 case LyXFont::ITALIC_SHAPE:
2969 case LyXFont::SLANTED_SHAPE:
2976 shape_type = font.shape();
2978 switch (shape_type) {
2979 case LyXFont::ITALIC_SHAPE:
2980 tag_open.push_back(IT);
2982 case LyXFont::SLANTED_SHAPE:
2983 tag_open.push_back(SL);
2990 if (font_old.emph() != font.emph()) {
2991 if (font.emph() == LyXFont::ON) {
2992 tag_open.push_back(EM);
3001 list < PAR_TAG > temp;
3002 while (!tag_state.empty() && tag_close) {
3003 PAR_TAG k = tag_state.top();
3005 os << "</" << tag_name(k) << ">";
3012 for(list< PAR_TAG >::const_iterator j = temp.begin();
3013 j != temp.end(); ++j) {
3015 os << "<" << tag_name(*j) << ">";
3018 for(list< PAR_TAG >::const_iterator j = tag_open.begin();
3019 j != tag_open.end(); ++j) {
3021 os << "<" << tag_name(*j) << ">";
3024 char c = par->getChar(i);
3026 if (c == Paragraph::META_INSET) {
3027 Inset * inset = par->getInset(i);
3028 inset->linuxdoc(this, os);
3033 if (style.latexparam() == "CDATA") {
3034 // "TeX"-Mode on == > SGML-Mode on.
3040 if (par->sgmlConvertChar(c, sgml_string)
3041 && !style.free_spacing && !par->isFreeSpacing())
3043 // in freespacing mode, spaces are
3044 // non-breaking characters
3045 if (desc_on) {// if char is ' ' then...
3048 sgmlLineBreak(os, char_line_count, 6);
3052 sgmlLineBreak(os, char_line_count, 1);
3057 char_line_count += sgml_string.length();
3063 while (!tag_state.empty()) {
3064 os << "</" << tag_name(tag_state.top()) << ">";
3068 // resets description flag correctly
3070 // <tag> not closed...
3071 sgmlLineBreak(os, char_line_count, 6);
3077 // Print an error message.
3078 void Buffer::sgmlError(Paragraph * par, int pos,
3079 string const & message) const
3081 // insert an error marker in text
3082 InsetError * new_inset = new InsetError(message);
3083 par->insertInset(pos, new_inset, LyXFont(LyXFont::ALL_INHERIT,
3088 void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
3090 ofstream ofs(fname.c_str());
3092 Alert::alert(_("LYX_ERROR:"), _("Cannot write file"), fname);
3096 Paragraph * par = paragraph;
3098 niceFile = nice; // this will be used by Insetincludes.
3100 LaTeXFeatures features(params);
3105 LyXTextClass const & tclass = textclasslist[params.textclass];
3106 string top_element = tclass.latexname();
3109 ofs << "<!DOCTYPE " << top_element
3110 << " PUBLIC \"-//OASIS//DTD DocBook V4.1//EN\"";
3112 string preamble = params.preamble;
3113 const string name = nice ? ChangeExtension(filename_, ".sgml")
3115 preamble += features.getIncludedFiles(name);
3116 preamble += features.getLyXSGMLEntities();
3118 if (!preamble.empty()) {
3119 ofs << "\n [ " << preamble << " ]";
3124 string top = top_element;
3126 top += params.language->code();
3129 if (!params.options.empty()) {
3131 top += params.options;
3133 sgmlOpenTag(ofs, 0, top);
3135 ofs << "<!-- DocBook file was created by " << lyx_docversion
3136 << "\n See http://www.lyx.org/ for more information -->\n";
3138 vector<string> environment_stack(10);
3139 vector<string> environment_inner(10);
3140 vector<string> command_stack(10);
3142 bool command_flag = false;
3143 Paragraph::depth_type command_depth = 0;
3144 Paragraph::depth_type command_base = 0;
3145 Paragraph::depth_type cmd_depth = 0;
3146 Paragraph::depth_type depth = 0; // paragraph depth
3149 string command_name;
3155 int desc_on = 0; // description mode
3157 LyXLayout const & style = tclass[par->layout()];
3159 // environment tag closing
3160 for (; depth > par->params().depth(); --depth) {
3161 if (environment_inner[depth] != "!-- --") {
3162 item_name = "listitem";
3163 sgmlCloseTag(ofs, command_depth + depth,
3165 if (environment_inner[depth] == "varlistentry")
3166 sgmlCloseTag(ofs, depth+command_depth,
3167 environment_inner[depth]);
3169 sgmlCloseTag(ofs, depth + command_depth,
3170 environment_stack[depth]);
3171 environment_stack[depth].erase();
3172 environment_inner[depth].erase();
3175 if (depth == par->params().depth()
3176 && environment_stack[depth] != style.latexname()
3177 && !environment_stack[depth].empty()) {
3178 if (environment_inner[depth] != "!-- --") {
3179 item_name= "listitem";
3180 sgmlCloseTag(ofs, command_depth+depth,
3182 if (environment_inner[depth] == "varlistentry")
3184 depth + command_depth,
3185 environment_inner[depth]);
3188 sgmlCloseTag(ofs, depth + command_depth,
3189 environment_stack[depth]);
3191 environment_stack[depth].erase();
3192 environment_inner[depth].erase();
3195 // Write opening SGML tags.
3196 switch (style.latextype) {
3197 case LATEX_PARAGRAPH:
3198 sgmlOpenTag(ofs, depth + command_depth,
3205 _("Error : Wrong depth for "
3206 "LatexType Command.\n"));
3208 command_name = style.latexname();
3210 sgmlparam = style.latexparam();
3211 c_params = split(sgmlparam, c_depth,'|');
3213 cmd_depth = lyx::atoi(c_depth);
3216 if (cmd_depth < command_base) {
3217 for (Paragraph::depth_type j = command_depth; j >= command_base; --j)
3218 sgmlCloseTag(ofs, j, command_stack[j]);
3219 command_depth = command_base = cmd_depth;
3220 } else if (cmd_depth <= command_depth) {
3221 for (int j = command_depth; j >= int(cmd_depth); --j)
3222 sgmlCloseTag(ofs, j, command_stack[j]);
3223 command_depth = cmd_depth;
3225 command_depth = cmd_depth;
3227 command_depth = command_base = cmd_depth;
3228 command_flag = true;
3230 if (command_stack.size() == command_depth + 1)
3231 command_stack.push_back(string());
3232 command_stack[command_depth] = command_name;
3234 // treat label as a special case for
3235 // more WYSIWYM handling.
3236 // This is a hack while paragraphs can't have
3237 // attributes, like id in this case.
3238 if (par->isInset(0)) {
3239 Inset * inset = par->getInset(0);
3240 Inset::Code lyx_code = inset->lyxCode();
3241 if (lyx_code == Inset::LABEL_CODE) {
3242 command_name += " id=\"";
3243 command_name += (static_cast<InsetCommand *>(inset))->getContents();
3244 command_name += "\"";
3249 sgmlOpenTag(ofs, depth + command_depth, command_name);
3250 if (c_params.empty())
3251 item_name = "title";
3253 item_name = c_params;
3254 sgmlOpenTag(ofs, depth + 1 + command_depth, item_name);
3257 case LATEX_ENVIRONMENT:
3258 case LATEX_ITEM_ENVIRONMENT:
3259 if (depth < par->params().depth()) {
3260 depth = par->params().depth();
3261 environment_stack[depth].erase();
3264 if (environment_stack[depth] != style.latexname()) {
3265 if (environment_stack.size() == depth + 1) {
3266 environment_stack.push_back("!-- --");
3267 environment_inner.push_back("!-- --");
3269 environment_stack[depth] = style.latexname();
3270 environment_inner[depth] = "!-- --";
3271 sgmlOpenTag(ofs, depth + command_depth,
3272 environment_stack[depth]);
3274 if (environment_inner[depth] != "!-- --") {
3275 item_name= "listitem";
3277 command_depth + depth,
3279 if (environment_inner[depth] == "varlistentry")
3281 depth + command_depth,
3282 environment_inner[depth]);
3286 if (style.latextype == LATEX_ENVIRONMENT) {
3287 if (!style.latexparam().empty()) {
3288 if (style.latexparam() == "CDATA")
3291 sgmlOpenTag(ofs, depth + command_depth,
3292 style.latexparam());
3297 desc_on = (style.labeltype == LABEL_MANUAL);
3300 environment_inner[depth]= "varlistentry";
3302 environment_inner[depth]= "listitem";
3304 sgmlOpenTag(ofs, depth + 1 + command_depth,
3305 environment_inner[depth]);
3309 sgmlOpenTag(ofs, depth + 1 + command_depth,
3313 sgmlOpenTag(ofs, depth + 1 + command_depth,
3318 sgmlOpenTag(ofs, depth + command_depth,
3323 simpleDocBookOnePar(ofs, par, desc_on, depth+1+command_depth);
3327 // write closing SGML tags
3328 switch (style.latextype) {
3330 if (c_params.empty())
3334 sgmlCloseTag(ofs, depth + command_depth, end_tag);
3336 case LATEX_ENVIRONMENT:
3337 if (!style.latexparam().empty()) {
3338 if (style.latexparam() == "CDATA")
3341 sgmlCloseTag(ofs, depth + command_depth,
3342 style.latexparam());
3345 case LATEX_ITEM_ENVIRONMENT:
3346 if (desc_on == 1) break;
3348 sgmlCloseTag(ofs, depth + 1 + command_depth, end_tag);
3350 case LATEX_PARAGRAPH:
3351 sgmlCloseTag(ofs, depth + command_depth, style.latexname());
3354 sgmlCloseTag(ofs, depth + command_depth, style.latexname());
3360 for (int d = depth; d >= 0; --d) {
3361 if (!environment_stack[depth].empty()) {
3362 if (environment_inner[depth] != "!-- --") {
3363 item_name = "listitem";
3364 sgmlCloseTag(ofs, command_depth + depth,
3366 if (environment_inner[depth] == "varlistentry")
3367 sgmlCloseTag(ofs, depth + command_depth,
3368 environment_inner[depth]);
3371 sgmlCloseTag(ofs, depth + command_depth,
3372 environment_stack[depth]);
3376 for (int j = command_depth; j >= 0 ; --j)
3377 if (!command_stack[j].empty())
3378 sgmlCloseTag(ofs, j, command_stack[j]);
3381 sgmlCloseTag(ofs, 0, top_element);
3384 // How to check for successful close
3386 // we want this to be true outside previews (for insetexternal)
3391 void Buffer::simpleDocBookOnePar(ostream & os,
3392 Paragraph * par, int & desc_on,
3393 Paragraph::depth_type depth) const
3395 bool emph_flag = false;
3397 LyXLayout const & style =
3398 textclasslist[params.textclass][par->layout()];
3400 LyXFont font_old = style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
3402 int char_line_count = depth;
3403 //if (!style.free_spacing)
3404 // os << string(depth,' ');
3406 // parsing main loop
3407 for (pos_type i = 0; i < par->size(); ++i) {
3408 LyXFont font = par->getFont(params, i);
3410 // handle <emphasis> tag
3411 if (font_old.emph() != font.emph()) {
3412 if (font.emph() == LyXFont::ON) {
3416 os << "</emphasis>";
3422 if (par->isInset(i)) {
3423 Inset * inset = par->getInset(i);
3424 // don't print the inset in position 0 if desc_on == 3 (label)
3425 if ( i || desc_on != 3) {
3426 if(style.latexparam() == "CDATA")
3428 inset->docbook(this, os);
3429 if(style.latexparam() == "CDATA")
3433 char c = par->getChar(i);
3435 par->sgmlConvertChar(c, sgml_string);
3437 if (style.pass_thru) {
3439 } else if (style.free_spacing || par->isFreeSpacing() || c != ' ') {
3441 } else if (desc_on ==1) {
3443 os << "\n</term><listitem><para>";
3453 os << "</emphasis>";
3456 // resets description flag correctly
3458 // <term> not closed...
3461 if (style.free_spacing) os << '\n';
3465 // This should be enabled when the Chktex class is implemented. (Asger)
3466 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
3467 // Other flags: -wall -v0 -x
3468 int Buffer::runChktex()
3470 if (!users->text) return 0;
3472 users->owner()->prohibitInput();
3474 // get LaTeX-Filename
3475 string const name = getLatexName();
3476 string path = filePath();
3478 string const org_path = path;
3479 if (lyxrc.use_tempdir || !IsDirWriteable(path)) {
3483 Path p(path); // path to LaTeX file
3484 users->owner()->message(_("Running chktex..."));
3486 // Remove all error insets
3487 bool const removedErrorInsets = users->removeAutoInsets();
3489 // Generate the LaTeX file if neccessary
3490 makeLaTeXFile(name, org_path, false);
3493 Chktex chktex(lyxrc.chktex_command, name, filePath());
3494 int res = chktex.run(terr); // run chktex
3497 Alert::alert(_("chktex did not work!"),
3498 _("Could not run with file:"), name);
3499 } else if (res > 0) {
3500 // Insert all errors as errors boxes
3501 users->insertErrors(terr);
3504 // if we removed error insets before we ran chktex or if we inserted
3505 // error insets after we ran chktex, this must be run:
3506 if (removedErrorInsets || res) {
3510 users->owner()->allowInput();
3516 void Buffer::validate(LaTeXFeatures & features) const
3518 Paragraph * par = paragraph;
3519 LyXTextClass const & tclass = textclasslist[params.textclass];
3521 // AMS Style is at document level
3522 if (params.use_amsmath || tclass.provides(LyXTextClass::amsmath))
3523 features.require("amsmath");
3526 // We don't use "lyxerr.debug" because of speed. (Asger)
3527 if (lyxerr.debugging(Debug::LATEX))
3528 lyxerr << "Paragraph: " << par << endl;
3530 // Now just follow the list of paragraphs and run
3531 // validate on each of them.
3532 par->validate(features);
3534 // and then the next paragraph
3538 // the bullet shapes are buffer level not paragraph level
3539 // so they are tested here
3540 for (int i = 0; i < 4; ++i) {
3541 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
3542 int const font = params.user_defined_bullets[i].getFont();
3544 int const c = params
3545 .user_defined_bullets[i]
3552 features.require("latexsym");
3554 } else if (font == 1) {
3555 features.require("amssymb");
3556 } else if ((font >= 2 && font <= 5)) {
3557 features.require("pifont");
3562 if (lyxerr.debugging(Debug::LATEX)) {
3563 features.showStruct();
3568 // This function should be in Buffer because it's a buffer's property (ale)
3569 string const Buffer::getIncludeonlyList(char delim)
3572 for (inset_iterator it = inset_iterator_begin();
3573 it != inset_iterator_end(); ++it) {
3574 if ((*it)->lyxCode() == Inset::INCLUDE_CODE) {
3575 InsetInclude * insetinc =
3576 static_cast<InsetInclude *>(*it);
3577 if (insetinc->isIncludeOnly()) {
3580 lst += insetinc->getRelFileBaseName();
3584 lyxerr[Debug::INFO] << "Includeonly(" << lst << ')' << endl;
3589 vector<string> const Buffer::getLabelList()
3591 /// if this is a child document and the parent is already loaded
3592 /// Use the parent's list instead [ale990407]
3593 if (!params.parentname.empty()
3594 && bufferlist.exists(params.parentname)) {
3595 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3597 return tmp->getLabelList();
3600 vector<string> label_list;
3601 for (inset_iterator it = inset_iterator_begin();
3602 it != inset_iterator_end(); ++it) {
3603 vector<string> const l = (*it)->getLabelList();
3604 label_list.insert(label_list.end(), l.begin(), l.end());
3610 Buffer::Lists const Buffer::getLists() const
3613 Paragraph * par = paragraph;
3615 LyXTextClass const & textclass = textclasslist[params.textclass];
3616 bool found = textclass.hasLayout("Caption");
3617 string const layout("Caption");
3620 char const labeltype = textclass[par->layout()].labeltype;
3622 if (labeltype >= LABEL_COUNTER_CHAPTER
3623 && labeltype <= LABEL_COUNTER_CHAPTER + params.tocdepth) {
3624 // insert this into the table of contents
3625 SingleList & item = l["TOC"];
3628 textclass.maxcounter());
3629 item.push_back(TocItem(par, depth, par->asString(this, true)));
3631 // For each paragrph, traverse its insets and look for
3635 Paragraph::inset_iterator it =
3636 par->inset_iterator_begin();
3637 Paragraph::inset_iterator end =
3638 par->inset_iterator_end();
3640 for (; it != end; ++it) {
3641 if ((*it)->lyxCode() == Inset::FLOAT_CODE) {
3643 static_cast<InsetFloat*>(*it);
3645 string const type = il->type();
3647 // Now find the caption in the float...
3648 // We now tranverse the paragraphs of
3650 Paragraph * tmp = il->inset.paragraph();
3652 if (tmp->layout() == layout) {
3653 SingleList & item = l[type];
3655 tostr(item.size()+1) + ". " + tmp->asString(this, false);
3656 item.push_back(TocItem(tmp, 0 , str));
3663 lyxerr << "Caption not found" << endl;
3672 // This is also a buffer property (ale)
3673 vector<pair<string, string> > const Buffer::getBibkeyList()
3675 /// if this is a child document and the parent is already loaded
3676 /// Use the parent's list instead [ale990412]
3677 if (!params.parentname.empty() && bufferlist.exists(params.parentname)) {
3678 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3680 return tmp->getBibkeyList();
3683 vector<pair<string, string> > keys;
3684 Paragraph * par = paragraph;
3687 keys.push_back(pair<string, string>(par->bibkey->getContents(),
3688 par->asString(this, false)));
3692 // Might be either using bibtex or a child has bibliography
3694 for (inset_iterator it = inset_iterator_begin();
3695 it != inset_iterator_end(); ++it) {
3696 // Search for Bibtex or Include inset
3697 if ((*it)->lyxCode() == Inset::BIBTEX_CODE) {
3698 vector<pair<string,string> > tmp =
3699 static_cast<InsetBibtex*>(*it)->getKeys(this);
3700 keys.insert(keys.end(), tmp.begin(), tmp.end());
3701 } else if ((*it)->lyxCode() == Inset::INCLUDE_CODE) {
3702 vector<pair<string,string> > const tmp =
3703 static_cast<InsetInclude*>(*it)->getKeys();
3704 keys.insert(keys.end(), tmp.begin(), tmp.end());
3713 bool Buffer::isDepClean(string const & name) const
3715 DEPCLEAN * item = dep_clean;
3716 while (item && item->master != name)
3718 if (!item) return true;
3723 void Buffer::markDepClean(string const & name)
3726 dep_clean = new DEPCLEAN;
3727 dep_clean->clean = true;
3728 dep_clean->master = name;
3729 dep_clean->next = 0;
3731 DEPCLEAN * item = dep_clean;
3732 while (item && item->master != name)
3737 item = new DEPCLEAN;
3739 item->master = name;
3746 bool Buffer::dispatch(string const & command)
3748 // Split command string into command and argument
3750 string line = frontStrip(command);
3751 string const arg = strip(frontStrip(split(line, cmd, ' ')));
3753 return dispatch(lyxaction.LookupFunc(cmd), arg);
3757 bool Buffer::dispatch(int action, string const & argument)
3759 bool dispatched = true;
3762 Exporter::Export(this, argument, false);
3772 void Buffer::resizeInsets(BufferView * bv)
3774 /// then remove all LyXText in text-insets
3775 Paragraph * par = paragraph;
3776 for (; par; par = par->next()) {
3777 par->resizeInsetsLyXText(bv);
3782 void Buffer::redraw()
3789 void Buffer::changeLanguage(Language const * from, Language const * to)
3792 ParIterator end = par_iterator_end();
3793 for (ParIterator it = par_iterator_begin(); it != end; ++it)
3794 (*it)->changeLanguage(params, from, to);
3798 bool Buffer::isMultiLingual()
3800 ParIterator end = par_iterator_end();
3801 for (ParIterator it = par_iterator_begin(); it != end; ++it)
3802 if ((*it)->isMultiLingual(params))
3809 Buffer::inset_iterator::inset_iterator(Paragraph * paragraph, pos_type pos)
3812 it = par->InsetIterator(pos);
3813 if (it == par->inset_iterator_end()) {
3820 void Buffer::inset_iterator::setParagraph()
3823 it = par->inset_iterator_begin();
3824 if (it != par->inset_iterator_end())
3829 // We maintain an invariant that whenever par = 0 then it = 0
3833 Inset * Buffer::getInsetFromID(int id_arg) const
3835 for (inset_iterator it = inset_const_iterator_begin();
3836 it != inset_const_iterator_end(); ++it)
3838 if ((*it)->id() == id_arg)
3840 Inset * in = (*it)->getInsetFromID(id_arg);
3848 Paragraph * Buffer::getParFromID(int id) const
3850 if (id < 0) return 0;
3851 Paragraph * par = paragraph;
3853 if (par->id() == id) {
3856 Paragraph * tmp = par->getParFromID(id);
3866 ParIterator Buffer::par_iterator_begin()
3868 return ParIterator(paragraph);
3872 ParIterator Buffer::par_iterator_end()
3874 return ParIterator();