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), 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()
481 #ifndef NO_COMPABILITY
482 if (compare_no_case(layoutname, "latex") == 0) {
483 ert_comp.active = true;
484 ert_comp.font = font;
488 // The is the compability reading of layout caption.
489 // It can be removed in LyX version 1.3.0. (Lgb)
490 if (compare_no_case(layoutname, "caption") == 0) {
491 // We expect that the par we are now working on is
492 // really inside a InsetText inside a InsetFloat.
493 // We also know that captions can only be
494 // one paragraph. (Lgb)
496 // We should now read until the next "\layout"
498 // This is probably not good enough, what if the
499 // caption is the last par in the document (Lgb)
500 istream & ist = lex.getStream();
506 if (prefixIs(line, "\\layout")) {
510 if (prefixIs(line, "\\begin_inset"))
512 if (prefixIs(line, "\\end_inset")) {
523 // Now we should have the whole layout in ss
524 // we should now be able to give this to the
526 ss << "\\end_inset\n";
528 // This seems like a bug in stringstream.
529 // We really should be able to use ss
531 istringstream is(ss.str());
533 tmplex.setStream(is);
534 Inset * inset = new InsetCaption;
535 inset->Read(this, tmplex);
536 par->InsertInset(pos, inset, font);
543 par = new Paragraph(par);
546 par->layout(layoutname);
547 // Test whether the layout is obsolete.
548 LyXLayout const & layout =
549 textclasslist[params.textclass][par->layout()];
550 if (!layout.obsoleted_by().empty())
551 par->layout(layout.obsoleted_by());
552 par->params().depth(depth);
553 font = LyXFont(LyXFont::ALL_INHERIT, params.language);
554 if (file_format < 216
555 && params.language->lang() == "hebrew")
556 font.setLanguage(default_language);
561 #ifndef NO_COMPABILITY
562 } else if (token == "\\begin_float") {
563 insertErtContents(par, pos);
564 //insertErtContents(par, pos, false);
565 //ert_stack.push(ert_comp);
566 //ert_comp = ErtComp();
568 // This is the compability reader. It can be removed in
569 // LyX version 1.3.0. (Lgb)
571 string const tmptok = lex.getString();
572 //lyxerr << "old float: " << tmptok << endl;
575 stringstream old_float;
577 if (tmptok == "footnote") {
578 inset = new InsetFoot(params);
579 old_float << "collapsed true\n";
580 } else if (tmptok == "margin") {
581 inset = new InsetMarginal(params);
582 old_float << "collapsed true\n";
583 } else if (tmptok == "fig") {
584 inset = new InsetFloat(params, "figure");
585 old_float << "placement htbp\n"
587 << "collapsed false\n";
588 } else if (tmptok == "tab") {
589 inset = new InsetFloat(params, "table");
590 old_float << "placement htbp\n"
592 << "collapsed false\n";
593 } else if (tmptok == "alg") {
594 inset = new InsetFloat(params, "algorithm");
595 old_float << "placement htbp\n"
597 << "collapsed false\n";
598 } else if (tmptok == "wide-fig") {
599 inset = new InsetFloat(params, "figure");
600 //InsetFloat * tmp = new InsetFloat("figure");
603 old_float << "placement htbp\n"
605 << "collapsed false\n";
606 } else if (tmptok == "wide-tab") {
607 inset = new InsetFloat(params, "table");
608 //InsetFloat * tmp = new InsetFloat("table");
611 old_float << "placement htbp\n"
613 << "collapsed false\n";
617 #ifndef NO_PEXTRA_REALLY
620 return false; // no end read yet
623 // Here we need to check for \end_deeper and handle that
624 // before we do the footnote parsing.
625 // This _is_ a hack! (Lgb)
628 string const tmp = lex.getString();
629 if (tmp == "\\end_deeper") {
630 //lyxerr << "\\end_deeper caught!" << endl;
632 lex.printError("\\end_deeper: "
633 "depth is already null");
638 old_float << tmp << ' ';
643 old_float << lex.getLongString("\\end_float")
644 << "\n\\end_inset\n";
645 //lyxerr << "Float Body:\n" << old_float.str() << endl;
646 // That this does not work seems like a bug
647 // in stringstream. (Lgb)
648 istringstream istr(old_float.str());
650 nylex.setStream(istr);
651 inset->read(this, nylex);
652 par->insertInset(pos, inset, font);
654 insertErtContents(par, pos);
656 } else if (token == "\\begin_deeper") {
658 } else if (token == "\\end_deeper") {
660 lex.printError("\\end_deeper: "
661 "depth is already null");
665 } else if (token == "\\begin_preamble") {
666 params.readPreamble(lex);
667 } else if (token == "\\textclass") {
669 pair<bool, textclass_type> pp =
670 textclasslist.NumberOfClass(lex.getString());
672 params.textclass = pp.second;
674 Alert::alert(string(_("Textclass error")),
675 string(_("The document uses an unknown textclass \"")) +
676 lex.getString() + string("\"."),
677 string(_("LyX will not be able to produce output correctly.")));
678 params.textclass = 0;
680 if (!textclasslist[params.textclass].load()) {
681 // if the textclass wasn't loaded properly
682 // we need to either substitute another
683 // or stop loading the file.
684 // I can substitute but I don't see how I can
685 // stop loading... ideas?? ARRae980418
686 Alert::alert(_("Textclass Loading Error!"),
687 string(_("Can't load textclass ")) +
688 textclasslist[params.textclass].name(),
689 _("-- substituting default"));
690 params.textclass = 0;
692 } else if (token == "\\options") {
694 params.options = lex.getString();
695 } else if (token == "\\language") {
696 params.readLanguage(lex);
697 } else if (token == "\\fontencoding") {
699 } else if (token == "\\inputencoding") {
701 params.inputenc = lex.getString();
702 } else if (token == "\\graphics") {
703 params.readGraphicsDriver(lex);
704 } else if (token == "\\fontscheme") {
706 params.fonts = lex.getString();
707 } else if (token == "\\noindent") {
708 par->params().noindent(true);
709 } else if (token == "\\fill_top") {
710 par->params().spaceTop(VSpace(VSpace::VFILL));
711 } else if (token == "\\fill_bottom") {
712 par->params().spaceBottom(VSpace(VSpace::VFILL));
713 } else if (token == "\\line_top") {
714 par->params().lineTop(true);
715 } else if (token == "\\line_bottom") {
716 par->params().lineBottom(true);
717 } else if (token == "\\pagebreak_top") {
718 par->params().pagebreakTop(true);
719 } else if (token == "\\pagebreak_bottom") {
720 par->params().pagebreakBottom(true);
721 } else if (token == "\\start_of_appendix") {
722 par->params().startOfAppendix(true);
723 } else if (token == "\\paragraph_separation") {
724 int tmpret = lex.findToken(string_paragraph_separation);
727 if (tmpret != LYX_LAYOUT_DEFAULT)
728 params.paragraph_separation =
729 static_cast<BufferParams::PARSEP>(tmpret);
730 } else if (token == "\\defskip") {
732 params.defskip = VSpace(lex.getString());
733 #ifndef NO_COMPABILITY
734 } else if (token == "\\epsfig") { // obsolete
735 // Indeed it is obsolete, but we HAVE to be backwards
736 // compatible until 0.14, because otherwise all figures
737 // in existing documents are irretrivably lost. (Asger)
738 params.readGraphicsDriver(lex);
740 } else if (token == "\\quotes_language") {
741 int tmpret = lex.findToken(string_quotes_language);
744 if (tmpret != LYX_LAYOUT_DEFAULT) {
745 InsetQuotes::quote_language tmpl =
746 InsetQuotes::EnglishQ;
749 tmpl = InsetQuotes::EnglishQ;
752 tmpl = InsetQuotes::SwedishQ;
755 tmpl = InsetQuotes::GermanQ;
758 tmpl = InsetQuotes::PolishQ;
761 tmpl = InsetQuotes::FrenchQ;
764 tmpl = InsetQuotes::DanishQ;
767 params.quotes_language = tmpl;
769 } else if (token == "\\quotes_times") {
771 switch (lex.getInteger()) {
773 params.quotes_times = InsetQuotes::SingleQ;
776 params.quotes_times = InsetQuotes::DoubleQ;
779 } else if (token == "\\papersize") {
780 int tmpret = lex.findToken(string_papersize);
784 params.papersize2 = tmpret;
785 } else if (token == "\\paperpackage") {
786 int tmpret = lex.findToken(string_paperpackages);
789 params.paperpackage = BufferParams::PACKAGE_NONE;
791 params.paperpackage = tmpret;
792 } else if (token == "\\use_geometry") {
794 params.use_geometry = lex.getInteger();
795 } else if (token == "\\use_amsmath") {
797 params.use_amsmath = lex.getInteger();
798 } else if (token == "\\use_natbib") {
800 params.use_natbib = lex.getInteger();
801 } else if (token == "\\use_numerical_citations") {
803 params.use_numerical_citations = lex.getInteger();
804 } else if (token == "\\paperorientation") {
805 int tmpret = lex.findToken(string_orientation);
808 if (tmpret != LYX_LAYOUT_DEFAULT)
809 params.orientation = static_cast<BufferParams::PAPER_ORIENTATION>(tmpret);
810 } else if (token == "\\paperwidth") {
812 params.paperwidth = lex.getString();
813 } else if (token == "\\paperheight") {
815 params.paperheight = lex.getString();
816 } else if (token == "\\leftmargin") {
818 params.leftmargin = lex.getString();
819 } else if (token == "\\topmargin") {
821 params.topmargin = lex.getString();
822 } else if (token == "\\rightmargin") {
824 params.rightmargin = lex.getString();
825 } else if (token == "\\bottommargin") {
827 params.bottommargin = lex.getString();
828 } else if (token == "\\headheight") {
830 params.headheight = lex.getString();
831 } else if (token == "\\headsep") {
833 params.headsep = lex.getString();
834 } else if (token == "\\footskip") {
836 params.footskip = lex.getString();
837 } else if (token == "\\paperfontsize") {
839 params.fontsize = strip(lex.getString());
840 } else if (token == "\\papercolumns") {
842 params.columns = lex.getInteger();
843 } else if (token == "\\papersides") {
845 switch (lex.getInteger()) {
847 case 1: params.sides = LyXTextClass::OneSide; break;
848 case 2: params.sides = LyXTextClass::TwoSides; break;
850 } else if (token == "\\paperpagestyle") {
852 params.pagestyle = strip(lex.getString());
853 } else if (token == "\\bullet") {
855 int const index = lex.getInteger();
857 int temp_int = lex.getInteger();
858 params.user_defined_bullets[index].setFont(temp_int);
859 params.temp_bullets[index].setFont(temp_int);
861 temp_int = lex.getInteger();
862 params.user_defined_bullets[index].setCharacter(temp_int);
863 params.temp_bullets[index].setCharacter(temp_int);
865 temp_int = lex.getInteger();
866 params.user_defined_bullets[index].setSize(temp_int);
867 params.temp_bullets[index].setSize(temp_int);
869 string const temp_str = lex.getString();
870 if (temp_str != "\\end_bullet") {
871 // this element isn't really necessary for
872 // parsing but is easier for humans
873 // to understand bullets. Put it back and
874 // set a debug message?
875 lex.printError("\\end_bullet expected, got" + temp_str);
876 //how can I put it back?
878 } else if (token == "\\bulletLaTeX") {
879 // The bullet class should be able to read this.
881 int const index = lex.getInteger();
883 string temp_str = lex.getString();
885 while (temp_str != "\\end_bullet") {
886 // this loop structure is needed when user
887 // enters an empty string since the first
888 // thing returned will be the \\end_bullet
890 // if the LaTeX entry has spaces. Each element
891 // therefore needs to be read in turn
894 temp_str = lex.getString();
897 params.user_defined_bullets[index].setText(sum_str);
898 params.temp_bullets[index].setText(sum_str);
899 } else if (token == "\\secnumdepth") {
901 params.secnumdepth = lex.getInteger();
902 } else if (token == "\\tocdepth") {
904 params.tocdepth = lex.getInteger();
905 } else if (token == "\\spacing") {
907 string const tmp = strip(lex.getString());
908 Spacing::Space tmp_space = Spacing::Default;
910 if (tmp == "single") {
911 tmp_space = Spacing::Single;
912 } else if (tmp == "onehalf") {
913 tmp_space = Spacing::Onehalf;
914 } else if (tmp == "double") {
915 tmp_space = Spacing::Double;
916 } else if (tmp == "other") {
918 tmp_space = Spacing::Other;
919 tmp_val = lex.getFloat();
921 lex.printError("Unknown spacing token: '$$Token'");
923 // Small hack so that files written with klyx will be
926 par->params().spacing(Spacing(tmp_space, tmp_val));
928 params.spacing.set(tmp_space, tmp_val);
930 } else if (token == "\\paragraph_spacing") {
932 string const tmp = strip(lex.getString());
933 if (tmp == "single") {
934 par->params().spacing(Spacing(Spacing::Single));
935 } else if (tmp == "onehalf") {
936 par->params().spacing(Spacing(Spacing::Onehalf));
937 } else if (tmp == "double") {
938 par->params().spacing(Spacing(Spacing::Double));
939 } else if (tmp == "other") {
941 par->params().spacing(Spacing(Spacing::Other,
944 lex.printError("Unknown spacing token: '$$Token'");
946 } else if (token == "\\float_placement") {
948 params.float_placement = lex.getString();
949 } else if (token == "\\family") {
951 font.setLyXFamily(lex.getString());
952 } else if (token == "\\series") {
954 font.setLyXSeries(lex.getString());
955 } else if (token == "\\shape") {
957 font.setLyXShape(lex.getString());
958 } else if (token == "\\size") {
960 font.setLyXSize(lex.getString());
961 #ifndef NO_COMPABILITY
962 } else if (token == "\\latex") {
964 string const tok = lex.getString();
965 if (tok == "no_latex") {
967 insertErtContents(par, pos);
968 } else if (tok == "latex") {
969 ert_comp.active = true;
970 ert_comp.font = font;
971 } else if (tok == "default") {
973 insertErtContents(par, pos);
975 lex.printError("Unknown LaTeX font flag "
979 } else if (token == "\\lang") {
981 string const tok = lex.getString();
982 Language const * lang = languages.getLanguage(tok);
984 font.setLanguage(lang);
986 font.setLanguage(params.language);
987 lex.printError("Unknown language `$$Token'");
989 } else if (token == "\\numeric") {
991 font.setNumber(font.setLyXMisc(lex.getString()));
992 } else if (token == "\\emph") {
994 font.setEmph(font.setLyXMisc(lex.getString()));
995 } else if (token == "\\bar") {
997 string const tok = lex.getString();
998 // This is dirty, but gone with LyX3. (Asger)
1000 font.setUnderbar(LyXFont::ON);
1001 else if (tok == "no")
1002 font.setUnderbar(LyXFont::OFF);
1003 else if (tok == "default")
1004 font.setUnderbar(LyXFont::INHERIT);
1006 lex.printError("Unknown bar font flag "
1008 } else if (token == "\\noun") {
1010 font.setNoun(font.setLyXMisc(lex.getString()));
1011 } else if (token == "\\color") {
1013 font.setLyXColor(lex.getString());
1014 } else if (token == "\\align") {
1015 int tmpret = lex.findToken(string_align);
1016 if (tmpret == -1) ++tmpret;
1017 if (tmpret != LYX_LAYOUT_DEFAULT) { // tmpret != 99 ???
1018 int const tmpret2 = int(pow(2.0, tmpret));
1019 //lyxerr << "Tmpret2 = " << tmpret2 << endl;
1020 par->params().align(LyXAlignment(tmpret2));
1022 } else if (token == "\\added_space_top") {
1024 VSpace value = VSpace(lex.getString());
1025 if ((value.length().len().value() != 0) ||
1026 (value.kind() != VSpace::LENGTH))
1027 par->params().spaceTop(value);
1028 } else if (token == "\\added_space_bottom") {
1030 VSpace value = VSpace(lex.getString());
1031 if ((value.length().len().value() != 0) ||
1032 (value.kind() != VSpace::LENGTH))
1033 par->params().spaceBottom(value);
1034 #ifndef NO_COMPABILITY
1035 #ifndef NO_PEXTRA_REALLY
1036 } else if (token == "\\pextra_type") {
1038 par->params().pextraType(lex.getInteger());
1039 } else if (token == "\\pextra_width") {
1041 par->params().pextraWidth(lex.getString());
1042 } else if (token == "\\pextra_widthp") {
1044 par->params().pextraWidthp(lex.getString());
1045 } else if (token == "\\pextra_alignment") {
1047 par->params().pextraAlignment(lex.getInteger());
1048 } else if (token == "\\pextra_hfill") {
1050 par->params().pextraHfill(lex.getInteger());
1051 } else if (token == "\\pextra_start_minipage") {
1053 par->params().pextraStartMinipage(lex.getInteger());
1056 } else if (token == "\\labelwidthstring") {
1058 par->params().labelWidthString(lex.getString());
1059 // do not delete this token, it is still needed!
1060 } else if (token == "\\end_inset") {
1061 lyxerr << "Solitary \\end_inset. Missing \\begin_inset?.\n"
1062 << "Last inset read was: " << last_inset_read
1064 // Simply ignore this. The insets do not have
1066 // But insets should read it, it is a part of
1067 // the inset isn't it? Lgb.
1068 } else if (token == "\\begin_inset") {
1069 #ifndef NO_COMPABILITY
1070 insertErtContents(par, pos, false);
1071 ert_stack.push(ert_comp);
1072 ert_comp = ErtComp();
1074 readInset(lex, par, pos, font);
1075 #ifndef NO_COMPABILITY
1076 ert_comp = ert_stack.top();
1078 insertErtContents(par, pos);
1080 } else if (token == "\\SpecialChar") {
1081 LyXLayout const & layout =
1082 textclasslist[params.textclass][par->layout()];
1084 // Insets don't make sense in a free-spacing context! ---Kayvan
1085 if (layout.free_spacing || par->isFreeSpacing()) {
1088 string next_token = lex.getString();
1089 if (next_token == "\\-") {
1090 par->insertChar(pos, '-', font);
1091 } else if (next_token == "\\protected_separator"
1092 || next_token == "~") {
1093 par->insertChar(pos, ' ', font);
1095 lex.printError("Token `$$Token' "
1097 "paragraph layout!");
1102 Inset * inset = new InsetSpecialChar;
1103 inset->read(this, lex);
1104 par->insertInset(pos, inset, font);
1107 } else if (token == "\\newline") {
1108 #ifndef NO_COMPABILITY
1109 if (!ert_comp.in_tabular && ert_comp.active) {
1110 ert_comp.contents += char(Paragraph::META_NEWLINE);
1112 // Since we cannot know it this is only a regular
1113 // newline or a tabular cell delimter we have to
1114 // handle the ERT here.
1115 insertErtContents(par, pos, false);
1117 par->insertChar(pos, Paragraph::META_NEWLINE, font);
1121 par->insertChar(pos, Paragraph::META_NEWLINE, font);
1124 } else if (token == "\\LyXTable") {
1125 #ifndef NO_COMPABILITY
1126 ert_comp.in_tabular = true;
1128 Inset * inset = new InsetTabular(*this);
1129 inset->read(this, lex);
1130 par->insertInset(pos, inset, font);
1132 } else if (token == "\\hfill") {
1133 par->insertChar(pos, Paragraph::META_HFILL, font);
1135 } else if (token == "\\protected_separator") { // obsolete
1136 // This is a backward compability thingie. (Lgb)
1137 // Remove it later some time...introduced with fileformat
1139 LyXLayout const & layout =
1140 textclasslist[params.textclass][par->layout()];
1142 if (layout.free_spacing || par->isFreeSpacing()) {
1143 par->insertChar(pos, ' ', font);
1145 Inset * inset = new InsetSpecialChar(InsetSpecialChar::PROTECTED_SEPARATOR);
1146 par->insertInset(pos, inset, font);
1149 } else if (token == "\\bibitem") { // ale970302
1151 InsetCommandParams p("bibitem", "dummy");
1152 par->bibkey = new InsetBibKey(p);
1154 par->bibkey->read(this, lex);
1155 } else if (token == "\\backslash") {
1156 #ifndef NO_COMPABILITY
1157 if (ert_comp.active) {
1158 ert_comp.contents += "\\";
1161 par->insertChar(pos, '\\', font);
1163 #ifndef NO_COMPABILITY
1166 } else if (token == "\\the_end") {
1167 #ifndef NO_COMPABILITY
1168 // If we still have some ert active here we have to insert
1169 // it so we don't loose it. (Lgb)
1170 insertErtContents(par, pos);
1172 the_end_read = true;
1173 #ifndef NO_COMPABILITY
1174 #ifndef NO_PEXTRA_REALLY
1177 minipar = parBeforeMinipage = 0;
1181 #ifndef NO_COMPABILITY
1182 if (ert_comp.active) {
1183 ert_comp.contents += token;
1186 // This should be insurance for the future: (Asger)
1189 string const s = _("Unknown token: ") + token
1190 + " " + lex.text() + "\n";
1192 InsetError * new_inset = new InsetError(s);
1193 par->insertInset(pos, new_inset, LyXFont(LyXFont::ALL_INHERIT,
1196 #ifndef NO_COMPABILITY
1201 #ifndef NO_COMPABILITY
1202 #ifndef NO_PEXTRA_REALLY
1203 // I wonder if we could use this blanket fix for all the
1204 // checkminipage cases...
1205 // don't forget about ert paragraphs and compatibility read for'em
1206 if (par && (par->size() || !ert_comp.contents.empty())) {
1207 // It is possible that this will check to often,
1208 // but that should not be an correctness issue.
1209 // Only a speed issue.
1210 checkminipage = true;
1213 // now check if we have a minipage paragraph as at this
1214 // point we already read all the necessary data!
1215 // this cannot be done in layout because there we did
1216 // not read yet the paragraph PEXTRA-params (Jug)
1218 // BEGIN pextra_minipage compability
1219 // This should be removed in 1.3.x (Lgb)
1220 // I don't think we should remove this so fast (Jug)
1222 // This compability code is not perfect. In a couple
1223 // of rand cases it fails. When the minipage par is
1224 // the first par in the document, and when there are
1225 // none or only one regular paragraphs after the
1226 // minipage. Currently I am not investing any effort
1227 // in fixing those cases.
1229 //lyxerr << "Call depth: " << call_depth << endl;
1230 if (checkminipage && (call_depth == 1)) {
1231 checkminipage = false;
1232 if (minipar && (minipar != par) &&
1233 (par->params().pextraType() == Paragraph::PEXTRA_MINIPAGE))
1235 lyxerr << "minipages in a row" << endl;
1236 if (par->params().pextraStartMinipage()) {
1237 lyxerr << "start new minipage" << endl;
1238 // minipages in a row
1239 par->previous()->next(0);
1242 Paragraph * tmp = minipar;
1244 tmp->params().pextraType(0);
1245 tmp->params().pextraWidth(string());
1246 tmp->params().pextraWidthp(string());
1247 tmp->params().pextraAlignment(0);
1248 tmp->params().pextraHfill(false);
1249 tmp->params().pextraStartMinipage(false);
1252 // create a new paragraph to insert the
1253 // minipages in the following case
1254 if (par->params().pextraStartMinipage() &&
1255 !par->params().pextraHfill()) {
1256 Paragraph * p = new Paragraph;
1257 p->layout(textclasslist[params.textclass].defaultLayoutName());
1259 p->previous(parBeforeMinipage);
1260 parBeforeMinipage->next(p);
1262 p->params().depth(parBeforeMinipage->params().depth());
1263 parBeforeMinipage = p;
1265 InsetMinipage * mini = new InsetMinipage(params);
1266 mini->pos(static_cast<InsetMinipage::Position>(par->params().pextraAlignment()));
1267 mini->pageWidth(LyXLength(par->params().pextraWidth()));
1268 if (!par->params().pextraWidthp().empty()) {
1269 lyxerr << "WP:" << mini->pageWidth().asString() << endl;
1270 mini->pageWidth(LyXLength((par->params().pextraWidthp())+"p%"));
1272 Paragraph * op = mini->firstParagraph();
1273 mini->inset.paragraph(par);
1275 // and free the old ones!
1278 Paragraph * pp = op->next();
1282 // Insert the minipage last in the
1283 // previous paragraph.
1284 if (par->params().pextraHfill()) {
1285 parBeforeMinipage->insertChar
1286 (parBeforeMinipage->size(), Paragraph::META_HFILL);
1288 parBeforeMinipage->insertInset
1289 (parBeforeMinipage->size(), mini);
1293 lyxerr << "new minipage par" << endl;
1294 //nothing to do just continue reading
1297 } else if (minipar && (minipar != par)) {
1298 lyxerr << "last minipage par read" << endl;
1299 // The last paragraph read was not part of a
1300 // minipage but the par linked list is...
1301 // So we need to remove the last par from the
1303 if (par->previous())
1304 par->previous()->next(0);
1305 par->previous(parBeforeMinipage);
1306 parBeforeMinipage->next(par);
1307 Paragraph * tmp = minipar;
1309 tmp->params().pextraType(0);
1310 tmp->params().pextraWidth(string());
1311 tmp->params().pextraWidthp(string());
1312 tmp->params().pextraAlignment(0);
1313 tmp->params().pextraHfill(false);
1314 tmp->params().pextraStartMinipage(false);
1317 depth = parBeforeMinipage->params().depth();
1318 // and set this depth on the par as it has not been set already
1319 par->params().depth(depth);
1320 minipar = parBeforeMinipage = 0;
1321 } else if (!minipar &&
1322 (par->params().pextraType() == Paragraph::PEXTRA_MINIPAGE))
1324 // par is the first paragraph in a minipage
1325 lyxerr << "begin minipage" << endl;
1326 // To minimize problems for
1327 // the users we will insert
1328 // the first minipage in
1329 // a sequence of minipages
1330 // in its own paragraph.
1331 Paragraph * p = new Paragraph;
1332 p->layout(textclasslist[params.textclass].defaultLayoutName());
1333 p->previous(par->previous());
1335 p->params().depth(depth);
1336 par->params().depth(0);
1338 if (par->previous())
1339 par->previous()->next(p);
1341 parBeforeMinipage = p;
1343 if (!first_par || (first_par == par))
1346 InsetMinipage * mini = new InsetMinipage(params);
1347 mini->pos(static_cast<InsetMinipage::Position>(minipar->params().pextraAlignment()));
1348 mini->pageWidth(LyXLength(minipar->params().pextraWidth()));
1349 if (!par->params().pextraWidthp().empty()) {
1350 lyxerr << "WP:" << mini->pageWidth().asString() << endl;
1351 mini->pageWidth(LyXLength((par->params().pextraWidthp())+"p%"));
1354 Paragraph * op = mini->firstParagraph();
1355 mini->inset.paragraph(minipar);
1357 // and free the old ones!
1360 Paragraph * pp = op->next();
1365 // Insert the minipage last in the
1366 // previous paragraph.
1367 if (minipar->params().pextraHfill()) {
1368 parBeforeMinipage->insertChar
1369 (parBeforeMinipage->size(),Paragraph::META_HFILL);
1371 parBeforeMinipage->insertInset
1372 (parBeforeMinipage->size(), mini);
1375 // End of pextra_minipage compability
1379 return the_end_read;
1382 // needed to insert the selection
1383 void Buffer::insertStringAsLines(Paragraph *& par, pos_type & pos,
1384 LyXFont const & fn,string const & str) const
1386 LyXLayout const & layout =
1387 textclasslist[params.textclass][par->layout()];
1390 par->checkInsertChar(font);
1391 // insert the string, don't insert doublespace
1392 bool space_inserted = true;
1393 for(string::const_iterator cit = str.begin();
1394 cit != str.end(); ++cit) {
1396 if (par->size() || layout.keepempty) {
1397 par->breakParagraph(params, pos,
1398 layout.isEnvironment());
1401 space_inserted = true;
1405 // do not insert consecutive spaces if !free_spacing
1406 } else if ((*cit == ' ' || *cit == '\t') &&
1407 space_inserted && !layout.free_spacing &&
1408 !par->isFreeSpacing())
1411 } else if (*cit == '\t') {
1412 if (!layout.free_spacing && !par->isFreeSpacing()) {
1413 // tabs are like spaces here
1414 par->insertChar(pos, ' ', font);
1416 space_inserted = true;
1418 const pos_type nb = 8 - pos % 8;
1419 for (pos_type a = 0; a < nb ; ++a) {
1420 par->insertChar(pos, ' ', font);
1423 space_inserted = true;
1425 } else if (!IsPrintable(*cit)) {
1426 // Ignore unprintables
1429 // just insert the character
1430 par->insertChar(pos, *cit, font);
1432 space_inserted = (*cit == ' ');
1439 void Buffer::readInset(LyXLex & lex, Paragraph *& par,
1440 int & pos, LyXFont & font)
1442 // consistency check
1443 if (lex.getString() != "\\begin_inset") {
1444 lyxerr << "Buffer::readInset: Consistency check failed."
1451 string const tmptok = lex.getString();
1452 last_inset_read = tmptok;
1454 // test the different insets
1455 if (tmptok == "LatexCommand") {
1456 InsetCommandParams inscmd;
1459 string const cmdName = inscmd.getCmdName();
1461 // This strange command allows LyX to recognize "natbib" style
1462 // citations: citet, citep, Citet etc.
1463 if (compare_no_case(cmdName, "cite", 4) == 0) {
1464 inset = new InsetCitation(inscmd);
1465 } else if (cmdName == "bibitem") {
1466 lex.printError("Wrong place for bibitem");
1467 inset = new InsetBibKey(inscmd);
1468 } else if (cmdName == "BibTeX") {
1469 inset = new InsetBibtex(inscmd);
1470 } else if (cmdName == "index") {
1471 inset = new InsetIndex(inscmd);
1472 } else if (cmdName == "include") {
1473 inset = new InsetInclude(inscmd, *this);
1474 } else if (cmdName == "label") {
1475 inset = new InsetLabel(inscmd);
1476 } else if (cmdName == "url"
1477 || cmdName == "htmlurl") {
1478 inset = new InsetUrl(inscmd);
1479 } else if (cmdName == "ref"
1480 || cmdName == "pageref"
1481 || cmdName == "vref"
1482 || cmdName == "vpageref"
1483 || cmdName == "prettyref") {
1484 if (!inscmd.getOptions().empty()
1485 || !inscmd.getContents().empty()) {
1486 inset = new InsetRef(inscmd, *this);
1488 } else if (cmdName == "tableofcontents") {
1489 inset = new InsetTOC(inscmd);
1490 } else if (cmdName == "listofalgorithms") {
1491 inset = new InsetFloatList("algorithm");
1492 } else if (cmdName == "listoffigures") {
1493 inset = new InsetFloatList("figure");
1494 } else if (cmdName == "listoftables") {
1495 inset = new InsetFloatList("table");
1496 } else if (cmdName == "printindex") {
1497 inset = new InsetPrintIndex(inscmd);
1498 } else if (cmdName == "lyxparent") {
1499 inset = new InsetParent(inscmd, *this);
1502 bool alreadyread = false;
1503 if (tmptok == "Quotes") {
1504 inset = new InsetQuotes;
1505 } else if (tmptok == "External") {
1506 inset = new InsetExternal;
1507 } else if (tmptok == "FormulaMacro") {
1508 inset = new InsetFormulaMacro;
1509 } else if (tmptok == "Formula") {
1510 inset = new InsetFormula;
1511 } else if (tmptok == "Figure") { // Backward compatibility
1512 // inset = new InsetFig(100, 100, *this);
1513 inset = new InsetGraphics;
1514 } else if (tmptok == "Graphics") {
1515 inset = new InsetGraphics;
1516 } else if (tmptok == "Info") {// backwards compatibility
1517 inset = new InsetNote(this,
1518 lex.getLongString("\\end_inset"),
1521 } else if (tmptok == "Note") {
1522 inset = new InsetNote(params);
1523 } else if (tmptok == "Include") {
1524 InsetCommandParams p("Include");
1525 inset = new InsetInclude(p, *this);
1526 } else if (tmptok == "ERT") {
1527 inset = new InsetERT(params);
1528 } else if (tmptok == "Tabular") {
1529 inset = new InsetTabular(*this);
1530 } else if (tmptok == "Text") {
1531 inset = new InsetText(params);
1532 } else if (tmptok == "Foot") {
1533 inset = new InsetFoot(params);
1534 } else if (tmptok == "Marginal") {
1535 inset = new InsetMarginal(params);
1536 } else if (tmptok == "Minipage") {
1537 inset = new InsetMinipage(params);
1538 } else if (tmptok == "Float") {
1540 string tmptok = lex.getString();
1541 inset = new InsetFloat(params, tmptok);
1543 } else if (tmptok == "List") {
1544 inset = new InsetList;
1545 } else if (tmptok == "Theorem") {
1546 inset = new InsetList;
1548 } else if (tmptok == "Caption") {
1549 inset = new InsetCaption(params);
1550 } else if (tmptok == "FloatList") {
1551 inset = new InsetFloatList;
1554 if (inset && !alreadyread) inset->read(this, lex);
1558 par->insertInset(pos, inset, font);
1564 bool Buffer::readFile(LyXLex & lex, Paragraph * par)
1568 string const token(lex.getString());
1569 if (token == "\\lyxformat") { // the first token _must_ be...
1571 string tmp_format = lex.getString();
1572 //lyxerr << "LyX Format: `" << tmp_format << "'" << endl;
1573 // if present remove ".," from string.
1574 string::size_type dot = tmp_format.find_first_of(".,");
1575 //lyxerr << " dot found at " << dot << endl;
1576 if (dot != string::npos)
1577 tmp_format.erase(dot, 1);
1578 file_format = strToInt(tmp_format);
1579 if (file_format == LYX_FORMAT) {
1581 } else if (file_format > LYX_FORMAT) {
1583 Alert::alert(_("Warning!"),
1584 _("LyX file format is newer that what"),
1585 _("is supported in this LyX version. Expect some problems."));
1587 } else if (file_format < LYX_FORMAT) {
1589 if (file_format < 200) {
1590 Alert::alert(_("ERROR!"),
1591 _("Old LyX file format found. "
1592 "Use LyX 0.10.x to read this!"));
1596 bool the_end = readLyXformat2(lex, par);
1597 params.setPaperStuff();
1598 // the_end was added in 213
1599 if (file_format < 213)
1603 Alert::alert(_("Warning!"),
1604 _("Reading of document is not complete"),
1605 _("Maybe the document is truncated"));
1608 } else { // "\\lyxformat" not found
1609 Alert::alert(_("ERROR!"), _("Not a LyX file!"));
1612 Alert::alert(_("ERROR!"), _("Unable to read file!"));
1617 // Should probably be moved to somewhere else: BufferView? LyXView?
1618 bool Buffer::save() const
1620 // We don't need autosaves in the immediate future. (Asger)
1621 resetAutosaveTimers();
1625 if (lyxrc.make_backup) {
1626 s = fileName() + '~';
1627 if (!lyxrc.backupdir_path.empty())
1628 s = AddName(lyxrc.backupdir_path,
1629 subst(os::slashify_path(s),'/','!'));
1631 // Rename is the wrong way of making a backup,
1632 // this is the correct way.
1633 /* truss cp fil fil2:
1634 lstat("LyXVC3.lyx", 0xEFFFF898) Err#2 ENOENT
1635 stat("LyXVC.lyx", 0xEFFFF688) = 0
1636 open("LyXVC.lyx", O_RDONLY) = 3
1637 open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
1638 fstat(4, 0xEFFFF508) = 0
1639 fstat(3, 0xEFFFF508) = 0
1640 read(3, " # T h i s f i l e w".., 8192) = 5579
1641 write(4, " # T h i s f i l e w".., 5579) = 5579
1642 read(3, 0xEFFFD4A0, 8192) = 0
1645 chmod("LyXVC3.lyx", 0100644) = 0
1646 lseek(0, 0, SEEK_CUR) = 46440
1650 // Should probably have some more error checking here.
1651 // Should be cleaned up in 0.13, at least a bit.
1652 // Doing it this way, also makes the inodes stay the same.
1653 // This is still not a very good solution, in particular we
1654 // might loose the owner of the backup.
1655 FileInfo finfo(fileName());
1656 if (finfo.exist()) {
1657 mode_t fmode = finfo.getMode();
1658 struct utimbuf times = {
1659 finfo.getAccessTime(),
1660 finfo.getModificationTime() };
1662 ifstream ifs(fileName().c_str());
1663 ofstream ofs(s.c_str(), ios::out|ios::trunc);
1668 ::chmod(s.c_str(), fmode);
1670 if (::utime(s.c_str(), ×)) {
1671 lyxerr << "utime error." << endl;
1674 lyxerr << "LyX was not able to make "
1675 "backup copy. Beware." << endl;
1680 if (writeFile(fileName(), false)) {
1682 removeAutosaveFile(fileName());
1684 // Saving failed, so backup is not backup
1685 if (lyxrc.make_backup) {
1686 lyx::rename(s, fileName());
1694 // Returns false if unsuccesful
1695 bool Buffer::writeFile(string const & fname, bool flag) const
1697 // if flag is false writeFile will not create any GUI
1698 // warnings, only cerr.
1699 // Needed for autosave in background or panic save (Matthias 120496)
1701 if (read_only && (fname == fileName())) {
1702 // Here we should come with a question if we should
1703 // perform the write anyway.
1705 lyxerr << _("Error! Document is read-only: ")
1708 Alert::alert(_("Error! Document is read-only: "),
1713 FileInfo finfo(fname);
1714 if (finfo.exist() && !finfo.writable()) {
1715 // Here we should come with a question if we should
1716 // try to do the save anyway. (i.e. do a chmod first)
1718 lyxerr << _("Error! Cannot write file: ")
1721 Alert::err_alert(_("Error! Cannot write file: "),
1726 ofstream ofs(fname.c_str());
1729 lyxerr << _("Error! Cannot open file: ")
1732 Alert::err_alert(_("Error! Cannot open file: "),
1738 // Use the standard "C" locale for file output.
1739 ofs.imbue(std::locale::classic());
1742 // The top of the file should not be written by params.
1744 // write out a comment in the top of the file
1745 ofs << '#' << lyx_docversion
1746 << " created this file. For more info see http://www.lyx.org/\n"
1747 << "\\lyxformat " << LYX_FORMAT << "\n";
1749 // now write out the buffer paramters.
1750 params.writeFile(ofs);
1752 Paragraph::depth_type depth = 0;
1754 // this will write out all the paragraphs
1755 // using recursive descent.
1756 paragraph->writeFile(this, ofs, params, depth);
1758 // Write marker that shows file is complete
1759 ofs << "\n\\the_end" << endl;
1763 // how to check if close went ok?
1764 // Following is an attempt... (BE 20001011)
1766 // good() returns false if any error occured, including some
1767 // formatting error.
1768 // bad() returns true if something bad happened in the buffer,
1769 // which should include file system full errors.
1776 lyxerr << "Buffer::writeFile: BAD ERROR!" << endl;
1778 lyxerr << "Buffer::writeFile: NOT SO BAD ERROR!"
1788 string const Buffer::asciiParagraph(Paragraph const * par,
1789 unsigned int linelen,
1790 bool noparbreak) const
1792 ostringstream buffer;
1794 Paragraph::depth_type depth = 0;
1796 Paragraph::depth_type ltype_depth = 0;
1797 string::size_type currlinelen = 0;
1798 bool ref_printed = false;
1799 // if (!par->previous()) {
1801 // begins or ends a deeper area ?
1802 if (depth != par->params().depth()) {
1803 if (par->params().depth() > depth) {
1804 while (par->params().depth() > depth) {
1808 while (par->params().depth() < depth) {
1814 depth = par->params().depth();
1817 // First write the layout
1818 string const & tmp = par->layout();
1819 if (compare_no_case(tmp, "itemize") == 0) {
1821 ltype_depth = depth + 1;
1822 } else if (compare_no_case(tmp, "enumerate") == 0) {
1824 ltype_depth = depth + 1;
1825 } else if (contains(lowercase(tmp), "ection")) {
1827 ltype_depth = depth + 1;
1828 } else if (contains(lowercase(tmp), "aragraph")) {
1830 ltype_depth = depth + 1;
1831 } else if (compare_no_case(tmp, "description") == 0) {
1833 ltype_depth = depth + 1;
1834 } else if (compare_no_case(tmp, "abstract") == 0) {
1837 } else if (compare_no_case(tmp, "bibliography") == 0) {
1845 /* maybe some vertical spaces */
1847 /* the labelwidthstring used in lists */
1851 /* some pagebreaks? */
1855 /* what about the alignment */
1857 // lyxerr << "Should this ever happen?" << endl;
1860 // linelen <= 0 is special and means we don't have pargraph breaks
1864 for (Paragraph::depth_type j = 0; j < depth; ++j)
1866 currlinelen = depth * 2;
1868 // we should probably change to the paragraph language in the
1869 // gettext here (if possible) so that strings are outputted in
1870 // the correct language! (20012712 Jug)
1874 case 4: // (Sub)Paragraph
1875 case 5: // Description
1879 buffer << _("Abstract") << "\n\n";
1881 buffer << _("Abstract: ");
1883 case 7: // Bibliography
1886 buffer << _("References") << "\n\n";
1888 buffer << _("References: ");
1893 buffer << par->params().labelString() << " ";
1897 string s = buffer.str();
1898 if (s.rfind('\n') != string::npos) {
1900 s = rsplit(buffer.str().c_str(), dummy, '\n');
1902 currlinelen = s.length();
1904 for (Paragraph::depth_type j = 0; j < depth; ++j)
1906 currlinelen = depth * 2;
1907 if (ltype_depth > depth) {
1908 for (Paragraph::depth_type j = ltype_depth;
1913 currlinelen += (ltype_depth-depth)*2;
1916 // this is to change the linebreak to do it by word a bit more intelligent
1917 // hopefully! (only in the case where we have a max linelenght!) (Jug)
1918 for (pos_type i = 0; i < par->size(); ++i) {
1919 char c = par->getUChar(params, i);
1921 case Paragraph::META_INSET:
1923 Inset const * inset = par->getInset(i);
1926 buffer << word.str();
1929 if (inset->ascii(this, buffer, linelen)) {
1930 // to be sure it breaks paragraph
1931 currlinelen += linelen;
1937 rsplit(buffer.str().c_str(),
1939 currlinelen = s.length();
1946 case Paragraph::META_NEWLINE:
1948 buffer << word.str() << "\n";
1950 for (Paragraph::depth_type j = 0;
1953 currlinelen = depth * 2;
1954 if (ltype_depth > depth) {
1955 for (Paragraph::depth_type j = ltype_depth;
1958 currlinelen += (ltype_depth - depth) * 2;
1963 case Paragraph::META_HFILL:
1964 buffer << word.str() << "\t";
1965 currlinelen += word.str().length() + 1;
1971 buffer << word.str() << ' ';
1972 currlinelen += word.str().length() + 1;
1978 lyxerr[Debug::INFO] <<
1979 "writeAsciiFile: NULL char in structure." << endl;
1981 if ((linelen > 0) &&
1982 (currlinelen+word.str().length()) > linelen)
1985 for (Paragraph::depth_type j = 0; j < depth; ++j)
1987 currlinelen = depth * 2;
1988 if (ltype_depth > depth) {
1989 for (Paragraph::depth_type j = ltype_depth;
1994 currlinelen += (ltype_depth-depth)*2;
2001 buffer << word.str();
2002 return buffer.str().c_str();
2006 void Buffer::writeFileAscii(string const & fname, int linelen)
2008 ofstream ofs(fname.c_str());
2010 Alert::err_alert(_("Error: Cannot write file:"), fname);
2013 writeFileAscii(ofs, linelen);
2017 void Buffer::writeFileAscii(ostream & ofs, int linelen)
2019 Paragraph * par = paragraph;
2021 ofs << asciiParagraph(par, linelen, par->previous() == 0);
2031 void Buffer::makeLaTeXFile(string const & fname,
2032 string const & original_path,
2033 bool nice, bool only_body)
2035 lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
2037 niceFile = nice; // this will be used by Insetincludes.
2039 tex_code_break_column = lyxrc.ascii_linelen;
2041 ofstream ofs(fname.c_str());
2043 Alert::err_alert(_("Error: Cannot open file: "), fname);
2047 // validate the buffer.
2048 lyxerr[Debug::LATEX] << " Validating buffer..." << endl;
2049 LaTeXFeatures features(params);
2051 lyxerr[Debug::LATEX] << " Buffer validation done." << endl;
2054 // The starting paragraph of the coming rows is the
2055 // first paragraph of the document. (Asger)
2056 texrow.start(paragraph, 0);
2058 if (!only_body && nice) {
2059 ofs << "%% " << lyx_docversion << " created this file. "
2060 "For more info, see http://www.lyx.org/.\n"
2061 "%% Do not edit unless you really know what "
2066 lyxerr[Debug::INFO] << "lyx header finished" << endl;
2067 // There are a few differences between nice LaTeX and usual files:
2068 // usual is \batchmode and has a
2069 // special input@path to allow the including of figures
2070 // with either \input or \includegraphics (what figinsets do).
2071 // batchmode is not set if there is a tex_code_break_column.
2072 // In this case somebody is interested in the generated LaTeX,
2073 // so this is OK. input@path is set when the actual parameter
2074 // original_path is set. This is done for usual tex-file, but not
2075 // for nice-latex-file. (Matthias 250696)
2078 // code for usual, NOT nice-latex-file
2079 ofs << "\\batchmode\n"; // changed
2080 // from \nonstopmode
2083 if (!original_path.empty()) {
2084 ofs << "\\makeatletter\n"
2085 << "\\def\\input@path{{"
2086 << os::external_path(original_path) << "/}}\n"
2087 << "\\makeatother\n";
2093 ofs << "\\documentclass";
2095 LyXTextClass const & tclass = textclasslist[params.textclass];
2097 ostringstream options; // the document class options.
2099 if (tokenPos(tclass.opt_fontsize(),
2100 '|', params.fontsize) >= 0) {
2101 // only write if existing in list (and not default)
2102 options << params.fontsize << "pt,";
2106 if (!params.use_geometry &&
2107 (params.paperpackage == BufferParams::PACKAGE_NONE)) {
2108 switch (params.papersize) {
2109 case BufferParams::PAPER_A4PAPER:
2110 options << "a4paper,";
2112 case BufferParams::PAPER_USLETTER:
2113 options << "letterpaper,";
2115 case BufferParams::PAPER_A5PAPER:
2116 options << "a5paper,";
2118 case BufferParams::PAPER_B5PAPER:
2119 options << "b5paper,";
2121 case BufferParams::PAPER_EXECUTIVEPAPER:
2122 options << "executivepaper,";
2124 case BufferParams::PAPER_LEGALPAPER:
2125 options << "legalpaper,";
2131 if (params.sides != tclass.sides()) {
2132 switch (params.sides) {
2133 case LyXTextClass::OneSide:
2134 options << "oneside,";
2136 case LyXTextClass::TwoSides:
2137 options << "twoside,";
2143 if (params.columns != tclass.columns()) {
2144 if (params.columns == 2)
2145 options << "twocolumn,";
2147 options << "onecolumn,";
2150 if (!params.use_geometry
2151 && params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
2152 options << "landscape,";
2154 // language should be a parameter to \documentclass
2156 ostringstream language_options;
2157 if (params.language->babel() == "hebrew"
2158 && default_language->babel() != "hebrew")
2159 // This seems necessary
2160 features.useLanguage(default_language);
2162 if (lyxrc.language_use_babel ||
2163 params.language->lang() != lyxrc.default_language ||
2164 !features.hasLanguages()) {
2166 language_options << features.getLanguages();
2167 language_options << params.language->babel();
2168 if (lyxrc.language_global_options)
2169 options << language_options.str() << ',';
2172 // the user-defined options
2173 if (!params.options.empty()) {
2174 options << params.options << ',';
2177 string strOptions(options.str().c_str());
2178 if (!strOptions.empty()) {
2179 strOptions = strip(strOptions, ',');
2180 ofs << '[' << strOptions << ']';
2183 ofs << '{' << tclass.latexname() << "}\n";
2185 // end of \documentclass defs
2187 // font selection must be done before loading fontenc.sty
2188 // The ae package is not needed when using OT1 font encoding.
2189 if (params.fonts != "default" &&
2190 (params.fonts != "ae" || lyxrc.fontenc != "default")) {
2191 ofs << "\\usepackage{" << params.fonts << "}\n";
2193 if (params.fonts == "ae") {
2194 ofs << "\\usepackage{aecompl}\n";
2198 // this one is not per buffer
2199 if (lyxrc.fontenc != "default") {
2200 ofs << "\\usepackage[" << lyxrc.fontenc
2205 if (params.inputenc == "auto") {
2206 string const doc_encoding =
2207 params.language->encoding()->LatexName();
2209 // Create a list with all the input encodings used
2211 set<string> encodings = features.getEncodingSet(doc_encoding);
2213 ofs << "\\usepackage[";
2214 std::copy(encodings.begin(), encodings.end(),
2215 std::ostream_iterator<string>(ofs, ","));
2216 ofs << doc_encoding << "]{inputenc}\n";
2218 } else if (params.inputenc != "default") {
2219 ofs << "\\usepackage[" << params.inputenc
2224 // At the very beginning the text parameters.
2225 if (params.paperpackage != BufferParams::PACKAGE_NONE) {
2226 switch (params.paperpackage) {
2227 case BufferParams::PACKAGE_A4:
2228 ofs << "\\usepackage{a4}\n";
2231 case BufferParams::PACKAGE_A4WIDE:
2232 ofs << "\\usepackage{a4wide}\n";
2235 case BufferParams::PACKAGE_WIDEMARGINSA4:
2236 ofs << "\\usepackage[widemargins]{a4}\n";
2241 if (params.use_geometry) {
2242 ofs << "\\usepackage{geometry}\n";
2244 ofs << "\\geometry{verbose";
2245 if (params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
2246 ofs << ",landscape";
2247 switch (params.papersize2) {
2248 case BufferParams::VM_PAPER_CUSTOM:
2249 if (!params.paperwidth.empty())
2250 ofs << ",paperwidth="
2251 << params.paperwidth;
2252 if (!params.paperheight.empty())
2253 ofs << ",paperheight="
2254 << params.paperheight;
2256 case BufferParams::VM_PAPER_USLETTER:
2257 ofs << ",letterpaper";
2259 case BufferParams::VM_PAPER_USLEGAL:
2260 ofs << ",legalpaper";
2262 case BufferParams::VM_PAPER_USEXECUTIVE:
2263 ofs << ",executivepaper";
2265 case BufferParams::VM_PAPER_A3:
2268 case BufferParams::VM_PAPER_A4:
2271 case BufferParams::VM_PAPER_A5:
2274 case BufferParams::VM_PAPER_B3:
2277 case BufferParams::VM_PAPER_B4:
2280 case BufferParams::VM_PAPER_B5:
2284 // default papersize ie BufferParams::VM_PAPER_DEFAULT
2285 switch (lyxrc.default_papersize) {
2286 case BufferParams::PAPER_DEFAULT: // keep compiler happy
2287 case BufferParams::PAPER_USLETTER:
2288 ofs << ",letterpaper";
2290 case BufferParams::PAPER_LEGALPAPER:
2291 ofs << ",legalpaper";
2293 case BufferParams::PAPER_EXECUTIVEPAPER:
2294 ofs << ",executivepaper";
2296 case BufferParams::PAPER_A3PAPER:
2299 case BufferParams::PAPER_A4PAPER:
2302 case BufferParams::PAPER_A5PAPER:
2305 case BufferParams::PAPER_B5PAPER:
2310 if (!params.topmargin.empty())
2311 ofs << ",tmargin=" << params.topmargin;
2312 if (!params.bottommargin.empty())
2313 ofs << ",bmargin=" << params.bottommargin;
2314 if (!params.leftmargin.empty())
2315 ofs << ",lmargin=" << params.leftmargin;
2316 if (!params.rightmargin.empty())
2317 ofs << ",rmargin=" << params.rightmargin;
2318 if (!params.headheight.empty())
2319 ofs << ",headheight=" << params.headheight;
2320 if (!params.headsep.empty())
2321 ofs << ",headsep=" << params.headsep;
2322 if (!params.footskip.empty())
2323 ofs << ",footskip=" << params.footskip;
2328 if (tokenPos(tclass.opt_pagestyle(),
2329 '|', params.pagestyle) >= 0) {
2330 if (params.pagestyle == "fancy") {
2331 ofs << "\\usepackage{fancyhdr}\n";
2334 ofs << "\\pagestyle{" << params.pagestyle << "}\n";
2338 if (params.secnumdepth != tclass.secnumdepth()) {
2339 ofs << "\\setcounter{secnumdepth}{"
2340 << params.secnumdepth
2344 if (params.tocdepth != tclass.tocdepth()) {
2345 ofs << "\\setcounter{tocdepth}{"
2351 if (params.paragraph_separation) {
2352 switch (params.defskip.kind()) {
2353 case VSpace::SMALLSKIP:
2354 ofs << "\\setlength\\parskip{\\smallskipamount}\n";
2356 case VSpace::MEDSKIP:
2357 ofs << "\\setlength\\parskip{\\medskipamount}\n";
2359 case VSpace::BIGSKIP:
2360 ofs << "\\setlength\\parskip{\\bigskipamount}\n";
2362 case VSpace::LENGTH:
2363 ofs << "\\setlength\\parskip{"
2364 << params.defskip.length().asLatexString()
2367 default: // should never happen // Then delete it.
2368 ofs << "\\setlength\\parskip{\\medskipamount}\n";
2373 ofs << "\\setlength\\parindent{0pt}\n";
2377 // Now insert the LyX specific LaTeX commands...
2379 // The optional packages;
2380 string preamble(features.getPackages());
2382 // this might be useful...
2383 preamble += "\n\\makeatletter\n";
2385 // Some macros LyX will need
2386 string tmppreamble(features.getMacros());
2388 if (!tmppreamble.empty()) {
2389 preamble += "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2390 "LyX specific LaTeX commands.\n"
2391 + tmppreamble + '\n';
2394 // the text class specific preamble
2395 tmppreamble = features.getTClassPreamble();
2396 if (!tmppreamble.empty()) {
2397 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2398 "Textclass specific LaTeX commands.\n"
2399 + tmppreamble + '\n';
2402 /* the user-defined preamble */
2403 if (!params.preamble.empty()) {
2404 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2405 "User specified LaTeX commands.\n"
2406 + params.preamble + '\n';
2409 preamble += "\\makeatother\n";
2411 // Itemize bullet settings need to be last in case the user
2412 // defines their own bullets that use a package included
2413 // in the user-defined preamble -- ARRae
2414 // Actually it has to be done much later than that
2415 // since some packages like frenchb make modifications
2416 // at \begin{document} time -- JMarc
2418 for (int i = 0; i < 4; ++i) {
2419 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
2420 if (bullets_def.empty())
2421 bullets_def="\\AtBeginDocument{\n";
2422 bullets_def += " \\renewcommand{\\labelitemi";
2424 // `i' is one less than the item to modify
2431 bullets_def += "ii";
2437 bullets_def += "}{" +
2438 params.user_defined_bullets[i].getText()
2443 if (!bullets_def.empty())
2444 preamble += bullets_def + "}\n\n";
2447 int(lyx::count(preamble.begin(), preamble.end(), '\n'));
2448 for (int j = 0; j != nlines; ++j) {
2454 // We try to load babel late, in case it interferes
2455 // with other packages.
2457 string tmp = lyxrc.language_package;
2458 if (!lyxrc.language_global_options
2459 && tmp == "\\usepackage{babel}")
2460 tmp = string("\\usepackage[") +
2461 language_options.str().c_str() +
2468 ofs << "\\begin{document}\n";
2471 lyxerr[Debug::INFO] << "preamble finished, now the body." << endl;
2473 if (!lyxrc.language_auto_begin) {
2474 ofs << subst(lyxrc.language_command_begin, "$$lang",
2475 params.language->babel())
2480 latexParagraphs(ofs, paragraph, 0, texrow);
2482 // add this just in case after all the paragraphs
2486 if (!lyxrc.language_auto_end) {
2487 ofs << subst(lyxrc.language_command_end, "$$lang",
2488 params.language->babel())
2494 ofs << "\\end{document}\n";
2497 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
2499 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
2503 // Just to be sure. (Asger)
2506 // tex_code_break_column's value is used to decide
2507 // if we are in batchmode or not (within mathed_write()
2508 // in math_write.C) so we must set it to a non-zero
2509 // value when we leave otherwise we save incorrect .lyx files.
2510 tex_code_break_column = lyxrc.ascii_linelen;
2514 lyxerr << "File was not closed properly." << endl;
2517 lyxerr[Debug::INFO] << "Finished making latex file." << endl;
2518 lyxerr[Debug::INFO] << "Row count was " << texrow.rows()-1 << "." << endl;
2523 // LaTeX all paragraphs from par to endpar, if endpar == 0 then to the end
2525 void Buffer::latexParagraphs(ostream & ofs, Paragraph * par,
2526 Paragraph * endpar, TexRow & texrow) const
2528 bool was_title = false;
2529 bool already_title = false;
2532 while (par != endpar) {
2533 Inset * in = par->inInset();
2534 // well we have to check if we are in an inset with unlimited
2535 // lenght (all in one row) if that is true then we don't allow
2536 // any special options in the paragraph and also we don't allow
2537 // any environment other then "Standard" to be valid!
2538 if ((in == 0) || !in->forceDefaultParagraphs(in)) {
2539 LyXLayout const & layout =
2540 textclasslist[params.textclass][par->layout()];
2542 if (layout.intitle) {
2543 if (already_title) {
2544 lyxerr <<"Error in latexParagraphs: You"
2545 " should not mix title layouts"
2546 " with normal ones." << endl;
2549 } else if (was_title && !already_title) {
2550 ofs << "\\maketitle\n";
2552 already_title = true;
2556 if (layout.isEnvironment()) {
2557 par = par->TeXEnvironment(this, params, ofs, texrow);
2559 par = par->TeXOnePar(this, params, ofs, texrow, false);
2562 par = par->TeXOnePar(this, params, ofs, texrow, false);
2565 // It might be that we only have a title in this document
2566 if (was_title && !already_title) {
2567 ofs << "\\maketitle\n";
2573 bool Buffer::isLatex() const
2575 return textclasslist[params.textclass].outputType() == LATEX;
2579 bool Buffer::isLinuxDoc() const
2581 return textclasslist[params.textclass].outputType() == LINUXDOC;
2585 bool Buffer::isLiterate() const
2587 return textclasslist[params.textclass].outputType() == LITERATE;
2591 bool Buffer::isDocBook() const
2593 return textclasslist[params.textclass].outputType() == DOCBOOK;
2597 bool Buffer::isSGML() const
2599 LyXTextClass const & tclass = textclasslist[params.textclass];
2601 return tclass.outputType() == LINUXDOC ||
2602 tclass.outputType() == DOCBOOK;
2606 void Buffer::sgmlOpenTag(ostream & os, Paragraph::depth_type,
2607 string const & latexname) const
2609 if (!latexname.empty() && latexname != "!-- --")
2610 //os << "<!-- " << depth << " -->" << "<" << latexname << ">";
2611 os << "<" << latexname << ">";
2615 void Buffer::sgmlCloseTag(ostream & os, Paragraph::depth_type,
2616 string const & latexname) const
2618 if (!latexname.empty() && latexname != "!-- --")
2619 //os << "<!-- " << depth << " -->" << "</" << latexname << ">\n";
2620 os << "</" << latexname << ">";
2624 void Buffer::makeLinuxDocFile(string const & fname, bool nice, bool body_only)
2626 ofstream ofs(fname.c_str());
2629 Alert::alert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2633 niceFile = nice; // this will be used by included files.
2635 LaTeXFeatures features(params);
2641 LyXTextClass const & tclass = textclasslist[params.textclass];
2643 string top_element = tclass.latexname();
2646 ofs << "<!doctype linuxdoc system";
2648 string preamble = params.preamble;
2649 const string name = nice ? ChangeExtension(filename_, ".sgml")
2651 preamble += features.getIncludedFiles(name);
2652 preamble += features.getLyXSGMLEntities();
2654 if (!preamble.empty()) {
2655 ofs << " [ " << preamble << " ]";
2659 if (params.options.empty())
2660 sgmlOpenTag(ofs, 0, top_element);
2662 string top = top_element;
2664 top += params.options;
2665 sgmlOpenTag(ofs, 0, top);
2669 ofs << "<!-- " << lyx_docversion
2670 << " created this file. For more info see http://www.lyx.org/"
2673 Paragraph::depth_type depth = 0; // paragraph depth
2674 Paragraph * par = paragraph;
2676 vector<string> environment_stack(5);
2679 LyXLayout const & style = tclass[par->layout()];
2681 // treat <toc> as a special case for compatibility with old code
2682 if (par->isInset(0)) {
2683 Inset * inset = par->getInset(0);
2684 Inset::Code lyx_code = inset->lyxCode();
2685 if (lyx_code == Inset::TOC_CODE) {
2686 string const temp = "toc";
2687 sgmlOpenTag(ofs, depth, temp);
2694 // environment tag closing
2695 for (; depth > par->params().depth(); --depth) {
2696 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2697 environment_stack[depth].erase();
2700 // write opening SGML tags
2701 switch (style.latextype) {
2702 case LATEX_PARAGRAPH:
2703 if (depth == par->params().depth()
2704 && !environment_stack[depth].empty()) {
2705 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2706 environment_stack[depth].erase();
2712 sgmlOpenTag(ofs, depth, style.latexname());
2718 _("Error : Wrong depth for"
2719 " LatexType Command.\n"));
2721 if (!environment_stack[depth].empty()) {
2722 sgmlCloseTag(ofs, depth,
2723 environment_stack[depth]);
2727 environment_stack[depth].erase();
2728 sgmlOpenTag(ofs, depth, style.latexname());
2731 case LATEX_ENVIRONMENT:
2732 case LATEX_ITEM_ENVIRONMENT:
2733 if (depth == par->params().depth()
2734 && environment_stack[depth] != style.latexname()) {
2735 sgmlCloseTag(ofs, depth,
2736 environment_stack[depth]);
2737 environment_stack[depth].erase();
2739 if (depth < par->params().depth()) {
2740 depth = par->params().depth();
2741 environment_stack[depth].erase();
2743 if (environment_stack[depth] != style.latexname()) {
2745 sgmlOpenTag(ofs, depth, "p");
2747 sgmlOpenTag(ofs, depth, style.latexname());
2749 if (environment_stack.size() == depth + 1)
2750 environment_stack.push_back("!-- --");
2751 environment_stack[depth] = style.latexname();
2754 if (style.latexparam() == "CDATA")
2757 if (style.latextype == LATEX_ENVIRONMENT) break;
2759 if (style.labeltype == LABEL_MANUAL)
2764 sgmlOpenTag(ofs, depth + 1, item_name);
2767 sgmlOpenTag(ofs, depth, style.latexname());
2771 simpleLinuxDocOnePar(ofs, par, depth);
2776 // write closing SGML tags
2777 switch (style.latextype) {
2780 case LATEX_ENVIRONMENT:
2781 case LATEX_ITEM_ENVIRONMENT:
2782 if (style.latexparam() == "CDATA")
2786 sgmlCloseTag(ofs, depth, style.latexname());
2792 for (int i=depth; i >= 0; --i)
2793 sgmlCloseTag(ofs, depth, environment_stack[i]);
2797 sgmlCloseTag(ofs, 0, top_element);
2801 // How to check for successful close
2805 // checks, if newcol chars should be put into this line
2806 // writes newline, if necessary.
2809 void sgmlLineBreak(ostream & os, string::size_type & colcount,
2810 string::size_type newcol)
2813 if (colcount > lyxrc.ascii_linelen) {
2815 colcount = newcol; // assume write after this call
2830 string tag_name(PAR_TAG const & pt) {
2832 case NONE: return "!-- --";
2833 case TT: return "tt";
2834 case SF: return "sf";
2835 case BF: return "bf";
2836 case IT: return "it";
2837 case SL: return "sl";
2838 case EM: return "em";
2845 void operator|=(PAR_TAG & p1, PAR_TAG const & p2)
2847 p1 = static_cast<PAR_TAG>(p1 | p2);
2852 void reset(PAR_TAG & p1, PAR_TAG const & p2)
2854 p1 = static_cast<PAR_TAG>(p1 & ~p2);
2860 // Handle internal paragraph parsing -- layout already processed.
2861 void Buffer::simpleLinuxDocOnePar(ostream & os,
2863 Paragraph::depth_type /*depth*/)
2865 LyXLayout const & style =
2866 textclasslist[params.textclass][par->layout()];
2867 string::size_type char_line_count = 5; // Heuristic choice ;-)
2869 // gets paragraph main font
2872 if (style.labeltype == LABEL_MANUAL) {
2873 font_old = style.labelfont;
2876 font_old = style.font;
2880 LyXFont::FONT_FAMILY family_type = LyXFont::ROMAN_FAMILY;
2881 LyXFont::FONT_SERIES series_type = LyXFont::MEDIUM_SERIES;
2882 LyXFont::FONT_SHAPE shape_type = LyXFont::UP_SHAPE;
2885 stack<PAR_TAG> tag_state;
2886 // parsing main loop
2887 for (pos_type i = 0; i < par->size(); ++i) {
2889 PAR_TAG tag_close = NONE;
2890 list < PAR_TAG > tag_open;
2892 LyXFont const font = par->getFont(params, i);
2894 if (font_old.family() != font.family()) {
2895 switch (family_type) {
2896 case LyXFont::SANS_FAMILY:
2899 case LyXFont::TYPEWRITER_FAMILY:
2906 family_type = font.family();
2908 switch (family_type) {
2909 case LyXFont::SANS_FAMILY:
2910 tag_open.push_back(SF);
2912 case LyXFont::TYPEWRITER_FAMILY:
2913 tag_open.push_back(TT);
2920 if (font_old.series() != font.series()) {
2921 switch (series_type) {
2922 case LyXFont::BOLD_SERIES:
2929 series_type = font.series();
2931 switch (series_type) {
2932 case LyXFont::BOLD_SERIES:
2933 tag_open.push_back(BF);
2941 if (font_old.shape() != font.shape()) {
2942 switch (shape_type) {
2943 case LyXFont::ITALIC_SHAPE:
2946 case LyXFont::SLANTED_SHAPE:
2953 shape_type = font.shape();
2955 switch (shape_type) {
2956 case LyXFont::ITALIC_SHAPE:
2957 tag_open.push_back(IT);
2959 case LyXFont::SLANTED_SHAPE:
2960 tag_open.push_back(SL);
2967 if (font_old.emph() != font.emph()) {
2968 if (font.emph() == LyXFont::ON) {
2969 tag_open.push_back(EM);
2978 list < PAR_TAG > temp;
2979 while (!tag_state.empty() && tag_close) {
2980 PAR_TAG k = tag_state.top();
2982 os << "</" << tag_name(k) << ">";
2989 for(list< PAR_TAG >::const_iterator j = temp.begin();
2990 j != temp.end(); ++j) {
2992 os << "<" << tag_name(*j) << ">";
2995 for(list< PAR_TAG >::const_iterator j = tag_open.begin();
2996 j != tag_open.end(); ++j) {
2998 os << "<" << tag_name(*j) << ">";
3001 char c = par->getChar(i);
3003 if (c == Paragraph::META_INSET) {
3004 Inset * inset = par->getInset(i);
3005 inset->linuxdoc(this, os);
3010 if (style.latexparam() == "CDATA") {
3011 // "TeX"-Mode on == > SGML-Mode on.
3017 if (par->sgmlConvertChar(c, sgml_string)
3018 && !style.free_spacing && !par->isFreeSpacing())
3020 // in freespacing mode, spaces are
3021 // non-breaking characters
3022 if (desc_on) {// if char is ' ' then...
3025 sgmlLineBreak(os, char_line_count, 6);
3029 sgmlLineBreak(os, char_line_count, 1);
3034 char_line_count += sgml_string.length();
3040 while (!tag_state.empty()) {
3041 os << "</" << tag_name(tag_state.top()) << ">";
3045 // resets description flag correctly
3047 // <tag> not closed...
3048 sgmlLineBreak(os, char_line_count, 6);
3054 // Print an error message.
3055 void Buffer::sgmlError(Paragraph * par, int pos,
3056 string const & message) const
3058 // insert an error marker in text
3059 InsetError * new_inset = new InsetError(message);
3060 par->insertInset(pos, new_inset, LyXFont(LyXFont::ALL_INHERIT,
3065 void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
3067 ofstream ofs(fname.c_str());
3069 Alert::alert(_("LYX_ERROR:"), _("Cannot write file"), fname);
3073 Paragraph * par = paragraph;
3075 niceFile = nice; // this will be used by Insetincludes.
3077 LaTeXFeatures features(params);
3082 LyXTextClass const & tclass = textclasslist[params.textclass];
3083 string top_element = tclass.latexname();
3086 ofs << "<!DOCTYPE " << top_element
3087 << " PUBLIC \"-//OASIS//DTD DocBook V4.1//EN\"";
3089 string preamble = params.preamble;
3090 const string name = nice ? ChangeExtension(filename_, ".sgml")
3092 preamble += features.getIncludedFiles(name);
3093 preamble += features.getLyXSGMLEntities();
3095 if (!preamble.empty()) {
3096 ofs << "\n [ " << preamble << " ]";
3101 string top = top_element;
3103 top += params.language->code();
3106 if (!params.options.empty()) {
3108 top += params.options;
3110 sgmlOpenTag(ofs, 0, top);
3112 ofs << "<!-- DocBook file was created by " << lyx_docversion
3113 << "\n See http://www.lyx.org/ for more information -->\n";
3115 vector<string> environment_stack(10);
3116 vector<string> environment_inner(10);
3117 vector<string> command_stack(10);
3119 bool command_flag = false;
3120 Paragraph::depth_type command_depth = 0;
3121 Paragraph::depth_type command_base = 0;
3122 Paragraph::depth_type cmd_depth = 0;
3123 Paragraph::depth_type depth = 0; // paragraph depth
3126 string command_name;
3132 int desc_on = 0; // description mode
3134 LyXLayout const & style = tclass[par->layout()];
3136 // environment tag closing
3137 for (; depth > par->params().depth(); --depth) {
3138 if (environment_inner[depth] != "!-- --") {
3139 item_name = "listitem";
3140 sgmlCloseTag(ofs, command_depth + depth,
3142 if (environment_inner[depth] == "varlistentry")
3143 sgmlCloseTag(ofs, depth+command_depth,
3144 environment_inner[depth]);
3146 sgmlCloseTag(ofs, depth + command_depth,
3147 environment_stack[depth]);
3148 environment_stack[depth].erase();
3149 environment_inner[depth].erase();
3152 if (depth == par->params().depth()
3153 && environment_stack[depth] != style.latexname()
3154 && !environment_stack[depth].empty()) {
3155 if (environment_inner[depth] != "!-- --") {
3156 item_name= "listitem";
3157 sgmlCloseTag(ofs, command_depth+depth,
3159 if (environment_inner[depth] == "varlistentry")
3161 depth + command_depth,
3162 environment_inner[depth]);
3165 sgmlCloseTag(ofs, depth + command_depth,
3166 environment_stack[depth]);
3168 environment_stack[depth].erase();
3169 environment_inner[depth].erase();
3172 // Write opening SGML tags.
3173 switch (style.latextype) {
3174 case LATEX_PARAGRAPH:
3175 sgmlOpenTag(ofs, depth + command_depth,
3182 _("Error : Wrong depth for "
3183 "LatexType Command.\n"));
3185 command_name = style.latexname();
3187 sgmlparam = style.latexparam();
3188 c_params = split(sgmlparam, c_depth,'|');
3190 cmd_depth = lyx::atoi(c_depth);
3193 if (cmd_depth < command_base) {
3194 for (Paragraph::depth_type j = command_depth; j >= command_base; --j)
3195 sgmlCloseTag(ofs, j, command_stack[j]);
3196 command_depth = command_base = cmd_depth;
3197 } else if (cmd_depth <= command_depth) {
3198 for (int j = command_depth; j >= int(cmd_depth); --j)
3199 sgmlCloseTag(ofs, j, command_stack[j]);
3200 command_depth = cmd_depth;
3202 command_depth = cmd_depth;
3204 command_depth = command_base = cmd_depth;
3205 command_flag = true;
3207 if (command_stack.size() == command_depth + 1)
3208 command_stack.push_back(string());
3209 command_stack[command_depth] = command_name;
3211 // treat label as a special case for
3212 // more WYSIWYM handling.
3213 // This is a hack while paragraphs can't have
3214 // attributes, like id in this case.
3215 if (par->isInset(0)) {
3216 Inset * inset = par->getInset(0);
3217 Inset::Code lyx_code = inset->lyxCode();
3218 if (lyx_code == Inset::LABEL_CODE) {
3219 command_name += " id=\"";
3220 command_name += (static_cast<InsetCommand *>(inset))->getContents();
3221 command_name += "\"";
3226 sgmlOpenTag(ofs, depth + command_depth, command_name);
3227 if (c_params.empty())
3228 item_name = "title";
3230 item_name = c_params;
3231 sgmlOpenTag(ofs, depth + 1 + command_depth, item_name);
3234 case LATEX_ENVIRONMENT:
3235 case LATEX_ITEM_ENVIRONMENT:
3236 if (depth < par->params().depth()) {
3237 depth = par->params().depth();
3238 environment_stack[depth].erase();
3241 if (environment_stack[depth] != style.latexname()) {
3242 if (environment_stack.size() == depth + 1) {
3243 environment_stack.push_back("!-- --");
3244 environment_inner.push_back("!-- --");
3246 environment_stack[depth] = style.latexname();
3247 environment_inner[depth] = "!-- --";
3248 sgmlOpenTag(ofs, depth + command_depth,
3249 environment_stack[depth]);
3251 if (environment_inner[depth] != "!-- --") {
3252 item_name= "listitem";
3254 command_depth + depth,
3256 if (environment_inner[depth] == "varlistentry")
3258 depth + command_depth,
3259 environment_inner[depth]);
3263 if (style.latextype == LATEX_ENVIRONMENT) {
3264 if (!style.latexparam().empty()) {
3265 if (style.latexparam() == "CDATA")
3268 sgmlOpenTag(ofs, depth + command_depth,
3269 style.latexparam());
3274 desc_on = (style.labeltype == LABEL_MANUAL);
3277 environment_inner[depth]= "varlistentry";
3279 environment_inner[depth]= "listitem";
3281 sgmlOpenTag(ofs, depth + 1 + command_depth,
3282 environment_inner[depth]);
3286 sgmlOpenTag(ofs, depth + 1 + command_depth,
3290 sgmlOpenTag(ofs, depth + 1 + command_depth,
3295 sgmlOpenTag(ofs, depth + command_depth,
3300 simpleDocBookOnePar(ofs, par, desc_on, depth+1+command_depth);
3304 // write closing SGML tags
3305 switch (style.latextype) {
3307 if (c_params.empty())
3311 sgmlCloseTag(ofs, depth + command_depth, end_tag);
3313 case LATEX_ENVIRONMENT:
3314 if (!style.latexparam().empty()) {
3315 if (style.latexparam() == "CDATA")
3318 sgmlCloseTag(ofs, depth + command_depth,
3319 style.latexparam());
3322 case LATEX_ITEM_ENVIRONMENT:
3323 if (desc_on == 1) break;
3325 sgmlCloseTag(ofs, depth + 1 + command_depth, end_tag);
3327 case LATEX_PARAGRAPH:
3328 sgmlCloseTag(ofs, depth + command_depth, style.latexname());
3331 sgmlCloseTag(ofs, depth + command_depth, style.latexname());
3337 for (int d = depth; d >= 0; --d) {
3338 if (!environment_stack[depth].empty()) {
3339 if (environment_inner[depth] != "!-- --") {
3340 item_name = "listitem";
3341 sgmlCloseTag(ofs, command_depth + depth,
3343 if (environment_inner[depth] == "varlistentry")
3344 sgmlCloseTag(ofs, depth + command_depth,
3345 environment_inner[depth]);
3348 sgmlCloseTag(ofs, depth + command_depth,
3349 environment_stack[depth]);
3353 for (int j = command_depth; j >= 0 ; --j)
3354 if (!command_stack[j].empty())
3355 sgmlCloseTag(ofs, j, command_stack[j]);
3358 sgmlCloseTag(ofs, 0, top_element);
3361 // How to check for successful close
3365 void Buffer::simpleDocBookOnePar(ostream & os,
3366 Paragraph * par, int & desc_on,
3367 Paragraph::depth_type depth) const
3369 bool emph_flag = false;
3371 LyXLayout const & style =
3372 textclasslist[params.textclass][par->layout()];
3374 LyXFont font_old = style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
3376 int char_line_count = depth;
3377 //if (!style.free_spacing)
3378 // os << string(depth,' ');
3380 // parsing main loop
3381 for (pos_type i = 0; i < par->size(); ++i) {
3382 LyXFont font = par->getFont(params, i);
3384 // handle <emphasis> tag
3385 if (font_old.emph() != font.emph()) {
3386 if (font.emph() == LyXFont::ON) {
3390 os << "</emphasis>";
3396 if (par->isInset(i)) {
3397 Inset * inset = par->getInset(i);
3398 // don't print the inset in position 0 if desc_on == 3 (label)
3399 if ( i || desc_on != 3) {
3400 if(style.latexparam() == "CDATA")
3402 inset->docbook(this, os);
3403 if(style.latexparam() == "CDATA")
3407 char c = par->getChar(i);
3409 par->sgmlConvertChar(c, sgml_string);
3411 if (style.pass_thru) {
3413 } else if (style.free_spacing || par->isFreeSpacing() || c != ' ') {
3415 } else if (desc_on ==1) {
3417 os << "\n</term><listitem><para>";
3427 os << "</emphasis>";
3430 // resets description flag correctly
3432 // <term> not closed...
3435 if (style.free_spacing) os << '\n';
3439 // This should be enabled when the Chktex class is implemented. (Asger)
3440 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
3441 // Other flags: -wall -v0 -x
3442 int Buffer::runChktex()
3444 if (!users->text) return 0;
3446 users->owner()->prohibitInput();
3448 // get LaTeX-Filename
3449 string const name = getLatexName();
3450 string path = filePath();
3452 string const org_path = path;
3453 if (lyxrc.use_tempdir || !IsDirWriteable(path)) {
3457 Path p(path); // path to LaTeX file
3458 users->owner()->message(_("Running chktex..."));
3460 // Remove all error insets
3461 bool const removedErrorInsets = users->removeAutoInsets();
3463 // Generate the LaTeX file if neccessary
3464 makeLaTeXFile(name, org_path, false);
3467 Chktex chktex(lyxrc.chktex_command, name, filePath());
3468 int res = chktex.run(terr); // run chktex
3471 Alert::alert(_("chktex did not work!"),
3472 _("Could not run with file:"), name);
3473 } else if (res > 0) {
3474 // Insert all errors as errors boxes
3475 users->insertErrors(terr);
3478 // if we removed error insets before we ran chktex or if we inserted
3479 // error insets after we ran chktex, this must be run:
3480 if (removedErrorInsets || res) {
3484 users->owner()->allowInput();
3490 void Buffer::validate(LaTeXFeatures & features) const
3492 Paragraph * par = paragraph;
3493 LyXTextClass const & tclass = textclasslist[params.textclass];
3495 // AMS Style is at document level
3496 if (params.use_amsmath || tclass.provides(LyXTextClass::amsmath))
3497 features.require("amsmath");
3500 // We don't use "lyxerr.debug" because of speed. (Asger)
3501 if (lyxerr.debugging(Debug::LATEX))
3502 lyxerr << "Paragraph: " << par << endl;
3504 // Now just follow the list of paragraphs and run
3505 // validate on each of them.
3506 par->validate(features);
3508 // and then the next paragraph
3512 // the bullet shapes are buffer level not paragraph level
3513 // so they are tested here
3514 for (int i = 0; i < 4; ++i) {
3515 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
3516 int const font = params.user_defined_bullets[i].getFont();
3518 int const c = params
3519 .user_defined_bullets[i]
3526 features.require("latexsym");
3528 } else if (font == 1) {
3529 features.require("amssymb");
3530 } else if ((font >= 2 && font <= 5)) {
3531 features.require("pifont");
3536 if (lyxerr.debugging(Debug::LATEX)) {
3537 features.showStruct();
3542 // This function should be in Buffer because it's a buffer's property (ale)
3543 string const Buffer::getIncludeonlyList(char delim)
3546 for (inset_iterator it = inset_iterator_begin();
3547 it != inset_iterator_end(); ++it) {
3548 if ((*it)->lyxCode() == Inset::INCLUDE_CODE) {
3549 InsetInclude * insetinc =
3550 static_cast<InsetInclude *>(*it);
3551 if (insetinc->isIncludeOnly()) {
3554 lst += insetinc->getRelFileBaseName();
3558 lyxerr[Debug::INFO] << "Includeonly(" << lst << ')' << endl;
3563 vector<string> const Buffer::getLabelList()
3565 /// if this is a child document and the parent is already loaded
3566 /// Use the parent's list instead [ale990407]
3567 if (!params.parentname.empty()
3568 && bufferlist.exists(params.parentname)) {
3569 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3571 return tmp->getLabelList();
3574 vector<string> label_list;
3575 for (inset_iterator it = inset_iterator_begin();
3576 it != inset_iterator_end(); ++it) {
3577 vector<string> const l = (*it)->getLabelList();
3578 label_list.insert(label_list.end(), l.begin(), l.end());
3584 Buffer::Lists const Buffer::getLists() const
3587 Paragraph * par = paragraph;
3589 LyXTextClass const & textclass = textclasslist[params.textclass];
3590 bool found = textclass.hasLayout("caption");
3591 string const layout("caption");
3594 char const labeltype = textclass[par->layout()].labeltype;
3596 if (labeltype >= LABEL_COUNTER_CHAPTER
3597 && labeltype <= LABEL_COUNTER_CHAPTER + params.tocdepth) {
3598 // insert this into the table of contents
3599 SingleList & item = l["TOC"];
3602 textclass.maxcounter());
3603 item.push_back(TocItem(par, depth, par->asString(this, true)));
3605 // For each paragrph, traverse its insets and look for
3609 Paragraph::inset_iterator it =
3610 par->inset_iterator_begin();
3611 Paragraph::inset_iterator end =
3612 par->inset_iterator_end();
3614 for (; it != end; ++it) {
3615 if ((*it)->lyxCode() == Inset::FLOAT_CODE) {
3617 static_cast<InsetFloat*>(*it);
3619 string const type = il->type();
3621 // Now find the caption in the float...
3622 // We now tranverse the paragraphs of
3624 Paragraph * tmp = il->inset.paragraph();
3626 if (tmp->layout() == layout) {
3627 SingleList & item = l[type];
3629 tostr(item.size()+1) + ". " + tmp->asString(this, false);
3630 item.push_back(TocItem(tmp, 0 , str));
3637 lyxerr << "caption not found" << endl;
3646 // This is also a buffer property (ale)
3647 vector<pair<string, string> > const Buffer::getBibkeyList()
3649 /// if this is a child document and the parent is already loaded
3650 /// Use the parent's list instead [ale990412]
3651 if (!params.parentname.empty() && bufferlist.exists(params.parentname)) {
3652 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3654 return tmp->getBibkeyList();
3657 vector<pair<string, string> > keys;
3658 Paragraph * par = paragraph;
3661 keys.push_back(pair<string, string>(par->bibkey->getContents(),
3662 par->asString(this, false)));
3666 // Might be either using bibtex or a child has bibliography
3668 for (inset_iterator it = inset_iterator_begin();
3669 it != inset_iterator_end(); ++it) {
3670 // Search for Bibtex or Include inset
3671 if ((*it)->lyxCode() == Inset::BIBTEX_CODE) {
3672 vector<pair<string,string> > tmp =
3673 static_cast<InsetBibtex*>(*it)->getKeys(this);
3674 keys.insert(keys.end(), tmp.begin(), tmp.end());
3675 } else if ((*it)->lyxCode() == Inset::INCLUDE_CODE) {
3676 vector<pair<string,string> > const tmp =
3677 static_cast<InsetInclude*>(*it)->getKeys();
3678 keys.insert(keys.end(), tmp.begin(), tmp.end());
3687 bool Buffer::isDepClean(string const & name) const
3689 DEPCLEAN * item = dep_clean;
3690 while (item && item->master != name)
3692 if (!item) return true;
3697 void Buffer::markDepClean(string const & name)
3700 dep_clean = new DEPCLEAN;
3701 dep_clean->clean = true;
3702 dep_clean->master = name;
3703 dep_clean->next = 0;
3705 DEPCLEAN * item = dep_clean;
3706 while (item && item->master != name)
3711 item = new DEPCLEAN;
3713 item->master = name;
3720 bool Buffer::dispatch(string const & command)
3722 // Split command string into command and argument
3724 string line = frontStrip(command);
3725 string const arg = strip(frontStrip(split(line, cmd, ' ')));
3727 return dispatch(lyxaction.LookupFunc(cmd), arg);
3731 bool Buffer::dispatch(int action, string const & argument)
3733 bool dispatched = true;
3736 Exporter::Export(this, argument, false);
3746 void Buffer::resizeInsets(BufferView * bv)
3748 /// then remove all LyXText in text-insets
3749 Paragraph * par = paragraph;
3750 for (; par; par = par->next()) {
3751 par->resizeInsetsLyXText(bv);
3756 void Buffer::redraw()
3763 void Buffer::changeLanguage(Language const * from, Language const * to)
3766 ParIterator end = par_iterator_end();
3767 for (ParIterator it = par_iterator_begin(); it != end; ++it)
3768 (*it)->changeLanguage(params, from, to);
3772 bool Buffer::isMultiLingual()
3774 ParIterator end = par_iterator_end();
3775 for (ParIterator it = par_iterator_begin(); it != end; ++it)
3776 if ((*it)->isMultiLingual(params))
3783 Buffer::inset_iterator::inset_iterator(Paragraph * paragraph, pos_type pos)
3786 it = par->InsetIterator(pos);
3787 if (it == par->inset_iterator_end()) {
3794 void Buffer::inset_iterator::setParagraph()
3797 it = par->inset_iterator_begin();
3798 if (it != par->inset_iterator_end())
3803 // We maintain an invariant that whenever par = 0 then it = 0
3807 Inset * Buffer::getInsetFromID(int id_arg) const
3809 for (inset_iterator it = inset_const_iterator_begin();
3810 it != inset_const_iterator_end(); ++it)
3812 if ((*it)->id() == id_arg)
3814 Inset * in = (*it)->getInsetFromID(id_arg);
3822 Paragraph * Buffer::getParFromID(int id) const
3824 if (id < 0) return 0;
3825 Paragraph * par = paragraph;
3827 if (par->id() == id) {
3830 Paragraph * tmp = par->getParFromID(id);
3840 ParIterator Buffer::par_iterator_begin()
3842 return ParIterator(paragraph);
3846 ParIterator Buffer::par_iterator_end()
3848 return ParIterator();