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);
336 par->layout(textclasslist[params.textclass].defaultLayoutName());
338 // We are inserting into an existing document
339 users->text->breakParagraph(users);
340 first_par = users->text->ownerParagraph();
343 // We don't want to adopt the parameters from the
344 // document we insert, so we skip until the text begins:
347 string const pretoken = lex.getString();
348 if (pretoken == "\\layout") {
349 lex.pushToken(pretoken);
357 string const token = lex.getString();
359 if (token.empty()) continue;
361 lyxerr[Debug::PARSER] << "Handling token: `"
362 << token << "'" << endl;
365 parseSingleLyXformat2Token(lex, par, first_par,
373 paragraph = first_par;
375 if (unknown_layouts > 0) {
376 string s = _("Couldn't set the layout for ");
377 if (unknown_layouts == 1) {
378 s += _("one paragraph");
380 s += tostr(unknown_layouts);
381 s += _(" paragraphs");
383 Alert::alert(_("Textclass Loading Error!"), s,
384 _("When reading " + fileName()));
387 if (unknown_tokens > 0) {
388 string s = _("Encountered ");
389 if (unknown_tokens == 1) {
390 s += _("one unknown token");
392 s += tostr(unknown_tokens);
393 s += _(" unknown tokens");
395 Alert::alert(_("Textclass Loading Error!"), s,
396 _("When reading " + fileName()));
403 #ifndef NO_COMPABILITY
404 void Buffer::insertErtContents(Paragraph * par, int & pos, bool set_inactive)
406 if (!ert_comp.contents.empty()) {
407 lyxerr[Debug::INSETS] << "ERT contents:\n'"
408 << ert_comp.contents << "'" << endl;
409 Inset * inset = new InsetERT(params, params.language,
410 ert_comp.contents, true);
411 par->insertInset(pos++, inset, ert_comp.font);
412 ert_comp.contents.erase();
415 ert_comp.active = false;
422 Buffer::parseSingleLyXformat2Token(LyXLex & lex, Paragraph *& par,
423 Paragraph *& first_par,
424 string const & token, int & pos,
425 Paragraph::depth_type & depth,
429 bool the_end_read = false;
430 #ifndef NO_COMPABILITY
431 #ifndef NO_PEXTRA_REALLY
432 // This is super temporary but is needed to get the compability
433 // mode for minipages work correctly together with new tabulars.
434 static int call_depth;
436 bool checkminipage = false;
437 static Paragraph * minipar = 0;
438 static Paragraph * parBeforeMinipage;
441 if (token[0] != '\\') {
442 #ifndef NO_COMPABILITY
443 if (ert_comp.active) {
444 ert_comp.contents += token;
447 for (string::const_iterator cit = token.begin();
448 cit != token.end(); ++cit) {
449 par->insertChar(pos, (*cit), font);
452 #ifndef NO_COMPABILITY
455 } else if (token == "\\i") {
456 Inset * inset = new InsetLatexAccent;
457 inset->read(this, lex);
458 par->insertInset(pos, inset, font);
460 } else if (token == "\\layout") {
461 #ifndef NO_COMPABILITY
462 ert_comp.in_tabular = false;
464 insertErtContents(par, pos);
467 string layoutname = lex.getString();
469 LyXTextClass const & tclass = textclasslist[params.textclass];
471 if (layoutname.empty()) {
472 layoutname = tclass.defaultLayoutName();
475 bool hasLayout = tclass.hasLayout(layoutname);
477 lyxerr << "Layout '" << layoutname << "' does not"
478 << " exist in textclass '" << tclass.name()
480 lyxerr << "Trying to use default layout instead."
482 layoutname = tclass.defaultLayoutName();
485 #ifndef NO_COMPABILITY
486 if (compare_no_case(layoutname, "latex") == 0) {
487 ert_comp.active = true;
488 ert_comp.font = font;
492 // The is the compability reading of layout caption.
493 // It can be removed in LyX version 1.3.0. (Lgb)
494 if (compare_no_case(layoutname, "caption") == 0) {
495 // We expect that the par we are now working on is
496 // really inside a InsetText inside a InsetFloat.
497 // We also know that captions can only be
498 // one paragraph. (Lgb)
500 // We should now read until the next "\layout"
502 // This is probably not good enough, what if the
503 // caption is the last par in the document (Lgb)
504 istream & ist = lex.getStream();
510 if (prefixIs(line, "\\layout")) {
514 if (prefixIs(line, "\\begin_inset"))
516 if (prefixIs(line, "\\end_inset")) {
527 // Now we should have the whole layout in ss
528 // we should now be able to give this to the
530 ss << "\\end_inset\n";
532 // This seems like a bug in stringstream.
533 // We really should be able to use ss
535 istringstream is(ss.str());
537 tmplex.setStream(is);
538 Inset * inset = new InsetCaption;
539 inset->Read(this, tmplex);
540 par->InsertInset(pos, inset, font);
547 par = new Paragraph(par);
548 par->layout(textclasslist[params.textclass].defaultLayoutName());
551 par->layout(layoutname);
552 // Test whether the layout is obsolete.
553 LyXLayout const & layout =
554 textclasslist[params.textclass][par->layout()];
555 if (!layout.obsoleted_by().empty())
556 par->layout(layout.obsoleted_by());
557 par->params().depth(depth);
558 font = LyXFont(LyXFont::ALL_INHERIT, params.language);
559 if (file_format < 216
560 && params.language->lang() == "hebrew")
561 font.setLanguage(default_language);
566 #ifndef NO_COMPABILITY
567 } else if (token == "\\begin_float") {
568 insertErtContents(par, pos);
569 //insertErtContents(par, pos, false);
570 //ert_stack.push(ert_comp);
571 //ert_comp = ErtComp();
573 // This is the compability reader. It can be removed in
574 // LyX version 1.3.0. (Lgb)
576 string const tmptok = lex.getString();
577 //lyxerr << "old float: " << tmptok << endl;
580 stringstream old_float;
582 if (tmptok == "footnote") {
583 inset = new InsetFoot(params);
584 old_float << "collapsed true\n";
585 } else if (tmptok == "margin") {
586 inset = new InsetMarginal(params);
587 old_float << "collapsed true\n";
588 } else if (tmptok == "fig") {
589 inset = new InsetFloat(params, "figure");
590 old_float << "placement htbp\n"
592 << "collapsed false\n";
593 } else if (tmptok == "tab") {
594 inset = new InsetFloat(params, "table");
595 old_float << "placement htbp\n"
597 << "collapsed false\n";
598 } else if (tmptok == "alg") {
599 inset = new InsetFloat(params, "algorithm");
600 old_float << "placement htbp\n"
602 << "collapsed false\n";
603 } else if (tmptok == "wide-fig") {
604 inset = new InsetFloat(params, "figure");
605 //InsetFloat * tmp = new InsetFloat("figure");
608 old_float << "placement htbp\n"
610 << "collapsed false\n";
611 } else if (tmptok == "wide-tab") {
612 inset = new InsetFloat(params, "table");
613 //InsetFloat * tmp = new InsetFloat("table");
616 old_float << "placement htbp\n"
618 << "collapsed false\n";
622 #ifndef NO_PEXTRA_REALLY
625 return false; // no end read yet
628 // Here we need to check for \end_deeper and handle that
629 // before we do the footnote parsing.
630 // This _is_ a hack! (Lgb)
633 string const tmp = lex.getString();
634 if (tmp == "\\end_deeper") {
635 //lyxerr << "\\end_deeper caught!" << endl;
637 lex.printError("\\end_deeper: "
638 "depth is already null");
643 old_float << tmp << ' ';
648 old_float << lex.getLongString("\\end_float")
649 << "\n\\end_inset\n";
650 //lyxerr << "Float Body:\n" << old_float.str() << endl;
651 // That this does not work seems like a bug
652 // in stringstream. (Lgb)
653 istringstream istr(old_float.str());
655 nylex.setStream(istr);
656 inset->read(this, nylex);
657 par->insertInset(pos, inset, font);
659 insertErtContents(par, pos);
661 } else if (token == "\\begin_deeper") {
663 } else if (token == "\\end_deeper") {
665 lex.printError("\\end_deeper: "
666 "depth is already null");
670 } else if (token == "\\begin_preamble") {
671 params.readPreamble(lex);
672 } else if (token == "\\textclass") {
674 pair<bool, textclass_type> pp =
675 textclasslist.NumberOfClass(lex.getString());
677 params.textclass = pp.second;
679 Alert::alert(string(_("Textclass error")),
680 string(_("The document uses an unknown textclass \"")) +
681 lex.getString() + string("\"."),
682 string(_("LyX will not be able to produce output correctly.")));
683 params.textclass = 0;
685 if (!textclasslist[params.textclass].load()) {
686 // if the textclass wasn't loaded properly
687 // we need to either substitute another
688 // or stop loading the file.
689 // I can substitute but I don't see how I can
690 // stop loading... ideas?? ARRae980418
691 Alert::alert(_("Textclass Loading Error!"),
692 string(_("Can't load textclass ")) +
693 textclasslist[params.textclass].name(),
694 _("-- substituting default"));
695 params.textclass = 0;
697 } else if (token == "\\options") {
699 params.options = lex.getString();
700 } else if (token == "\\language") {
701 params.readLanguage(lex);
702 } else if (token == "\\fontencoding") {
704 } else if (token == "\\inputencoding") {
706 params.inputenc = lex.getString();
707 } else if (token == "\\graphics") {
708 params.readGraphicsDriver(lex);
709 } else if (token == "\\fontscheme") {
711 params.fonts = lex.getString();
712 } else if (token == "\\noindent") {
713 par->params().noindent(true);
714 } else if (token == "\\fill_top") {
715 par->params().spaceTop(VSpace(VSpace::VFILL));
716 } else if (token == "\\fill_bottom") {
717 par->params().spaceBottom(VSpace(VSpace::VFILL));
718 } else if (token == "\\line_top") {
719 par->params().lineTop(true);
720 } else if (token == "\\line_bottom") {
721 par->params().lineBottom(true);
722 } else if (token == "\\pagebreak_top") {
723 par->params().pagebreakTop(true);
724 } else if (token == "\\pagebreak_bottom") {
725 par->params().pagebreakBottom(true);
726 } else if (token == "\\start_of_appendix") {
727 par->params().startOfAppendix(true);
728 } else if (token == "\\paragraph_separation") {
729 int tmpret = lex.findToken(string_paragraph_separation);
732 if (tmpret != LYX_LAYOUT_DEFAULT)
733 params.paragraph_separation =
734 static_cast<BufferParams::PARSEP>(tmpret);
735 } else if (token == "\\defskip") {
737 params.defskip = VSpace(lex.getString());
738 #ifndef NO_COMPABILITY
739 } else if (token == "\\epsfig") { // obsolete
740 // Indeed it is obsolete, but we HAVE to be backwards
741 // compatible until 0.14, because otherwise all figures
742 // in existing documents are irretrivably lost. (Asger)
743 params.readGraphicsDriver(lex);
745 } else if (token == "\\quotes_language") {
746 int tmpret = lex.findToken(string_quotes_language);
749 if (tmpret != LYX_LAYOUT_DEFAULT) {
750 InsetQuotes::quote_language tmpl =
751 InsetQuotes::EnglishQ;
754 tmpl = InsetQuotes::EnglishQ;
757 tmpl = InsetQuotes::SwedishQ;
760 tmpl = InsetQuotes::GermanQ;
763 tmpl = InsetQuotes::PolishQ;
766 tmpl = InsetQuotes::FrenchQ;
769 tmpl = InsetQuotes::DanishQ;
772 params.quotes_language = tmpl;
774 } else if (token == "\\quotes_times") {
776 switch (lex.getInteger()) {
778 params.quotes_times = InsetQuotes::SingleQ;
781 params.quotes_times = InsetQuotes::DoubleQ;
784 } else if (token == "\\papersize") {
785 int tmpret = lex.findToken(string_papersize);
789 params.papersize2 = tmpret;
790 } else if (token == "\\paperpackage") {
791 int tmpret = lex.findToken(string_paperpackages);
794 params.paperpackage = BufferParams::PACKAGE_NONE;
796 params.paperpackage = tmpret;
797 } else if (token == "\\use_geometry") {
799 params.use_geometry = lex.getInteger();
800 } else if (token == "\\use_amsmath") {
802 params.use_amsmath = lex.getInteger();
803 } else if (token == "\\use_natbib") {
805 params.use_natbib = lex.getInteger();
806 } else if (token == "\\use_numerical_citations") {
808 params.use_numerical_citations = lex.getInteger();
809 } else if (token == "\\paperorientation") {
810 int tmpret = lex.findToken(string_orientation);
813 if (tmpret != LYX_LAYOUT_DEFAULT)
814 params.orientation = static_cast<BufferParams::PAPER_ORIENTATION>(tmpret);
815 } else if (token == "\\paperwidth") {
817 params.paperwidth = lex.getString();
818 } else if (token == "\\paperheight") {
820 params.paperheight = lex.getString();
821 } else if (token == "\\leftmargin") {
823 params.leftmargin = lex.getString();
824 } else if (token == "\\topmargin") {
826 params.topmargin = lex.getString();
827 } else if (token == "\\rightmargin") {
829 params.rightmargin = lex.getString();
830 } else if (token == "\\bottommargin") {
832 params.bottommargin = lex.getString();
833 } else if (token == "\\headheight") {
835 params.headheight = lex.getString();
836 } else if (token == "\\headsep") {
838 params.headsep = lex.getString();
839 } else if (token == "\\footskip") {
841 params.footskip = lex.getString();
842 } else if (token == "\\paperfontsize") {
844 params.fontsize = strip(lex.getString());
845 } else if (token == "\\papercolumns") {
847 params.columns = lex.getInteger();
848 } else if (token == "\\papersides") {
850 switch (lex.getInteger()) {
852 case 1: params.sides = LyXTextClass::OneSide; break;
853 case 2: params.sides = LyXTextClass::TwoSides; break;
855 } else if (token == "\\paperpagestyle") {
857 params.pagestyle = strip(lex.getString());
858 } else if (token == "\\bullet") {
860 int const index = lex.getInteger();
862 int temp_int = lex.getInteger();
863 params.user_defined_bullets[index].setFont(temp_int);
864 params.temp_bullets[index].setFont(temp_int);
866 temp_int = lex.getInteger();
867 params.user_defined_bullets[index].setCharacter(temp_int);
868 params.temp_bullets[index].setCharacter(temp_int);
870 temp_int = lex.getInteger();
871 params.user_defined_bullets[index].setSize(temp_int);
872 params.temp_bullets[index].setSize(temp_int);
874 string const temp_str = lex.getString();
875 if (temp_str != "\\end_bullet") {
876 // this element isn't really necessary for
877 // parsing but is easier for humans
878 // to understand bullets. Put it back and
879 // set a debug message?
880 lex.printError("\\end_bullet expected, got" + temp_str);
881 //how can I put it back?
883 } else if (token == "\\bulletLaTeX") {
884 // The bullet class should be able to read this.
886 int const index = lex.getInteger();
888 string temp_str = lex.getString();
890 while (temp_str != "\\end_bullet") {
891 // this loop structure is needed when user
892 // enters an empty string since the first
893 // thing returned will be the \\end_bullet
895 // if the LaTeX entry has spaces. Each element
896 // therefore needs to be read in turn
899 temp_str = lex.getString();
902 params.user_defined_bullets[index].setText(sum_str);
903 params.temp_bullets[index].setText(sum_str);
904 } else if (token == "\\secnumdepth") {
906 params.secnumdepth = lex.getInteger();
907 } else if (token == "\\tocdepth") {
909 params.tocdepth = lex.getInteger();
910 } else if (token == "\\spacing") {
912 string const tmp = strip(lex.getString());
913 Spacing::Space tmp_space = Spacing::Default;
915 if (tmp == "single") {
916 tmp_space = Spacing::Single;
917 } else if (tmp == "onehalf") {
918 tmp_space = Spacing::Onehalf;
919 } else if (tmp == "double") {
920 tmp_space = Spacing::Double;
921 } else if (tmp == "other") {
923 tmp_space = Spacing::Other;
924 tmp_val = lex.getFloat();
926 lex.printError("Unknown spacing token: '$$Token'");
928 // Small hack so that files written with klyx will be
931 par->params().spacing(Spacing(tmp_space, tmp_val));
933 params.spacing.set(tmp_space, tmp_val);
935 } else if (token == "\\paragraph_spacing") {
937 string const tmp = strip(lex.getString());
938 if (tmp == "single") {
939 par->params().spacing(Spacing(Spacing::Single));
940 } else if (tmp == "onehalf") {
941 par->params().spacing(Spacing(Spacing::Onehalf));
942 } else if (tmp == "double") {
943 par->params().spacing(Spacing(Spacing::Double));
944 } else if (tmp == "other") {
946 par->params().spacing(Spacing(Spacing::Other,
949 lex.printError("Unknown spacing token: '$$Token'");
951 } else if (token == "\\float_placement") {
953 params.float_placement = lex.getString();
954 } else if (token == "\\family") {
956 font.setLyXFamily(lex.getString());
957 } else if (token == "\\series") {
959 font.setLyXSeries(lex.getString());
960 } else if (token == "\\shape") {
962 font.setLyXShape(lex.getString());
963 } else if (token == "\\size") {
965 font.setLyXSize(lex.getString());
966 #ifndef NO_COMPABILITY
967 } else if (token == "\\latex") {
969 string const tok = lex.getString();
970 if (tok == "no_latex") {
972 insertErtContents(par, pos);
973 } else if (tok == "latex") {
974 ert_comp.active = true;
975 ert_comp.font = font;
976 } else if (tok == "default") {
978 insertErtContents(par, pos);
980 lex.printError("Unknown LaTeX font flag "
984 } else if (token == "\\lang") {
986 string const tok = lex.getString();
987 Language const * lang = languages.getLanguage(tok);
989 font.setLanguage(lang);
991 font.setLanguage(params.language);
992 lex.printError("Unknown language `$$Token'");
994 } else if (token == "\\numeric") {
996 font.setNumber(font.setLyXMisc(lex.getString()));
997 } else if (token == "\\emph") {
999 font.setEmph(font.setLyXMisc(lex.getString()));
1000 } else if (token == "\\bar") {
1002 string const tok = lex.getString();
1003 // This is dirty, but gone with LyX3. (Asger)
1005 font.setUnderbar(LyXFont::ON);
1006 else if (tok == "no")
1007 font.setUnderbar(LyXFont::OFF);
1008 else if (tok == "default")
1009 font.setUnderbar(LyXFont::INHERIT);
1011 lex.printError("Unknown bar font flag "
1013 } else if (token == "\\noun") {
1015 font.setNoun(font.setLyXMisc(lex.getString()));
1016 } else if (token == "\\color") {
1018 font.setLyXColor(lex.getString());
1019 } else if (token == "\\align") {
1020 int tmpret = lex.findToken(string_align);
1021 if (tmpret == -1) ++tmpret;
1022 if (tmpret != LYX_LAYOUT_DEFAULT) { // tmpret != 99 ???
1023 int const tmpret2 = int(pow(2.0, tmpret));
1024 //lyxerr << "Tmpret2 = " << tmpret2 << endl;
1025 par->params().align(LyXAlignment(tmpret2));
1027 } else if (token == "\\added_space_top") {
1029 VSpace value = VSpace(lex.getString());
1030 if ((value.length().len().value() != 0) ||
1031 (value.kind() != VSpace::LENGTH))
1032 par->params().spaceTop(value);
1033 } else if (token == "\\added_space_bottom") {
1035 VSpace value = VSpace(lex.getString());
1036 if ((value.length().len().value() != 0) ||
1037 (value.kind() != VSpace::LENGTH))
1038 par->params().spaceBottom(value);
1039 #ifndef NO_COMPABILITY
1040 #ifndef NO_PEXTRA_REALLY
1041 } else if (token == "\\pextra_type") {
1043 par->params().pextraType(lex.getInteger());
1044 } else if (token == "\\pextra_width") {
1046 par->params().pextraWidth(lex.getString());
1047 } else if (token == "\\pextra_widthp") {
1049 par->params().pextraWidthp(lex.getString());
1050 } else if (token == "\\pextra_alignment") {
1052 par->params().pextraAlignment(lex.getInteger());
1053 } else if (token == "\\pextra_hfill") {
1055 par->params().pextraHfill(lex.getInteger());
1056 } else if (token == "\\pextra_start_minipage") {
1058 par->params().pextraStartMinipage(lex.getInteger());
1061 } else if (token == "\\labelwidthstring") {
1063 par->params().labelWidthString(lex.getString());
1064 // do not delete this token, it is still needed!
1065 } else if (token == "\\end_inset") {
1066 lyxerr << "Solitary \\end_inset. Missing \\begin_inset?.\n"
1067 << "Last inset read was: " << last_inset_read
1069 // Simply ignore this. The insets do not have
1071 // But insets should read it, it is a part of
1072 // the inset isn't it? Lgb.
1073 } else if (token == "\\begin_inset") {
1074 #ifndef NO_COMPABILITY
1075 insertErtContents(par, pos, false);
1076 ert_stack.push(ert_comp);
1077 ert_comp = ErtComp();
1079 readInset(lex, par, pos, font);
1080 #ifndef NO_COMPABILITY
1081 ert_comp = ert_stack.top();
1083 insertErtContents(par, pos);
1085 } else if (token == "\\SpecialChar") {
1086 LyXLayout const & layout =
1087 textclasslist[params.textclass][par->layout()];
1089 // Insets don't make sense in a free-spacing context! ---Kayvan
1090 if (layout.free_spacing || par->isFreeSpacing()) {
1093 string next_token = lex.getString();
1094 if (next_token == "\\-") {
1095 par->insertChar(pos, '-', font);
1096 } else if (next_token == "\\protected_separator"
1097 || next_token == "~") {
1098 par->insertChar(pos, ' ', font);
1100 lex.printError("Token `$$Token' "
1102 "paragraph layout!");
1107 Inset * inset = new InsetSpecialChar;
1108 inset->read(this, lex);
1109 par->insertInset(pos, inset, font);
1112 } else if (token == "\\newline") {
1113 #ifndef NO_COMPABILITY
1114 if (!ert_comp.in_tabular && ert_comp.active) {
1115 ert_comp.contents += char(Paragraph::META_NEWLINE);
1117 // Since we cannot know it this is only a regular
1118 // newline or a tabular cell delimter we have to
1119 // handle the ERT here.
1120 insertErtContents(par, pos, false);
1122 par->insertChar(pos, Paragraph::META_NEWLINE, font);
1126 par->insertChar(pos, Paragraph::META_NEWLINE, font);
1129 } else if (token == "\\LyXTable") {
1130 #ifndef NO_COMPABILITY
1131 ert_comp.in_tabular = true;
1133 Inset * inset = new InsetTabular(*this);
1134 inset->read(this, lex);
1135 par->insertInset(pos, inset, font);
1137 } else if (token == "\\hfill") {
1138 par->insertChar(pos, Paragraph::META_HFILL, font);
1140 } else if (token == "\\protected_separator") { // obsolete
1141 // This is a backward compability thingie. (Lgb)
1142 // Remove it later some time...introduced with fileformat
1144 LyXLayout const & layout =
1145 textclasslist[params.textclass][par->layout()];
1147 if (layout.free_spacing || par->isFreeSpacing()) {
1148 par->insertChar(pos, ' ', font);
1150 Inset * inset = new InsetSpecialChar(InsetSpecialChar::PROTECTED_SEPARATOR);
1151 par->insertInset(pos, inset, font);
1154 } else if (token == "\\bibitem") { // ale970302
1156 InsetCommandParams p("bibitem", "dummy");
1157 par->bibkey = new InsetBibKey(p);
1159 par->bibkey->read(this, lex);
1160 } else if (token == "\\backslash") {
1161 #ifndef NO_COMPABILITY
1162 if (ert_comp.active) {
1163 ert_comp.contents += "\\";
1166 par->insertChar(pos, '\\', font);
1168 #ifndef NO_COMPABILITY
1171 } else if (token == "\\the_end") {
1172 #ifndef NO_COMPABILITY
1173 // If we still have some ert active here we have to insert
1174 // it so we don't loose it. (Lgb)
1175 insertErtContents(par, pos);
1177 the_end_read = true;
1178 #ifndef NO_COMPABILITY
1179 #ifndef NO_PEXTRA_REALLY
1182 minipar = parBeforeMinipage = 0;
1186 #ifndef NO_COMPABILITY
1187 if (ert_comp.active) {
1188 ert_comp.contents += token;
1191 // This should be insurance for the future: (Asger)
1194 string const s = _("Unknown token: ") + token
1195 + " " + lex.text() + "\n";
1197 InsetError * new_inset = new InsetError(s);
1198 par->insertInset(pos, new_inset, LyXFont(LyXFont::ALL_INHERIT,
1201 #ifndef NO_COMPABILITY
1206 #ifndef NO_COMPABILITY
1207 #ifndef NO_PEXTRA_REALLY
1208 // I wonder if we could use this blanket fix for all the
1209 // checkminipage cases...
1210 // don't forget about ert paragraphs and compatibility read for'em
1211 if (par && (par->size() || !ert_comp.contents.empty())) {
1212 // It is possible that this will check to often,
1213 // but that should not be an correctness issue.
1214 // Only a speed issue.
1215 checkminipage = true;
1218 // now check if we have a minipage paragraph as at this
1219 // point we already read all the necessary data!
1220 // this cannot be done in layout because there we did
1221 // not read yet the paragraph PEXTRA-params (Jug)
1223 // BEGIN pextra_minipage compability
1224 // This should be removed in 1.3.x (Lgb)
1225 // I don't think we should remove this so fast (Jug)
1227 // This compability code is not perfect. In a couple
1228 // of rand cases it fails. When the minipage par is
1229 // the first par in the document, and when there are
1230 // none or only one regular paragraphs after the
1231 // minipage. Currently I am not investing any effort
1232 // in fixing those cases.
1234 //lyxerr << "Call depth: " << call_depth << endl;
1235 if (checkminipage && (call_depth == 1)) {
1236 checkminipage = false;
1237 if (minipar && (minipar != par) &&
1238 (par->params().pextraType() == Paragraph::PEXTRA_MINIPAGE))
1240 lyxerr << "minipages in a row" << endl;
1241 if (par->params().pextraStartMinipage()) {
1242 lyxerr << "start new minipage" << endl;
1243 // minipages in a row
1244 par->previous()->next(0);
1247 Paragraph * tmp = minipar;
1249 tmp->params().pextraType(0);
1250 tmp->params().pextraWidth(string());
1251 tmp->params().pextraWidthp(string());
1252 tmp->params().pextraAlignment(0);
1253 tmp->params().pextraHfill(false);
1254 tmp->params().pextraStartMinipage(false);
1257 // create a new paragraph to insert the
1258 // minipages in the following case
1259 if (par->params().pextraStartMinipage() &&
1260 !par->params().pextraHfill()) {
1261 Paragraph * p = new Paragraph;
1262 p->layout(textclasslist[params.textclass].defaultLayoutName());
1264 p->previous(parBeforeMinipage);
1265 parBeforeMinipage->next(p);
1267 p->params().depth(parBeforeMinipage->params().depth());
1268 parBeforeMinipage = p;
1270 InsetMinipage * mini = new InsetMinipage(params);
1271 mini->pos(static_cast<InsetMinipage::Position>(par->params().pextraAlignment()));
1272 mini->pageWidth(LyXLength(par->params().pextraWidth()));
1273 if (!par->params().pextraWidthp().empty()) {
1274 lyxerr << "WP:" << mini->pageWidth().asString() << endl;
1275 mini->pageWidth(LyXLength((par->params().pextraWidthp())+"p%"));
1277 Paragraph * op = mini->firstParagraph();
1278 mini->inset.paragraph(par);
1280 // and free the old ones!
1283 Paragraph * pp = op->next();
1287 // Insert the minipage last in the
1288 // previous paragraph.
1289 if (par->params().pextraHfill()) {
1290 parBeforeMinipage->insertChar
1291 (parBeforeMinipage->size(), Paragraph::META_HFILL);
1293 parBeforeMinipage->insertInset
1294 (parBeforeMinipage->size(), mini);
1298 lyxerr << "new minipage par" << endl;
1299 //nothing to do just continue reading
1302 } else if (minipar && (minipar != par)) {
1303 lyxerr << "last minipage par read" << endl;
1304 // The last paragraph read was not part of a
1305 // minipage but the par linked list is...
1306 // So we need to remove the last par from the
1308 if (par->previous())
1309 par->previous()->next(0);
1310 par->previous(parBeforeMinipage);
1311 parBeforeMinipage->next(par);
1312 Paragraph * tmp = minipar;
1314 tmp->params().pextraType(0);
1315 tmp->params().pextraWidth(string());
1316 tmp->params().pextraWidthp(string());
1317 tmp->params().pextraAlignment(0);
1318 tmp->params().pextraHfill(false);
1319 tmp->params().pextraStartMinipage(false);
1322 depth = parBeforeMinipage->params().depth();
1323 // and set this depth on the par as it has not been set already
1324 par->params().depth(depth);
1325 minipar = parBeforeMinipage = 0;
1326 } else if (!minipar &&
1327 (par->params().pextraType() == Paragraph::PEXTRA_MINIPAGE))
1329 // par is the first paragraph in a minipage
1330 lyxerr << "begin minipage" << endl;
1331 // To minimize problems for
1332 // the users we will insert
1333 // the first minipage in
1334 // a sequence of minipages
1335 // in its own paragraph.
1336 Paragraph * p = new Paragraph;
1337 p->layout(textclasslist[params.textclass].defaultLayoutName());
1338 p->previous(par->previous());
1340 p->params().depth(depth);
1341 par->params().depth(0);
1343 if (par->previous())
1344 par->previous()->next(p);
1346 parBeforeMinipage = p;
1348 if (!first_par || (first_par == par))
1351 InsetMinipage * mini = new InsetMinipage(params);
1352 mini->pos(static_cast<InsetMinipage::Position>(minipar->params().pextraAlignment()));
1353 mini->pageWidth(LyXLength(minipar->params().pextraWidth()));
1354 if (!par->params().pextraWidthp().empty()) {
1355 lyxerr << "WP:" << mini->pageWidth().asString() << endl;
1356 mini->pageWidth(LyXLength((par->params().pextraWidthp())+"p%"));
1359 Paragraph * op = mini->firstParagraph();
1360 mini->inset.paragraph(minipar);
1362 // and free the old ones!
1365 Paragraph * pp = op->next();
1370 // Insert the minipage last in the
1371 // previous paragraph.
1372 if (minipar->params().pextraHfill()) {
1373 parBeforeMinipage->insertChar
1374 (parBeforeMinipage->size(),Paragraph::META_HFILL);
1376 parBeforeMinipage->insertInset
1377 (parBeforeMinipage->size(), mini);
1380 // End of pextra_minipage compability
1384 return the_end_read;
1387 // needed to insert the selection
1388 void Buffer::insertStringAsLines(Paragraph *& par, pos_type & pos,
1389 LyXFont const & fn,string const & str) const
1391 LyXLayout const & layout =
1392 textclasslist[params.textclass][par->layout()];
1395 par->checkInsertChar(font);
1396 // insert the string, don't insert doublespace
1397 bool space_inserted = true;
1398 for(string::const_iterator cit = str.begin();
1399 cit != str.end(); ++cit) {
1401 if (par->size() || layout.keepempty) {
1402 par->breakParagraph(params, pos,
1403 layout.isEnvironment());
1406 space_inserted = true;
1410 // do not insert consecutive spaces if !free_spacing
1411 } else if ((*cit == ' ' || *cit == '\t') &&
1412 space_inserted && !layout.free_spacing &&
1413 !par->isFreeSpacing())
1416 } else if (*cit == '\t') {
1417 if (!layout.free_spacing && !par->isFreeSpacing()) {
1418 // tabs are like spaces here
1419 par->insertChar(pos, ' ', font);
1421 space_inserted = true;
1423 const pos_type nb = 8 - pos % 8;
1424 for (pos_type a = 0; a < nb ; ++a) {
1425 par->insertChar(pos, ' ', font);
1428 space_inserted = true;
1430 } else if (!IsPrintable(*cit)) {
1431 // Ignore unprintables
1434 // just insert the character
1435 par->insertChar(pos, *cit, font);
1437 space_inserted = (*cit == ' ');
1444 void Buffer::readInset(LyXLex & lex, Paragraph *& par,
1445 int & pos, LyXFont & font)
1447 // consistency check
1448 if (lex.getString() != "\\begin_inset") {
1449 lyxerr << "Buffer::readInset: Consistency check failed."
1456 string const tmptok = lex.getString();
1457 last_inset_read = tmptok;
1459 // test the different insets
1460 if (tmptok == "LatexCommand") {
1461 InsetCommandParams inscmd;
1464 string const cmdName = inscmd.getCmdName();
1466 // This strange command allows LyX to recognize "natbib" style
1467 // citations: citet, citep, Citet etc.
1468 if (compare_no_case(cmdName, "cite", 4) == 0) {
1469 inset = new InsetCitation(inscmd);
1470 } else if (cmdName == "bibitem") {
1471 lex.printError("Wrong place for bibitem");
1472 inset = new InsetBibKey(inscmd);
1473 } else if (cmdName == "BibTeX") {
1474 inset = new InsetBibtex(inscmd);
1475 } else if (cmdName == "index") {
1476 inset = new InsetIndex(inscmd);
1477 } else if (cmdName == "include") {
1478 inset = new InsetInclude(inscmd, *this);
1479 } else if (cmdName == "label") {
1480 inset = new InsetLabel(inscmd);
1481 } else if (cmdName == "url"
1482 || cmdName == "htmlurl") {
1483 inset = new InsetUrl(inscmd);
1484 } else if (cmdName == "ref"
1485 || cmdName == "pageref"
1486 || cmdName == "vref"
1487 || cmdName == "vpageref"
1488 || cmdName == "prettyref") {
1489 if (!inscmd.getOptions().empty()
1490 || !inscmd.getContents().empty()) {
1491 inset = new InsetRef(inscmd, *this);
1493 } else if (cmdName == "tableofcontents") {
1494 inset = new InsetTOC(inscmd);
1495 } else if (cmdName == "listofalgorithms") {
1496 inset = new InsetFloatList("algorithm");
1497 } else if (cmdName == "listoffigures") {
1498 inset = new InsetFloatList("figure");
1499 } else if (cmdName == "listoftables") {
1500 inset = new InsetFloatList("table");
1501 } else if (cmdName == "printindex") {
1502 inset = new InsetPrintIndex(inscmd);
1503 } else if (cmdName == "lyxparent") {
1504 inset = new InsetParent(inscmd, *this);
1507 bool alreadyread = false;
1508 if (tmptok == "Quotes") {
1509 inset = new InsetQuotes;
1510 } else if (tmptok == "External") {
1511 inset = new InsetExternal;
1512 } else if (tmptok == "FormulaMacro") {
1513 inset = new InsetFormulaMacro;
1514 } else if (tmptok == "Formula") {
1515 inset = new InsetFormula;
1516 } else if (tmptok == "Figure") { // Backward compatibility
1517 // inset = new InsetFig(100, 100, *this);
1518 inset = new InsetGraphics;
1519 } else if (tmptok == "Graphics") {
1520 inset = new InsetGraphics;
1521 } else if (tmptok == "Info") {// backwards compatibility
1522 inset = new InsetNote(this,
1523 lex.getLongString("\\end_inset"),
1526 } else if (tmptok == "Note") {
1527 inset = new InsetNote(params);
1528 } else if (tmptok == "Include") {
1529 InsetCommandParams p("Include");
1530 inset = new InsetInclude(p, *this);
1531 } else if (tmptok == "ERT") {
1532 inset = new InsetERT(params);
1533 } else if (tmptok == "Tabular") {
1534 inset = new InsetTabular(*this);
1535 } else if (tmptok == "Text") {
1536 inset = new InsetText(params);
1537 } else if (tmptok == "Foot") {
1538 inset = new InsetFoot(params);
1539 } else if (tmptok == "Marginal") {
1540 inset = new InsetMarginal(params);
1541 } else if (tmptok == "Minipage") {
1542 inset = new InsetMinipage(params);
1543 } else if (tmptok == "Float") {
1545 string tmptok = lex.getString();
1546 inset = new InsetFloat(params, tmptok);
1548 } else if (tmptok == "List") {
1549 inset = new InsetList;
1550 } else if (tmptok == "Theorem") {
1551 inset = new InsetList;
1553 } else if (tmptok == "Caption") {
1554 inset = new InsetCaption(params);
1555 } else if (tmptok == "FloatList") {
1556 inset = new InsetFloatList;
1559 if (inset && !alreadyread) inset->read(this, lex);
1563 par->insertInset(pos, inset, font);
1569 bool Buffer::readFile(LyXLex & lex, Paragraph * par)
1573 string const token(lex.getString());
1574 if (token == "\\lyxformat") { // the first token _must_ be...
1576 string tmp_format = lex.getString();
1577 //lyxerr << "LyX Format: `" << tmp_format << "'" << endl;
1578 // if present remove ".," from string.
1579 string::size_type dot = tmp_format.find_first_of(".,");
1580 //lyxerr << " dot found at " << dot << endl;
1581 if (dot != string::npos)
1582 tmp_format.erase(dot, 1);
1583 file_format = strToInt(tmp_format);
1584 if (file_format == LYX_FORMAT) {
1586 } else if (file_format > LYX_FORMAT) {
1588 Alert::alert(_("Warning!"),
1589 _("LyX file format is newer that what"),
1590 _("is supported in this LyX version. Expect some problems."));
1592 } else if (file_format < LYX_FORMAT) {
1594 if (file_format < 200) {
1595 Alert::alert(_("ERROR!"),
1596 _("Old LyX file format found. "
1597 "Use LyX 0.10.x to read this!"));
1601 bool the_end = readLyXformat2(lex, par);
1602 params.setPaperStuff();
1603 // the_end was added in 213
1604 if (file_format < 213)
1608 Alert::alert(_("Warning!"),
1609 _("Reading of document is not complete"),
1610 _("Maybe the document is truncated"));
1613 } else { // "\\lyxformat" not found
1614 Alert::alert(_("ERROR!"), _("Not a LyX file!"));
1617 Alert::alert(_("ERROR!"), _("Unable to read file!"));
1622 // Should probably be moved to somewhere else: BufferView? LyXView?
1623 bool Buffer::save() const
1625 // We don't need autosaves in the immediate future. (Asger)
1626 resetAutosaveTimers();
1630 if (lyxrc.make_backup) {
1631 s = fileName() + '~';
1632 if (!lyxrc.backupdir_path.empty())
1633 s = AddName(lyxrc.backupdir_path,
1634 subst(os::slashify_path(s),'/','!'));
1636 // Rename is the wrong way of making a backup,
1637 // this is the correct way.
1638 /* truss cp fil fil2:
1639 lstat("LyXVC3.lyx", 0xEFFFF898) Err#2 ENOENT
1640 stat("LyXVC.lyx", 0xEFFFF688) = 0
1641 open("LyXVC.lyx", O_RDONLY) = 3
1642 open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
1643 fstat(4, 0xEFFFF508) = 0
1644 fstat(3, 0xEFFFF508) = 0
1645 read(3, " # T h i s f i l e w".., 8192) = 5579
1646 write(4, " # T h i s f i l e w".., 5579) = 5579
1647 read(3, 0xEFFFD4A0, 8192) = 0
1650 chmod("LyXVC3.lyx", 0100644) = 0
1651 lseek(0, 0, SEEK_CUR) = 46440
1655 // Should probably have some more error checking here.
1656 // Should be cleaned up in 0.13, at least a bit.
1657 // Doing it this way, also makes the inodes stay the same.
1658 // This is still not a very good solution, in particular we
1659 // might loose the owner of the backup.
1660 FileInfo finfo(fileName());
1661 if (finfo.exist()) {
1662 mode_t fmode = finfo.getMode();
1663 struct utimbuf times = {
1664 finfo.getAccessTime(),
1665 finfo.getModificationTime() };
1667 ifstream ifs(fileName().c_str());
1668 ofstream ofs(s.c_str(), ios::out|ios::trunc);
1673 ::chmod(s.c_str(), fmode);
1675 if (::utime(s.c_str(), ×)) {
1676 lyxerr << "utime error." << endl;
1679 lyxerr << "LyX was not able to make "
1680 "backup copy. Beware." << endl;
1685 if (writeFile(fileName(), false)) {
1687 removeAutosaveFile(fileName());
1689 // Saving failed, so backup is not backup
1690 if (lyxrc.make_backup) {
1691 lyx::rename(s, fileName());
1699 // Returns false if unsuccesful
1700 bool Buffer::writeFile(string const & fname, bool flag) const
1702 // if flag is false writeFile will not create any GUI
1703 // warnings, only cerr.
1704 // Needed for autosave in background or panic save (Matthias 120496)
1706 if (read_only && (fname == fileName())) {
1707 // Here we should come with a question if we should
1708 // perform the write anyway.
1710 lyxerr << _("Error! Document is read-only: ")
1713 Alert::alert(_("Error! Document is read-only: "),
1718 FileInfo finfo(fname);
1719 if (finfo.exist() && !finfo.writable()) {
1720 // Here we should come with a question if we should
1721 // try to do the save anyway. (i.e. do a chmod first)
1723 lyxerr << _("Error! Cannot write file: ")
1726 Alert::err_alert(_("Error! Cannot write file: "),
1731 ofstream ofs(fname.c_str());
1734 lyxerr << _("Error! Cannot open file: ")
1737 Alert::err_alert(_("Error! Cannot open file: "),
1743 // Use the standard "C" locale for file output.
1744 ofs.imbue(std::locale::classic());
1747 // The top of the file should not be written by params.
1749 // write out a comment in the top of the file
1750 ofs << '#' << lyx_docversion
1751 << " created this file. For more info see http://www.lyx.org/\n"
1752 << "\\lyxformat " << LYX_FORMAT << "\n";
1754 // now write out the buffer paramters.
1755 params.writeFile(ofs);
1757 Paragraph::depth_type depth = 0;
1759 // this will write out all the paragraphs
1760 // using recursive descent.
1761 paragraph->writeFile(this, ofs, params, depth);
1763 // Write marker that shows file is complete
1764 ofs << "\n\\the_end" << endl;
1768 // how to check if close went ok?
1769 // Following is an attempt... (BE 20001011)
1771 // good() returns false if any error occured, including some
1772 // formatting error.
1773 // bad() returns true if something bad happened in the buffer,
1774 // which should include file system full errors.
1781 lyxerr << "Buffer::writeFile: BAD ERROR!" << endl;
1783 lyxerr << "Buffer::writeFile: NOT SO BAD ERROR!"
1795 pair<int, string> const addDepth(int depth, int ldepth)
1799 d += (ldepth - depth) * 2;
1800 return make_pair(d, string(d, ' '));
1806 string const Buffer::asciiParagraph(Paragraph const * par,
1807 unsigned int linelen,
1808 bool noparbreak) const
1810 ostringstream buffer;
1811 Paragraph::depth_type depth = 0;
1813 Paragraph::depth_type ltype_depth = 0;
1814 bool ref_printed = false;
1815 // if (!par->previous()) {
1817 // begins or ends a deeper area ?
1818 if (depth != par->params().depth()) {
1819 if (par->params().depth() > depth) {
1820 while (par->params().depth() > depth) {
1824 while (par->params().depth() < depth) {
1830 depth = par->params().depth();
1833 // First write the layout
1834 string const & tmp = par->layout();
1835 if (compare_no_case(tmp, "itemize") == 0) {
1837 ltype_depth = depth + 1;
1838 } else if (compare_no_case(tmp, "enumerate") == 0) {
1840 ltype_depth = depth + 1;
1841 } else if (contains(lowercase(tmp), "ection")) {
1843 ltype_depth = depth + 1;
1844 } else if (contains(lowercase(tmp), "aragraph")) {
1846 ltype_depth = depth + 1;
1847 } else if (compare_no_case(tmp, "description") == 0) {
1849 ltype_depth = depth + 1;
1850 } else if (compare_no_case(tmp, "abstract") == 0) {
1853 } else if (compare_no_case(tmp, "bibliography") == 0) {
1861 /* maybe some vertical spaces */
1863 /* the labelwidthstring used in lists */
1867 /* some pagebreaks? */
1871 /* what about the alignment */
1873 // lyxerr << "Should this ever happen?" << endl;
1876 // linelen <= 0 is special and means we don't have pargraph breaks
1878 string::size_type currlinelen = 0;
1884 buffer << string(depth * 2, ' ');
1885 currlinelen += depth * 2;
1888 // we should probably change to the paragraph language in the
1889 // gettext here (if possible) so that strings are outputted in
1890 // the correct language! (20012712 Jug)
1894 case 4: // (Sub)Paragraph
1895 case 5: // Description
1899 buffer << _("Abstract") << "\n\n";
1902 string const abst = _("Abstract: ");
1904 currlinelen += abst.length();
1907 case 7: // Bibliography
1910 buffer << _("References") << "\n\n";
1913 string const refs = _("References: ");
1915 currlinelen += refs.length();
1923 string const parlab = par->params().labelString();
1924 buffer << parlab << " ";
1925 currlinelen += parlab.length() + 1;
1933 pair<int, string> p = addDepth(depth, ltype_depth);
1935 currlinelen += p.first;
1938 // this is to change the linebreak to do it by word a bit more
1939 // intelligent hopefully! (only in the case where we have a
1940 // max linelenght!) (Jug)
1944 for (pos_type i = 0; i < par->size(); ++i) {
1945 char c = par->getUChar(params, i);
1947 case Paragraph::META_INSET:
1949 Inset const * inset = par->getInset(i);
1953 currlinelen += word.length();
1956 if (inset->ascii(this, buffer, linelen)) {
1957 // to be sure it breaks paragraph
1958 currlinelen += linelen;
1964 case Paragraph::META_NEWLINE:
1966 buffer << word << "\n";
1969 pair<int, string> p = addDepth(depth,
1972 currlinelen = p.first;
1976 case Paragraph::META_HFILL:
1977 buffer << word << "\t";
1978 currlinelen += word.length() + 1;
1985 currlinelen + word.length() > linelen - 10) {
1987 pair<int, string> p =
1988 addDepth(depth, ltype_depth);
1990 currlinelen = p.first;
1993 buffer << word << ' ';
1994 currlinelen += word.length() + 1;
2001 lyxerr[Debug::INFO] <<
2002 "writeAsciiFile: NULL char in structure." << endl;
2004 if ((linelen > 0) &&
2005 (currlinelen + word.length()) > linelen)
2009 pair<int, string> p =
2010 addDepth(depth, ltype_depth);
2012 currlinelen = p.first;
2019 return buffer.str().c_str();
2023 void Buffer::writeFileAscii(string const & fname, int linelen)
2025 ofstream ofs(fname.c_str());
2027 Alert::err_alert(_("Error: Cannot write file:"), fname);
2030 writeFileAscii(ofs, linelen);
2034 void Buffer::writeFileAscii(ostream & ofs, int linelen)
2036 Paragraph * par = paragraph;
2038 ofs << asciiParagraph(par, linelen, par->previous() == 0);
2048 void Buffer::makeLaTeXFile(string const & fname,
2049 string const & original_path,
2050 bool nice, bool only_body)
2052 lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
2054 ofstream ofs(fname.c_str());
2056 Alert::err_alert(_("Error: Cannot open file: "), fname);
2060 niceFile = nice; // this will be used by Insetincludes.
2062 tex_code_break_column = lyxrc.ascii_linelen;
2064 // validate the buffer.
2065 lyxerr[Debug::LATEX] << " Validating buffer..." << endl;
2066 LaTeXFeatures features(params);
2068 lyxerr[Debug::LATEX] << " Buffer validation done." << endl;
2071 // The starting paragraph of the coming rows is the
2072 // first paragraph of the document. (Asger)
2073 texrow.start(paragraph, 0);
2075 if (!only_body && nice) {
2076 ofs << "%% " << lyx_docversion << " created this file. "
2077 "For more info, see http://www.lyx.org/.\n"
2078 "%% Do not edit unless you really know what "
2083 lyxerr[Debug::INFO] << "lyx header finished" << endl;
2084 // There are a few differences between nice LaTeX and usual files:
2085 // usual is \batchmode and has a
2086 // special input@path to allow the including of figures
2087 // with either \input or \includegraphics (what figinsets do).
2088 // batchmode is not set if there is a tex_code_break_column.
2089 // In this case somebody is interested in the generated LaTeX,
2090 // so this is OK. input@path is set when the actual parameter
2091 // original_path is set. This is done for usual tex-file, but not
2092 // for nice-latex-file. (Matthias 250696)
2095 // code for usual, NOT nice-latex-file
2096 ofs << "\\batchmode\n"; // changed
2097 // from \nonstopmode
2100 if (!original_path.empty()) {
2101 string inputpath = os::external_path(original_path);
2102 subst(inputpath, "~", "\\string~");
2103 ofs << "\\makeatletter\n"
2104 << "\\def\\input@path{{"
2105 << inputpath << "/}}\n"
2106 << "\\makeatother\n";
2112 ofs << "\\documentclass";
2114 LyXTextClass const & tclass = textclasslist[params.textclass];
2116 ostringstream options; // the document class options.
2118 if (tokenPos(tclass.opt_fontsize(),
2119 '|', params.fontsize) >= 0) {
2120 // only write if existing in list (and not default)
2121 options << params.fontsize << "pt,";
2125 if (!params.use_geometry &&
2126 (params.paperpackage == BufferParams::PACKAGE_NONE)) {
2127 switch (params.papersize) {
2128 case BufferParams::PAPER_A4PAPER:
2129 options << "a4paper,";
2131 case BufferParams::PAPER_USLETTER:
2132 options << "letterpaper,";
2134 case BufferParams::PAPER_A5PAPER:
2135 options << "a5paper,";
2137 case BufferParams::PAPER_B5PAPER:
2138 options << "b5paper,";
2140 case BufferParams::PAPER_EXECUTIVEPAPER:
2141 options << "executivepaper,";
2143 case BufferParams::PAPER_LEGALPAPER:
2144 options << "legalpaper,";
2150 if (params.sides != tclass.sides()) {
2151 switch (params.sides) {
2152 case LyXTextClass::OneSide:
2153 options << "oneside,";
2155 case LyXTextClass::TwoSides:
2156 options << "twoside,";
2162 if (params.columns != tclass.columns()) {
2163 if (params.columns == 2)
2164 options << "twocolumn,";
2166 options << "onecolumn,";
2169 if (!params.use_geometry
2170 && params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
2171 options << "landscape,";
2173 // language should be a parameter to \documentclass
2175 ostringstream language_options;
2176 if (params.language->babel() == "hebrew"
2177 && default_language->babel() != "hebrew")
2178 // This seems necessary
2179 features.useLanguage(default_language);
2181 if (lyxrc.language_use_babel ||
2182 params.language->lang() != lyxrc.default_language ||
2183 !features.hasLanguages()) {
2185 language_options << features.getLanguages();
2186 language_options << params.language->babel();
2187 if (lyxrc.language_global_options)
2188 options << language_options.str() << ',';
2191 // the user-defined options
2192 if (!params.options.empty()) {
2193 options << params.options << ',';
2196 string strOptions(options.str().c_str());
2197 if (!strOptions.empty()) {
2198 strOptions = strip(strOptions, ',');
2199 ofs << '[' << strOptions << ']';
2202 ofs << '{' << tclass.latexname() << "}\n";
2204 // end of \documentclass defs
2206 // font selection must be done before loading fontenc.sty
2207 // The ae package is not needed when using OT1 font encoding.
2208 if (params.fonts != "default" &&
2209 (params.fonts != "ae" || lyxrc.fontenc != "default")) {
2210 ofs << "\\usepackage{" << params.fonts << "}\n";
2212 if (params.fonts == "ae") {
2213 ofs << "\\usepackage{aecompl}\n";
2217 // this one is not per buffer
2218 if (lyxrc.fontenc != "default") {
2219 ofs << "\\usepackage[" << lyxrc.fontenc
2224 if (params.inputenc == "auto") {
2225 string const doc_encoding =
2226 params.language->encoding()->LatexName();
2228 // Create a list with all the input encodings used
2230 set<string> encodings = features.getEncodingSet(doc_encoding);
2232 ofs << "\\usepackage[";
2233 std::copy(encodings.begin(), encodings.end(),
2234 std::ostream_iterator<string>(ofs, ","));
2235 ofs << doc_encoding << "]{inputenc}\n";
2237 } else if (params.inputenc != "default") {
2238 ofs << "\\usepackage[" << params.inputenc
2243 // At the very beginning the text parameters.
2244 if (params.paperpackage != BufferParams::PACKAGE_NONE) {
2245 switch (params.paperpackage) {
2246 case BufferParams::PACKAGE_A4:
2247 ofs << "\\usepackage{a4}\n";
2250 case BufferParams::PACKAGE_A4WIDE:
2251 ofs << "\\usepackage{a4wide}\n";
2254 case BufferParams::PACKAGE_WIDEMARGINSA4:
2255 ofs << "\\usepackage[widemargins]{a4}\n";
2260 if (params.use_geometry) {
2261 ofs << "\\usepackage{geometry}\n";
2263 ofs << "\\geometry{verbose";
2264 if (params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
2265 ofs << ",landscape";
2266 switch (params.papersize2) {
2267 case BufferParams::VM_PAPER_CUSTOM:
2268 if (!params.paperwidth.empty())
2269 ofs << ",paperwidth="
2270 << params.paperwidth;
2271 if (!params.paperheight.empty())
2272 ofs << ",paperheight="
2273 << params.paperheight;
2275 case BufferParams::VM_PAPER_USLETTER:
2276 ofs << ",letterpaper";
2278 case BufferParams::VM_PAPER_USLEGAL:
2279 ofs << ",legalpaper";
2281 case BufferParams::VM_PAPER_USEXECUTIVE:
2282 ofs << ",executivepaper";
2284 case BufferParams::VM_PAPER_A3:
2287 case BufferParams::VM_PAPER_A4:
2290 case BufferParams::VM_PAPER_A5:
2293 case BufferParams::VM_PAPER_B3:
2296 case BufferParams::VM_PAPER_B4:
2299 case BufferParams::VM_PAPER_B5:
2303 // default papersize ie BufferParams::VM_PAPER_DEFAULT
2304 switch (lyxrc.default_papersize) {
2305 case BufferParams::PAPER_DEFAULT: // keep compiler happy
2306 case BufferParams::PAPER_USLETTER:
2307 ofs << ",letterpaper";
2309 case BufferParams::PAPER_LEGALPAPER:
2310 ofs << ",legalpaper";
2312 case BufferParams::PAPER_EXECUTIVEPAPER:
2313 ofs << ",executivepaper";
2315 case BufferParams::PAPER_A3PAPER:
2318 case BufferParams::PAPER_A4PAPER:
2321 case BufferParams::PAPER_A5PAPER:
2324 case BufferParams::PAPER_B5PAPER:
2329 if (!params.topmargin.empty())
2330 ofs << ",tmargin=" << params.topmargin;
2331 if (!params.bottommargin.empty())
2332 ofs << ",bmargin=" << params.bottommargin;
2333 if (!params.leftmargin.empty())
2334 ofs << ",lmargin=" << params.leftmargin;
2335 if (!params.rightmargin.empty())
2336 ofs << ",rmargin=" << params.rightmargin;
2337 if (!params.headheight.empty())
2338 ofs << ",headheight=" << params.headheight;
2339 if (!params.headsep.empty())
2340 ofs << ",headsep=" << params.headsep;
2341 if (!params.footskip.empty())
2342 ofs << ",footskip=" << params.footskip;
2347 if (tokenPos(tclass.opt_pagestyle(),
2348 '|', params.pagestyle) >= 0) {
2349 if (params.pagestyle == "fancy") {
2350 ofs << "\\usepackage{fancyhdr}\n";
2353 ofs << "\\pagestyle{" << params.pagestyle << "}\n";
2357 if (params.secnumdepth != tclass.secnumdepth()) {
2358 ofs << "\\setcounter{secnumdepth}{"
2359 << params.secnumdepth
2363 if (params.tocdepth != tclass.tocdepth()) {
2364 ofs << "\\setcounter{tocdepth}{"
2370 if (params.paragraph_separation) {
2371 switch (params.defskip.kind()) {
2372 case VSpace::SMALLSKIP:
2373 ofs << "\\setlength\\parskip{\\smallskipamount}\n";
2375 case VSpace::MEDSKIP:
2376 ofs << "\\setlength\\parskip{\\medskipamount}\n";
2378 case VSpace::BIGSKIP:
2379 ofs << "\\setlength\\parskip{\\bigskipamount}\n";
2381 case VSpace::LENGTH:
2382 ofs << "\\setlength\\parskip{"
2383 << params.defskip.length().asLatexString()
2386 default: // should never happen // Then delete it.
2387 ofs << "\\setlength\\parskip{\\medskipamount}\n";
2392 ofs << "\\setlength\\parindent{0pt}\n";
2396 // Now insert the LyX specific LaTeX commands...
2398 // The optional packages;
2399 string preamble(features.getPackages());
2401 // this might be useful...
2402 preamble += "\n\\makeatletter\n";
2404 // Some macros LyX will need
2405 string tmppreamble(features.getMacros());
2407 if (!tmppreamble.empty()) {
2408 preamble += "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2409 "LyX specific LaTeX commands.\n"
2410 + tmppreamble + '\n';
2413 // the text class specific preamble
2414 tmppreamble = features.getTClassPreamble();
2415 if (!tmppreamble.empty()) {
2416 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2417 "Textclass specific LaTeX commands.\n"
2418 + tmppreamble + '\n';
2421 /* the user-defined preamble */
2422 if (!params.preamble.empty()) {
2423 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2424 "User specified LaTeX commands.\n"
2425 + params.preamble + '\n';
2428 preamble += "\\makeatother\n";
2430 // Itemize bullet settings need to be last in case the user
2431 // defines their own bullets that use a package included
2432 // in the user-defined preamble -- ARRae
2433 // Actually it has to be done much later than that
2434 // since some packages like frenchb make modifications
2435 // at \begin{document} time -- JMarc
2437 for (int i = 0; i < 4; ++i) {
2438 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
2439 if (bullets_def.empty())
2440 bullets_def="\\AtBeginDocument{\n";
2441 bullets_def += " \\renewcommand{\\labelitemi";
2443 // `i' is one less than the item to modify
2450 bullets_def += "ii";
2456 bullets_def += "}{" +
2457 params.user_defined_bullets[i].getText()
2462 if (!bullets_def.empty())
2463 preamble += bullets_def + "}\n\n";
2466 int(lyx::count(preamble.begin(), preamble.end(), '\n'));
2467 for (int j = 0; j != nlines; ++j) {
2473 // We try to load babel late, in case it interferes
2474 // with other packages.
2476 string tmp = lyxrc.language_package;
2477 if (!lyxrc.language_global_options
2478 && tmp == "\\usepackage{babel}")
2479 tmp = string("\\usepackage[") +
2480 language_options.str().c_str() +
2487 ofs << "\\begin{document}\n";
2490 lyxerr[Debug::INFO] << "preamble finished, now the body." << endl;
2492 if (!lyxrc.language_auto_begin) {
2493 ofs << subst(lyxrc.language_command_begin, "$$lang",
2494 params.language->babel())
2499 latexParagraphs(ofs, paragraph, 0, texrow);
2501 // add this just in case after all the paragraphs
2505 if (!lyxrc.language_auto_end) {
2506 ofs << subst(lyxrc.language_command_end, "$$lang",
2507 params.language->babel())
2513 ofs << "\\end{document}\n";
2516 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
2518 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
2522 // Just to be sure. (Asger)
2525 // tex_code_break_column's value is used to decide
2526 // if we are in batchmode or not (within mathed_write()
2527 // in math_write.C) so we must set it to a non-zero
2528 // value when we leave otherwise we save incorrect .lyx files.
2529 tex_code_break_column = lyxrc.ascii_linelen;
2533 lyxerr << "File was not closed properly." << endl;
2536 lyxerr[Debug::INFO] << "Finished making latex file." << endl;
2537 lyxerr[Debug::INFO] << "Row count was " << texrow.rows()-1 << "." << endl;
2539 // we want this to be true outside previews (for insetexternal)
2545 // LaTeX all paragraphs from par to endpar, if endpar == 0 then to the end
2547 void Buffer::latexParagraphs(ostream & ofs, Paragraph * par,
2548 Paragraph * endpar, TexRow & texrow) const
2550 bool was_title = false;
2551 bool already_title = false;
2554 while (par != endpar) {
2555 Inset * in = par->inInset();
2556 // well we have to check if we are in an inset with unlimited
2557 // lenght (all in one row) if that is true then we don't allow
2558 // any special options in the paragraph and also we don't allow
2559 // any environment other then "Standard" to be valid!
2560 if ((in == 0) || !in->forceDefaultParagraphs(in)) {
2561 LyXLayout const & layout =
2562 textclasslist[params.textclass][par->layout()];
2564 if (layout.intitle) {
2565 if (already_title) {
2566 lyxerr <<"Error in latexParagraphs: You"
2567 " should not mix title layouts"
2568 " with normal ones." << endl;
2571 } else if (was_title && !already_title) {
2572 ofs << "\\maketitle\n";
2574 already_title = true;
2578 if (layout.isEnvironment()) {
2579 par = par->TeXEnvironment(this, params, ofs, texrow);
2581 par = par->TeXOnePar(this, params, ofs, texrow, false);
2584 par = par->TeXOnePar(this, params, ofs, texrow, false);
2587 // It might be that we only have a title in this document
2588 if (was_title && !already_title) {
2589 ofs << "\\maketitle\n";
2595 bool Buffer::isLatex() const
2597 return textclasslist[params.textclass].outputType() == LATEX;
2601 bool Buffer::isLinuxDoc() const
2603 return textclasslist[params.textclass].outputType() == LINUXDOC;
2607 bool Buffer::isLiterate() const
2609 return textclasslist[params.textclass].outputType() == LITERATE;
2613 bool Buffer::isDocBook() const
2615 return textclasslist[params.textclass].outputType() == DOCBOOK;
2619 bool Buffer::isSGML() const
2621 LyXTextClass const & tclass = textclasslist[params.textclass];
2623 return tclass.outputType() == LINUXDOC ||
2624 tclass.outputType() == DOCBOOK;
2628 void Buffer::sgmlOpenTag(ostream & os, Paragraph::depth_type,
2629 string const & latexname) const
2631 if (!latexname.empty() && latexname != "!-- --")
2632 //os << "<!-- " << depth << " -->" << "<" << latexname << ">";
2633 os << "<" << latexname << ">";
2637 void Buffer::sgmlCloseTag(ostream & os, Paragraph::depth_type,
2638 string const & latexname) const
2640 if (!latexname.empty() && latexname != "!-- --")
2641 //os << "<!-- " << depth << " -->" << "</" << latexname << ">\n";
2642 os << "</" << latexname << ">";
2646 void Buffer::makeLinuxDocFile(string const & fname, bool nice, bool body_only)
2648 ofstream ofs(fname.c_str());
2651 Alert::alert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2655 niceFile = nice; // this will be used by included files.
2657 LaTeXFeatures features(params);
2663 LyXTextClass const & tclass = textclasslist[params.textclass];
2665 string top_element = tclass.latexname();
2668 ofs << "<!doctype linuxdoc system";
2670 string preamble = params.preamble;
2671 const string name = nice ? ChangeExtension(filename_, ".sgml")
2673 preamble += features.getIncludedFiles(name);
2674 preamble += features.getLyXSGMLEntities();
2676 if (!preamble.empty()) {
2677 ofs << " [ " << preamble << " ]";
2681 if (params.options.empty())
2682 sgmlOpenTag(ofs, 0, top_element);
2684 string top = top_element;
2686 top += params.options;
2687 sgmlOpenTag(ofs, 0, top);
2691 ofs << "<!-- " << lyx_docversion
2692 << " created this file. For more info see http://www.lyx.org/"
2695 Paragraph::depth_type depth = 0; // paragraph depth
2696 Paragraph * par = paragraph;
2698 vector<string> environment_stack(5);
2701 LyXLayout const & style = tclass[par->layout()];
2703 // treat <toc> as a special case for compatibility with old code
2704 if (par->isInset(0)) {
2705 Inset * inset = par->getInset(0);
2706 Inset::Code lyx_code = inset->lyxCode();
2707 if (lyx_code == Inset::TOC_CODE) {
2708 string const temp = "toc";
2709 sgmlOpenTag(ofs, depth, temp);
2716 // environment tag closing
2717 for (; depth > par->params().depth(); --depth) {
2718 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2719 environment_stack[depth].erase();
2722 // write opening SGML tags
2723 switch (style.latextype) {
2724 case LATEX_PARAGRAPH:
2725 if (depth == par->params().depth()
2726 && !environment_stack[depth].empty()) {
2727 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2728 environment_stack[depth].erase();
2734 sgmlOpenTag(ofs, depth, style.latexname());
2740 _("Error : Wrong depth for"
2741 " LatexType Command.\n"));
2743 if (!environment_stack[depth].empty()) {
2744 sgmlCloseTag(ofs, depth,
2745 environment_stack[depth]);
2749 environment_stack[depth].erase();
2750 sgmlOpenTag(ofs, depth, style.latexname());
2753 case LATEX_ENVIRONMENT:
2754 case LATEX_ITEM_ENVIRONMENT:
2755 if (depth == par->params().depth()
2756 && environment_stack[depth] != style.latexname()) {
2757 sgmlCloseTag(ofs, depth,
2758 environment_stack[depth]);
2759 environment_stack[depth].erase();
2761 if (depth < par->params().depth()) {
2762 depth = par->params().depth();
2763 environment_stack[depth].erase();
2765 if (environment_stack[depth] != style.latexname()) {
2767 sgmlOpenTag(ofs, depth, "p");
2769 sgmlOpenTag(ofs, depth, style.latexname());
2771 if (environment_stack.size() == depth + 1)
2772 environment_stack.push_back("!-- --");
2773 environment_stack[depth] = style.latexname();
2776 if (style.latexparam() == "CDATA")
2779 if (style.latextype == LATEX_ENVIRONMENT) break;
2781 if (style.labeltype == LABEL_MANUAL)
2786 sgmlOpenTag(ofs, depth + 1, item_name);
2789 sgmlOpenTag(ofs, depth, style.latexname());
2793 simpleLinuxDocOnePar(ofs, par, depth);
2798 // write closing SGML tags
2799 switch (style.latextype) {
2802 case LATEX_ENVIRONMENT:
2803 case LATEX_ITEM_ENVIRONMENT:
2804 if (style.latexparam() == "CDATA")
2808 sgmlCloseTag(ofs, depth, style.latexname());
2814 for (int i=depth; i >= 0; --i)
2815 sgmlCloseTag(ofs, depth, environment_stack[i]);
2819 sgmlCloseTag(ofs, 0, top_element);
2823 // How to check for successful close
2825 // we want this to be true outside previews (for insetexternal)
2830 // checks, if newcol chars should be put into this line
2831 // writes newline, if necessary.
2834 void sgmlLineBreak(ostream & os, string::size_type & colcount,
2835 string::size_type newcol)
2838 if (colcount > lyxrc.ascii_linelen) {
2840 colcount = newcol; // assume write after this call
2855 string tag_name(PAR_TAG const & pt) {
2857 case NONE: return "!-- --";
2858 case TT: return "tt";
2859 case SF: return "sf";
2860 case BF: return "bf";
2861 case IT: return "it";
2862 case SL: return "sl";
2863 case EM: return "em";
2870 void operator|=(PAR_TAG & p1, PAR_TAG const & p2)
2872 p1 = static_cast<PAR_TAG>(p1 | p2);
2877 void reset(PAR_TAG & p1, PAR_TAG const & p2)
2879 p1 = static_cast<PAR_TAG>(p1 & ~p2);
2885 // Handle internal paragraph parsing -- layout already processed.
2886 void Buffer::simpleLinuxDocOnePar(ostream & os,
2888 Paragraph::depth_type /*depth*/)
2890 LyXLayout const & style =
2891 textclasslist[params.textclass][par->layout()];
2892 string::size_type char_line_count = 5; // Heuristic choice ;-)
2894 // gets paragraph main font
2897 if (style.labeltype == LABEL_MANUAL) {
2898 font_old = style.labelfont;
2901 font_old = style.font;
2905 LyXFont::FONT_FAMILY family_type = LyXFont::ROMAN_FAMILY;
2906 LyXFont::FONT_SERIES series_type = LyXFont::MEDIUM_SERIES;
2907 LyXFont::FONT_SHAPE shape_type = LyXFont::UP_SHAPE;
2910 stack<PAR_TAG> tag_state;
2911 // parsing main loop
2912 for (pos_type i = 0; i < par->size(); ++i) {
2914 PAR_TAG tag_close = NONE;
2915 list < PAR_TAG > tag_open;
2917 LyXFont const font = par->getFont(params, i);
2919 if (font_old.family() != font.family()) {
2920 switch (family_type) {
2921 case LyXFont::SANS_FAMILY:
2924 case LyXFont::TYPEWRITER_FAMILY:
2931 family_type = font.family();
2933 switch (family_type) {
2934 case LyXFont::SANS_FAMILY:
2935 tag_open.push_back(SF);
2937 case LyXFont::TYPEWRITER_FAMILY:
2938 tag_open.push_back(TT);
2945 if (font_old.series() != font.series()) {
2946 switch (series_type) {
2947 case LyXFont::BOLD_SERIES:
2954 series_type = font.series();
2956 switch (series_type) {
2957 case LyXFont::BOLD_SERIES:
2958 tag_open.push_back(BF);
2966 if (font_old.shape() != font.shape()) {
2967 switch (shape_type) {
2968 case LyXFont::ITALIC_SHAPE:
2971 case LyXFont::SLANTED_SHAPE:
2978 shape_type = font.shape();
2980 switch (shape_type) {
2981 case LyXFont::ITALIC_SHAPE:
2982 tag_open.push_back(IT);
2984 case LyXFont::SLANTED_SHAPE:
2985 tag_open.push_back(SL);
2992 if (font_old.emph() != font.emph()) {
2993 if (font.emph() == LyXFont::ON) {
2994 tag_open.push_back(EM);
3003 list < PAR_TAG > temp;
3004 while (!tag_state.empty() && tag_close) {
3005 PAR_TAG k = tag_state.top();
3007 os << "</" << tag_name(k) << ">";
3014 for(list< PAR_TAG >::const_iterator j = temp.begin();
3015 j != temp.end(); ++j) {
3017 os << "<" << tag_name(*j) << ">";
3020 for(list< PAR_TAG >::const_iterator j = tag_open.begin();
3021 j != tag_open.end(); ++j) {
3023 os << "<" << tag_name(*j) << ">";
3026 char c = par->getChar(i);
3028 if (c == Paragraph::META_INSET) {
3029 Inset * inset = par->getInset(i);
3030 inset->linuxdoc(this, os);
3035 if (style.latexparam() == "CDATA") {
3036 // "TeX"-Mode on == > SGML-Mode on.
3042 if (par->sgmlConvertChar(c, sgml_string)
3043 && !style.free_spacing && !par->isFreeSpacing())
3045 // in freespacing mode, spaces are
3046 // non-breaking characters
3047 if (desc_on) {// if char is ' ' then...
3050 sgmlLineBreak(os, char_line_count, 6);
3054 sgmlLineBreak(os, char_line_count, 1);
3059 char_line_count += sgml_string.length();
3065 while (!tag_state.empty()) {
3066 os << "</" << tag_name(tag_state.top()) << ">";
3070 // resets description flag correctly
3072 // <tag> not closed...
3073 sgmlLineBreak(os, char_line_count, 6);
3079 // Print an error message.
3080 void Buffer::sgmlError(Paragraph * par, int pos,
3081 string const & message) const
3083 // insert an error marker in text
3084 InsetError * new_inset = new InsetError(message);
3085 par->insertInset(pos, new_inset, LyXFont(LyXFont::ALL_INHERIT,
3090 void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
3092 ofstream ofs(fname.c_str());
3094 Alert::alert(_("LYX_ERROR:"), _("Cannot write file"), fname);
3098 Paragraph * par = paragraph;
3100 niceFile = nice; // this will be used by Insetincludes.
3102 LaTeXFeatures features(params);
3107 LyXTextClass const & tclass = textclasslist[params.textclass];
3108 string top_element = tclass.latexname();
3111 ofs << "<!DOCTYPE " << top_element
3112 << " PUBLIC \"-//OASIS//DTD DocBook V4.1//EN\"";
3114 string preamble = params.preamble;
3115 const string name = nice ? ChangeExtension(filename_, ".sgml")
3117 preamble += features.getIncludedFiles(name);
3118 preamble += features.getLyXSGMLEntities();
3120 if (!preamble.empty()) {
3121 ofs << "\n [ " << preamble << " ]";
3126 string top = top_element;
3128 top += params.language->code();
3131 if (!params.options.empty()) {
3133 top += params.options;
3135 sgmlOpenTag(ofs, 0, top);
3137 ofs << "<!-- DocBook file was created by " << lyx_docversion
3138 << "\n See http://www.lyx.org/ for more information -->\n";
3140 vector<string> environment_stack(10);
3141 vector<string> environment_inner(10);
3142 vector<string> command_stack(10);
3144 bool command_flag = false;
3145 Paragraph::depth_type command_depth = 0;
3146 Paragraph::depth_type command_base = 0;
3147 Paragraph::depth_type cmd_depth = 0;
3148 Paragraph::depth_type depth = 0; // paragraph depth
3151 string command_name;
3157 int desc_on = 0; // description mode
3159 LyXLayout const & style = tclass[par->layout()];
3161 // environment tag closing
3162 for (; depth > par->params().depth(); --depth) {
3163 if (environment_inner[depth] != "!-- --") {
3164 item_name = "listitem";
3165 sgmlCloseTag(ofs, command_depth + depth,
3167 if (environment_inner[depth] == "varlistentry")
3168 sgmlCloseTag(ofs, depth+command_depth,
3169 environment_inner[depth]);
3171 sgmlCloseTag(ofs, depth + command_depth,
3172 environment_stack[depth]);
3173 environment_stack[depth].erase();
3174 environment_inner[depth].erase();
3177 if (depth == par->params().depth()
3178 && environment_stack[depth] != style.latexname()
3179 && !environment_stack[depth].empty()) {
3180 if (environment_inner[depth] != "!-- --") {
3181 item_name= "listitem";
3182 sgmlCloseTag(ofs, command_depth+depth,
3184 if (environment_inner[depth] == "varlistentry")
3186 depth + command_depth,
3187 environment_inner[depth]);
3190 sgmlCloseTag(ofs, depth + command_depth,
3191 environment_stack[depth]);
3193 environment_stack[depth].erase();
3194 environment_inner[depth].erase();
3197 // Write opening SGML tags.
3198 switch (style.latextype) {
3199 case LATEX_PARAGRAPH:
3200 sgmlOpenTag(ofs, depth + command_depth,
3207 _("Error : Wrong depth for "
3208 "LatexType Command.\n"));
3210 command_name = style.latexname();
3212 sgmlparam = style.latexparam();
3213 c_params = split(sgmlparam, c_depth,'|');
3215 cmd_depth = lyx::atoi(c_depth);
3218 if (cmd_depth < command_base) {
3219 for (Paragraph::depth_type j = command_depth; j >= command_base; --j)
3220 sgmlCloseTag(ofs, j, command_stack[j]);
3221 command_depth = command_base = cmd_depth;
3222 } else if (cmd_depth <= command_depth) {
3223 for (int j = command_depth; j >= int(cmd_depth); --j)
3224 sgmlCloseTag(ofs, j, command_stack[j]);
3225 command_depth = cmd_depth;
3227 command_depth = cmd_depth;
3229 command_depth = command_base = cmd_depth;
3230 command_flag = true;
3232 if (command_stack.size() == command_depth + 1)
3233 command_stack.push_back(string());
3234 command_stack[command_depth] = command_name;
3236 // treat label as a special case for
3237 // more WYSIWYM handling.
3238 // This is a hack while paragraphs can't have
3239 // attributes, like id in this case.
3240 if (par->isInset(0)) {
3241 Inset * inset = par->getInset(0);
3242 Inset::Code lyx_code = inset->lyxCode();
3243 if (lyx_code == Inset::LABEL_CODE) {
3244 command_name += " id=\"";
3245 command_name += (static_cast<InsetCommand *>(inset))->getContents();
3246 command_name += "\"";
3251 sgmlOpenTag(ofs, depth + command_depth, command_name);
3252 if (c_params.empty())
3253 item_name = "title";
3255 item_name = c_params;
3256 sgmlOpenTag(ofs, depth + 1 + command_depth, item_name);
3259 case LATEX_ENVIRONMENT:
3260 case LATEX_ITEM_ENVIRONMENT:
3261 if (depth < par->params().depth()) {
3262 depth = par->params().depth();
3263 environment_stack[depth].erase();
3266 if (environment_stack[depth] != style.latexname()) {
3267 if (environment_stack.size() == depth + 1) {
3268 environment_stack.push_back("!-- --");
3269 environment_inner.push_back("!-- --");
3271 environment_stack[depth] = style.latexname();
3272 environment_inner[depth] = "!-- --";
3273 sgmlOpenTag(ofs, depth + command_depth,
3274 environment_stack[depth]);
3276 if (environment_inner[depth] != "!-- --") {
3277 item_name= "listitem";
3279 command_depth + depth,
3281 if (environment_inner[depth] == "varlistentry")
3283 depth + command_depth,
3284 environment_inner[depth]);
3288 if (style.latextype == LATEX_ENVIRONMENT) {
3289 if (!style.latexparam().empty()) {
3290 if (style.latexparam() == "CDATA")
3293 sgmlOpenTag(ofs, depth + command_depth,
3294 style.latexparam());
3299 desc_on = (style.labeltype == LABEL_MANUAL);
3302 environment_inner[depth]= "varlistentry";
3304 environment_inner[depth]= "listitem";
3306 sgmlOpenTag(ofs, depth + 1 + command_depth,
3307 environment_inner[depth]);
3311 sgmlOpenTag(ofs, depth + 1 + command_depth,
3315 sgmlOpenTag(ofs, depth + 1 + command_depth,
3320 sgmlOpenTag(ofs, depth + command_depth,
3325 simpleDocBookOnePar(ofs, par, desc_on, depth+1+command_depth);
3329 // write closing SGML tags
3330 switch (style.latextype) {
3332 if (c_params.empty())
3336 sgmlCloseTag(ofs, depth + command_depth, end_tag);
3338 case LATEX_ENVIRONMENT:
3339 if (!style.latexparam().empty()) {
3340 if (style.latexparam() == "CDATA")
3343 sgmlCloseTag(ofs, depth + command_depth,
3344 style.latexparam());
3347 case LATEX_ITEM_ENVIRONMENT:
3348 if (desc_on == 1) break;
3350 sgmlCloseTag(ofs, depth + 1 + command_depth, end_tag);
3352 case LATEX_PARAGRAPH:
3353 sgmlCloseTag(ofs, depth + command_depth, style.latexname());
3356 sgmlCloseTag(ofs, depth + command_depth, style.latexname());
3362 for (int d = depth; d >= 0; --d) {
3363 if (!environment_stack[depth].empty()) {
3364 if (environment_inner[depth] != "!-- --") {
3365 item_name = "listitem";
3366 sgmlCloseTag(ofs, command_depth + depth,
3368 if (environment_inner[depth] == "varlistentry")
3369 sgmlCloseTag(ofs, depth + command_depth,
3370 environment_inner[depth]);
3373 sgmlCloseTag(ofs, depth + command_depth,
3374 environment_stack[depth]);
3378 for (int j = command_depth; j >= 0 ; --j)
3379 if (!command_stack[j].empty())
3380 sgmlCloseTag(ofs, j, command_stack[j]);
3383 sgmlCloseTag(ofs, 0, top_element);
3386 // How to check for successful close
3388 // we want this to be true outside previews (for insetexternal)
3393 void Buffer::simpleDocBookOnePar(ostream & os,
3394 Paragraph * par, int & desc_on,
3395 Paragraph::depth_type depth) const
3397 bool emph_flag = false;
3399 LyXLayout const & style =
3400 textclasslist[params.textclass][par->layout()];
3402 LyXFont font_old = style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
3404 int char_line_count = depth;
3405 //if (!style.free_spacing)
3406 // os << string(depth,' ');
3408 // parsing main loop
3409 for (pos_type i = 0; i < par->size(); ++i) {
3410 LyXFont font = par->getFont(params, i);
3412 // handle <emphasis> tag
3413 if (font_old.emph() != font.emph()) {
3414 if (font.emph() == LyXFont::ON) {
3418 os << "</emphasis>";
3424 if (par->isInset(i)) {
3425 Inset * inset = par->getInset(i);
3426 // don't print the inset in position 0 if desc_on == 3 (label)
3427 if ( i || desc_on != 3) {
3428 if(style.latexparam() == "CDATA")
3430 inset->docbook(this, os);
3431 if(style.latexparam() == "CDATA")
3435 char c = par->getChar(i);
3437 par->sgmlConvertChar(c, sgml_string);
3439 if (style.pass_thru) {
3441 } else if (style.free_spacing || par->isFreeSpacing() || c != ' ') {
3443 } else if (desc_on ==1) {
3445 os << "\n</term><listitem><para>";
3455 os << "</emphasis>";
3458 // resets description flag correctly
3460 // <term> not closed...
3461 os << "</term>\n<listitem><para> </para>";
3463 if (style.free_spacing) os << '\n';
3467 // This should be enabled when the Chktex class is implemented. (Asger)
3468 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
3469 // Other flags: -wall -v0 -x
3470 int Buffer::runChktex()
3472 if (!users->text) return 0;
3474 users->owner()->prohibitInput();
3476 // get LaTeX-Filename
3477 string const name = getLatexName();
3478 string path = filePath();
3480 string const org_path = path;
3481 if (lyxrc.use_tempdir || !IsDirWriteable(path)) {
3485 Path p(path); // path to LaTeX file
3486 users->owner()->message(_("Running chktex..."));
3488 // Remove all error insets
3489 bool const removedErrorInsets = users->removeAutoInsets();
3491 // Generate the LaTeX file if neccessary
3492 makeLaTeXFile(name, org_path, false);
3495 Chktex chktex(lyxrc.chktex_command, name, filePath());
3496 int res = chktex.run(terr); // run chktex
3499 Alert::alert(_("chktex did not work!"),
3500 _("Could not run with file:"), name);
3501 } else if (res > 0) {
3502 // Insert all errors as errors boxes
3503 users->insertErrors(terr);
3506 // if we removed error insets before we ran chktex or if we inserted
3507 // error insets after we ran chktex, this must be run:
3508 if (removedErrorInsets || res) {
3512 users->owner()->allowInput();
3518 void Buffer::validate(LaTeXFeatures & features) const
3520 Paragraph * par = paragraph;
3521 LyXTextClass const & tclass = textclasslist[params.textclass];
3523 // AMS Style is at document level
3524 if (params.use_amsmath || tclass.provides(LyXTextClass::amsmath))
3525 features.require("amsmath");
3528 // We don't use "lyxerr.debug" because of speed. (Asger)
3529 if (lyxerr.debugging(Debug::LATEX))
3530 lyxerr << "Paragraph: " << par << endl;
3532 // Now just follow the list of paragraphs and run
3533 // validate on each of them.
3534 par->validate(features);
3536 // and then the next paragraph
3540 // the bullet shapes are buffer level not paragraph level
3541 // so they are tested here
3542 for (int i = 0; i < 4; ++i) {
3543 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
3544 int const font = params.user_defined_bullets[i].getFont();
3546 int const c = params
3547 .user_defined_bullets[i]
3554 features.require("latexsym");
3556 } else if (font == 1) {
3557 features.require("amssymb");
3558 } else if ((font >= 2 && font <= 5)) {
3559 features.require("pifont");
3564 if (lyxerr.debugging(Debug::LATEX)) {
3565 features.showStruct();
3570 // This function should be in Buffer because it's a buffer's property (ale)
3571 string const Buffer::getIncludeonlyList(char delim)
3574 for (inset_iterator it = inset_iterator_begin();
3575 it != inset_iterator_end(); ++it) {
3576 if ((*it)->lyxCode() == Inset::INCLUDE_CODE) {
3577 InsetInclude * insetinc =
3578 static_cast<InsetInclude *>(*it);
3579 if (insetinc->isIncludeOnly()) {
3582 lst += insetinc->getRelFileBaseName();
3586 lyxerr[Debug::INFO] << "Includeonly(" << lst << ')' << endl;
3591 vector<string> const Buffer::getLabelList()
3593 /// if this is a child document and the parent is already loaded
3594 /// Use the parent's list instead [ale990407]
3595 if (!params.parentname.empty()
3596 && bufferlist.exists(params.parentname)) {
3597 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3599 return tmp->getLabelList();
3602 vector<string> label_list;
3603 for (inset_iterator it = inset_iterator_begin();
3604 it != inset_iterator_end(); ++it) {
3605 vector<string> const l = (*it)->getLabelList();
3606 label_list.insert(label_list.end(), l.begin(), l.end());
3612 Buffer::Lists const Buffer::getLists() const
3615 Paragraph * par = paragraph;
3617 LyXTextClass const & textclass = textclasslist[params.textclass];
3618 bool found = textclass.hasLayout("Caption");
3619 string const layout("Caption");
3622 char const labeltype = textclass[par->layout()].labeltype;
3624 if (labeltype >= LABEL_COUNTER_CHAPTER
3625 && labeltype <= LABEL_COUNTER_CHAPTER + params.tocdepth) {
3626 // insert this into the table of contents
3627 SingleList & item = l["TOC"];
3630 textclass.maxcounter());
3631 item.push_back(TocItem(par, depth, par->asString(this, true)));
3633 // For each paragrph, traverse its insets and look for
3637 Paragraph::inset_iterator it =
3638 par->inset_iterator_begin();
3639 Paragraph::inset_iterator end =
3640 par->inset_iterator_end();
3642 for (; it != end; ++it) {
3643 if ((*it)->lyxCode() == Inset::FLOAT_CODE) {
3645 static_cast<InsetFloat*>(*it);
3647 string const type = il->type();
3649 // Now find the caption in the float...
3650 // We now tranverse the paragraphs of
3652 Paragraph * tmp = il->inset.paragraph();
3654 if (tmp->layout() == layout) {
3655 SingleList & item = l[type];
3657 tostr(item.size()+1) + ". " + tmp->asString(this, false);
3658 item.push_back(TocItem(tmp, 0 , str));
3665 lyxerr << "Caption not found" << endl;
3674 // This is also a buffer property (ale)
3675 vector<pair<string, string> > const Buffer::getBibkeyList()
3677 /// if this is a child document and the parent is already loaded
3678 /// Use the parent's list instead [ale990412]
3679 if (!params.parentname.empty() && bufferlist.exists(params.parentname)) {
3680 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3682 return tmp->getBibkeyList();
3685 vector<pair<string, string> > keys;
3686 Paragraph * par = paragraph;
3689 keys.push_back(pair<string, string>(par->bibkey->getContents(),
3690 par->asString(this, false)));
3694 // Might be either using bibtex or a child has bibliography
3696 for (inset_iterator it = inset_iterator_begin();
3697 it != inset_iterator_end(); ++it) {
3698 // Search for Bibtex or Include inset
3699 if ((*it)->lyxCode() == Inset::BIBTEX_CODE) {
3700 vector<pair<string,string> > tmp =
3701 static_cast<InsetBibtex*>(*it)->getKeys(this);
3702 keys.insert(keys.end(), tmp.begin(), tmp.end());
3703 } else if ((*it)->lyxCode() == Inset::INCLUDE_CODE) {
3704 vector<pair<string,string> > const tmp =
3705 static_cast<InsetInclude*>(*it)->getKeys();
3706 keys.insert(keys.end(), tmp.begin(), tmp.end());
3715 bool Buffer::isDepClean(string const & name) const
3717 DEPCLEAN * item = dep_clean;
3718 while (item && item->master != name)
3720 if (!item) return true;
3725 void Buffer::markDepClean(string const & name)
3728 dep_clean = new DEPCLEAN;
3729 dep_clean->clean = true;
3730 dep_clean->master = name;
3731 dep_clean->next = 0;
3733 DEPCLEAN * item = dep_clean;
3734 while (item && item->master != name)
3739 item = new DEPCLEAN;
3741 item->master = name;
3748 bool Buffer::dispatch(string const & command)
3750 // Split command string into command and argument
3752 string line = frontStrip(command);
3753 string const arg = strip(frontStrip(split(line, cmd, ' ')));
3755 return dispatch(lyxaction.LookupFunc(cmd), arg);
3759 bool Buffer::dispatch(int action, string const & argument)
3761 bool dispatched = true;
3764 Exporter::Export(this, argument, false);
3774 void Buffer::resizeInsets(BufferView * bv)
3776 /// then remove all LyXText in text-insets
3777 Paragraph * par = paragraph;
3778 for (; par; par = par->next()) {
3779 par->resizeInsetsLyXText(bv);
3784 void Buffer::redraw()
3791 void Buffer::changeLanguage(Language const * from, Language const * to)
3794 ParIterator end = par_iterator_end();
3795 for (ParIterator it = par_iterator_begin(); it != end; ++it)
3796 (*it)->changeLanguage(params, from, to);
3800 bool Buffer::isMultiLingual()
3802 ParIterator end = par_iterator_end();
3803 for (ParIterator it = par_iterator_begin(); it != end; ++it)
3804 if ((*it)->isMultiLingual(params))
3811 Buffer::inset_iterator::inset_iterator(Paragraph * paragraph, pos_type pos)
3814 it = par->InsetIterator(pos);
3815 if (it == par->inset_iterator_end()) {
3822 void Buffer::inset_iterator::setParagraph()
3825 it = par->inset_iterator_begin();
3826 if (it != par->inset_iterator_end())
3831 // We maintain an invariant that whenever par = 0 then it = 0
3835 Inset * Buffer::getInsetFromID(int id_arg) const
3837 for (inset_iterator it = inset_const_iterator_begin();
3838 it != inset_const_iterator_end(); ++it)
3840 if ((*it)->id() == id_arg)
3842 Inset * in = (*it)->getInsetFromID(id_arg);
3850 Paragraph * Buffer::getParFromID(int id) const
3852 if (id < 0) return 0;
3853 Paragraph * par = paragraph;
3855 if (par->id() == id) {
3858 Paragraph * tmp = par->getParFromID(id);
3868 ParIterator Buffer::par_iterator_begin()
3870 return ParIterator(paragraph);
3874 ParIterator Buffer::par_iterator_end()
3876 return ParIterator();