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;
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 const layoutname = lex.getString();
467 LyXTextClass const & tclass = textclasslist[params.textclass];
468 bool hasLayout = tclass.hasLayout(layoutname);
470 lyxerr << "Layout '" << layoutname << "' does not"
471 << " exist in textclass '" << tclass.name()
475 #ifndef NO_COMPABILITY
476 if (compare_no_case(layoutname, "latex") == 0) {
477 ert_comp.active = true;
478 ert_comp.font = font;
482 // The is the compability reading of layout caption.
483 // It can be removed in LyX version 1.3.0. (Lgb)
484 if (compare_no_case(layoutname, "caption") == 0) {
485 // We expect that the par we are now working on is
486 // really inside a InsetText inside a InsetFloat.
487 // We also know that captions can only be
488 // one paragraph. (Lgb)
490 // We should now read until the next "\layout"
492 // This is probably not good enough, what if the
493 // caption is the last par in the document (Lgb)
494 istream & ist = lex.getStream();
500 if (prefixIs(line, "\\layout")) {
504 if (prefixIs(line, "\\begin_inset"))
506 if (prefixIs(line, "\\end_inset")) {
517 // Now we should have the whole layout in ss
518 // we should now be able to give this to the
520 ss << "\\end_inset\n";
522 // This seems like a bug in stringstream.
523 // We really should be able to use ss
525 istringstream is(ss.str());
527 tmplex.setStream(is);
528 Inset * inset = new InsetCaption;
529 inset->Read(this, tmplex);
530 par->InsertInset(pos, inset, font);
537 par = new Paragraph(par);
540 par->layout(layoutname);
541 // Test whether the layout is obsolete.
542 LyXLayout const & layout =
543 textclasslist[params.textclass][par->layout()];
544 if (!layout.obsoleted_by().empty())
545 par->layout(layout.obsoleted_by());
546 par->params().depth(depth);
547 font = LyXFont(LyXFont::ALL_INHERIT, params.language);
548 if (file_format < 216
549 && params.language->lang() == "hebrew")
550 font.setLanguage(default_language);
555 #ifndef NO_COMPABILITY
556 } else if (token == "\\begin_float") {
557 insertErtContents(par, pos);
558 //insertErtContents(par, pos, false);
559 //ert_stack.push(ert_comp);
560 //ert_comp = ErtComp();
562 // This is the compability reader. It can be removed in
563 // LyX version 1.3.0. (Lgb)
565 string const tmptok = lex.getString();
566 //lyxerr << "old float: " << tmptok << endl;
569 stringstream old_float;
571 if (tmptok == "footnote") {
572 inset = new InsetFoot(params);
573 old_float << "collapsed true\n";
574 } else if (tmptok == "margin") {
575 inset = new InsetMarginal(params);
576 old_float << "collapsed true\n";
577 } else if (tmptok == "fig") {
578 inset = new InsetFloat(params, "figure");
579 old_float << "placement htbp\n"
581 << "collapsed false\n";
582 } else if (tmptok == "tab") {
583 inset = new InsetFloat(params, "table");
584 old_float << "placement htbp\n"
586 << "collapsed false\n";
587 } else if (tmptok == "alg") {
588 inset = new InsetFloat(params, "algorithm");
589 old_float << "placement htbp\n"
591 << "collapsed false\n";
592 } else if (tmptok == "wide-fig") {
593 inset = new InsetFloat(params, "figure");
594 //InsetFloat * tmp = new InsetFloat("figure");
597 old_float << "placement htbp\n"
599 << "collapsed false\n";
600 } else if (tmptok == "wide-tab") {
601 inset = new InsetFloat(params, "table");
602 //InsetFloat * tmp = new InsetFloat("table");
605 old_float << "placement htbp\n"
607 << "collapsed false\n";
611 #ifndef NO_PEXTRA_REALLY
614 return false; // no end read yet
617 // Here we need to check for \end_deeper and handle that
618 // before we do the footnote parsing.
619 // This _is_ a hack! (Lgb)
622 string const tmp = lex.getString();
623 if (tmp == "\\end_deeper") {
624 //lyxerr << "\\end_deeper caught!" << endl;
626 lex.printError("\\end_deeper: "
627 "depth is already null");
632 old_float << tmp << ' ';
637 old_float << lex.getLongString("\\end_float")
638 << "\n\\end_inset\n";
639 //lyxerr << "Float Body:\n" << old_float.str() << endl;
640 // That this does not work seems like a bug
641 // in stringstream. (Lgb)
642 istringstream istr(old_float.str());
644 nylex.setStream(istr);
645 inset->read(this, nylex);
646 par->insertInset(pos, inset, font);
648 insertErtContents(par, pos);
650 } else if (token == "\\begin_deeper") {
652 } else if (token == "\\end_deeper") {
654 lex.printError("\\end_deeper: "
655 "depth is already null");
659 } else if (token == "\\begin_preamble") {
660 params.readPreamble(lex);
661 } else if (token == "\\textclass") {
663 pair<bool, textclass_type> pp =
664 textclasslist.NumberOfClass(lex.getString());
666 params.textclass = pp.second;
668 Alert::alert(string(_("Textclass error")),
669 string(_("The document uses an unknown textclass \"")) +
670 lex.getString() + string("\"."),
671 string(_("LyX will not be able to produce output correctly.")));
672 params.textclass = 0;
674 if (!textclasslist[params.textclass].load()) {
675 // if the textclass wasn't loaded properly
676 // we need to either substitute another
677 // or stop loading the file.
678 // I can substitute but I don't see how I can
679 // stop loading... ideas?? ARRae980418
680 Alert::alert(_("Textclass Loading Error!"),
681 string(_("Can't load textclass ")) +
682 textclasslist[params.textclass].name(),
683 _("-- substituting default"));
684 params.textclass = 0;
686 } else if (token == "\\options") {
688 params.options = lex.getString();
689 } else if (token == "\\language") {
690 params.readLanguage(lex);
691 } else if (token == "\\fontencoding") {
693 } else if (token == "\\inputencoding") {
695 params.inputenc = lex.getString();
696 } else if (token == "\\graphics") {
697 params.readGraphicsDriver(lex);
698 } else if (token == "\\fontscheme") {
700 params.fonts = lex.getString();
701 } else if (token == "\\noindent") {
702 par->params().noindent(true);
703 } else if (token == "\\fill_top") {
704 par->params().spaceTop(VSpace(VSpace::VFILL));
705 } else if (token == "\\fill_bottom") {
706 par->params().spaceBottom(VSpace(VSpace::VFILL));
707 } else if (token == "\\line_top") {
708 par->params().lineTop(true);
709 } else if (token == "\\line_bottom") {
710 par->params().lineBottom(true);
711 } else if (token == "\\pagebreak_top") {
712 par->params().pagebreakTop(true);
713 } else if (token == "\\pagebreak_bottom") {
714 par->params().pagebreakBottom(true);
715 } else if (token == "\\start_of_appendix") {
716 par->params().startOfAppendix(true);
717 } else if (token == "\\paragraph_separation") {
718 int tmpret = lex.findToken(string_paragraph_separation);
721 if (tmpret != LYX_LAYOUT_DEFAULT)
722 params.paragraph_separation =
723 static_cast<BufferParams::PARSEP>(tmpret);
724 } else if (token == "\\defskip") {
726 params.defskip = VSpace(lex.getString());
727 #ifndef NO_COMPABILITY
728 } else if (token == "\\epsfig") { // obsolete
729 // Indeed it is obsolete, but we HAVE to be backwards
730 // compatible until 0.14, because otherwise all figures
731 // in existing documents are irretrivably lost. (Asger)
732 params.readGraphicsDriver(lex);
734 } else if (token == "\\quotes_language") {
735 int tmpret = lex.findToken(string_quotes_language);
738 if (tmpret != LYX_LAYOUT_DEFAULT) {
739 InsetQuotes::quote_language tmpl =
740 InsetQuotes::EnglishQ;
743 tmpl = InsetQuotes::EnglishQ;
746 tmpl = InsetQuotes::SwedishQ;
749 tmpl = InsetQuotes::GermanQ;
752 tmpl = InsetQuotes::PolishQ;
755 tmpl = InsetQuotes::FrenchQ;
758 tmpl = InsetQuotes::DanishQ;
761 params.quotes_language = tmpl;
763 } else if (token == "\\quotes_times") {
765 switch (lex.getInteger()) {
767 params.quotes_times = InsetQuotes::SingleQ;
770 params.quotes_times = InsetQuotes::DoubleQ;
773 } else if (token == "\\papersize") {
774 int tmpret = lex.findToken(string_papersize);
778 params.papersize2 = tmpret;
779 } else if (token == "\\paperpackage") {
780 int tmpret = lex.findToken(string_paperpackages);
783 params.paperpackage = BufferParams::PACKAGE_NONE;
785 params.paperpackage = tmpret;
786 } else if (token == "\\use_geometry") {
788 params.use_geometry = lex.getInteger();
789 } else if (token == "\\use_amsmath") {
791 params.use_amsmath = lex.getInteger();
792 } else if (token == "\\use_natbib") {
794 params.use_natbib = lex.getInteger();
795 } else if (token == "\\use_numerical_citations") {
797 params.use_numerical_citations = lex.getInteger();
798 } else if (token == "\\paperorientation") {
799 int tmpret = lex.findToken(string_orientation);
802 if (tmpret != LYX_LAYOUT_DEFAULT)
803 params.orientation = static_cast<BufferParams::PAPER_ORIENTATION>(tmpret);
804 } else if (token == "\\paperwidth") {
806 params.paperwidth = lex.getString();
807 } else if (token == "\\paperheight") {
809 params.paperheight = lex.getString();
810 } else if (token == "\\leftmargin") {
812 params.leftmargin = lex.getString();
813 } else if (token == "\\topmargin") {
815 params.topmargin = lex.getString();
816 } else if (token == "\\rightmargin") {
818 params.rightmargin = lex.getString();
819 } else if (token == "\\bottommargin") {
821 params.bottommargin = lex.getString();
822 } else if (token == "\\headheight") {
824 params.headheight = lex.getString();
825 } else if (token == "\\headsep") {
827 params.headsep = lex.getString();
828 } else if (token == "\\footskip") {
830 params.footskip = lex.getString();
831 } else if (token == "\\paperfontsize") {
833 params.fontsize = strip(lex.getString());
834 } else if (token == "\\papercolumns") {
836 params.columns = lex.getInteger();
837 } else if (token == "\\papersides") {
839 switch (lex.getInteger()) {
841 case 1: params.sides = LyXTextClass::OneSide; break;
842 case 2: params.sides = LyXTextClass::TwoSides; break;
844 } else if (token == "\\paperpagestyle") {
846 params.pagestyle = strip(lex.getString());
847 } else if (token == "\\bullet") {
849 int const index = lex.getInteger();
851 int temp_int = lex.getInteger();
852 params.user_defined_bullets[index].setFont(temp_int);
853 params.temp_bullets[index].setFont(temp_int);
855 temp_int = lex.getInteger();
856 params.user_defined_bullets[index].setCharacter(temp_int);
857 params.temp_bullets[index].setCharacter(temp_int);
859 temp_int = lex.getInteger();
860 params.user_defined_bullets[index].setSize(temp_int);
861 params.temp_bullets[index].setSize(temp_int);
863 string const temp_str = lex.getString();
864 if (temp_str != "\\end_bullet") {
865 // this element isn't really necessary for
866 // parsing but is easier for humans
867 // to understand bullets. Put it back and
868 // set a debug message?
869 lex.printError("\\end_bullet expected, got" + temp_str);
870 //how can I put it back?
872 } else if (token == "\\bulletLaTeX") {
873 // The bullet class should be able to read this.
875 int const index = lex.getInteger();
877 string temp_str = lex.getString();
879 while (temp_str != "\\end_bullet") {
880 // this loop structure is needed when user
881 // enters an empty string since the first
882 // thing returned will be the \\end_bullet
884 // if the LaTeX entry has spaces. Each element
885 // therefore needs to be read in turn
888 temp_str = lex.getString();
891 params.user_defined_bullets[index].setText(sum_str);
892 params.temp_bullets[index].setText(sum_str);
893 } else if (token == "\\secnumdepth") {
895 params.secnumdepth = lex.getInteger();
896 } else if (token == "\\tocdepth") {
898 params.tocdepth = lex.getInteger();
899 } else if (token == "\\spacing") {
901 string const tmp = strip(lex.getString());
902 Spacing::Space tmp_space = Spacing::Default;
904 if (tmp == "single") {
905 tmp_space = Spacing::Single;
906 } else if (tmp == "onehalf") {
907 tmp_space = Spacing::Onehalf;
908 } else if (tmp == "double") {
909 tmp_space = Spacing::Double;
910 } else if (tmp == "other") {
912 tmp_space = Spacing::Other;
913 tmp_val = lex.getFloat();
915 lex.printError("Unknown spacing token: '$$Token'");
917 // Small hack so that files written with klyx will be
920 par->params().spacing(Spacing(tmp_space, tmp_val));
922 params.spacing.set(tmp_space, tmp_val);
924 } else if (token == "\\paragraph_spacing") {
926 string const tmp = strip(lex.getString());
927 if (tmp == "single") {
928 par->params().spacing(Spacing(Spacing::Single));
929 } else if (tmp == "onehalf") {
930 par->params().spacing(Spacing(Spacing::Onehalf));
931 } else if (tmp == "double") {
932 par->params().spacing(Spacing(Spacing::Double));
933 } else if (tmp == "other") {
935 par->params().spacing(Spacing(Spacing::Other,
938 lex.printError("Unknown spacing token: '$$Token'");
940 } else if (token == "\\float_placement") {
942 params.float_placement = lex.getString();
943 } else if (token == "\\family") {
945 font.setLyXFamily(lex.getString());
946 } else if (token == "\\series") {
948 font.setLyXSeries(lex.getString());
949 } else if (token == "\\shape") {
951 font.setLyXShape(lex.getString());
952 } else if (token == "\\size") {
954 font.setLyXSize(lex.getString());
955 #ifndef NO_COMPABILITY
956 } else if (token == "\\latex") {
958 string const tok = lex.getString();
959 if (tok == "no_latex") {
961 insertErtContents(par, pos);
962 } else if (tok == "latex") {
963 ert_comp.active = true;
964 ert_comp.font = font;
965 } else if (tok == "default") {
967 insertErtContents(par, pos);
969 lex.printError("Unknown LaTeX font flag "
973 } else if (token == "\\lang") {
975 string const tok = lex.getString();
976 Language const * lang = languages.getLanguage(tok);
978 font.setLanguage(lang);
980 font.setLanguage(params.language);
981 lex.printError("Unknown language `$$Token'");
983 } else if (token == "\\numeric") {
985 font.setNumber(font.setLyXMisc(lex.getString()));
986 } else if (token == "\\emph") {
988 font.setEmph(font.setLyXMisc(lex.getString()));
989 } else if (token == "\\bar") {
991 string const tok = lex.getString();
992 // This is dirty, but gone with LyX3. (Asger)
994 font.setUnderbar(LyXFont::ON);
995 else if (tok == "no")
996 font.setUnderbar(LyXFont::OFF);
997 else if (tok == "default")
998 font.setUnderbar(LyXFont::INHERIT);
1000 lex.printError("Unknown bar font flag "
1002 } else if (token == "\\noun") {
1004 font.setNoun(font.setLyXMisc(lex.getString()));
1005 } else if (token == "\\color") {
1007 font.setLyXColor(lex.getString());
1008 } else if (token == "\\align") {
1009 int tmpret = lex.findToken(string_align);
1010 if (tmpret == -1) ++tmpret;
1011 if (tmpret != LYX_LAYOUT_DEFAULT) { // tmpret != 99 ???
1012 int const tmpret2 = int(pow(2.0, tmpret));
1013 //lyxerr << "Tmpret2 = " << tmpret2 << endl;
1014 par->params().align(LyXAlignment(tmpret2));
1016 } else if (token == "\\added_space_top") {
1018 VSpace value = VSpace(lex.getString());
1019 if ((value.length().len().value() != 0) ||
1020 (value.kind() != VSpace::LENGTH))
1021 par->params().spaceTop(value);
1022 } else if (token == "\\added_space_bottom") {
1024 VSpace value = VSpace(lex.getString());
1025 if ((value.length().len().value() != 0) ||
1026 (value.kind() != VSpace::LENGTH))
1027 par->params().spaceBottom(value);
1028 #ifndef NO_COMPABILITY
1029 #ifndef NO_PEXTRA_REALLY
1030 } else if (token == "\\pextra_type") {
1032 par->params().pextraType(lex.getInteger());
1033 } else if (token == "\\pextra_width") {
1035 par->params().pextraWidth(lex.getString());
1036 } else if (token == "\\pextra_widthp") {
1038 par->params().pextraWidthp(lex.getString());
1039 } else if (token == "\\pextra_alignment") {
1041 par->params().pextraAlignment(lex.getInteger());
1042 } else if (token == "\\pextra_hfill") {
1044 par->params().pextraHfill(lex.getInteger());
1045 } else if (token == "\\pextra_start_minipage") {
1047 par->params().pextraStartMinipage(lex.getInteger());
1050 } else if (token == "\\labelwidthstring") {
1052 par->params().labelWidthString(lex.getString());
1053 // do not delete this token, it is still needed!
1054 } else if (token == "\\end_inset") {
1055 lyxerr << "Solitary \\end_inset. Missing \\begin_inset?.\n"
1056 << "Last inset read was: " << last_inset_read
1058 // Simply ignore this. The insets do not have
1060 // But insets should read it, it is a part of
1061 // the inset isn't it? Lgb.
1062 } else if (token == "\\begin_inset") {
1063 #ifndef NO_COMPABILITY
1064 insertErtContents(par, pos, false);
1065 ert_stack.push(ert_comp);
1066 ert_comp = ErtComp();
1068 readInset(lex, par, pos, font);
1069 #ifndef NO_COMPABILITY
1070 ert_comp = ert_stack.top();
1072 insertErtContents(par, pos);
1074 } else if (token == "\\SpecialChar") {
1075 LyXLayout const & layout =
1076 textclasslist[params.textclass][par->layout()];
1078 // Insets don't make sense in a free-spacing context! ---Kayvan
1079 if (layout.free_spacing || par->isFreeSpacing()) {
1082 string next_token = lex.getString();
1083 if (next_token == "\\-") {
1084 par->insertChar(pos, '-', font);
1085 } else if (next_token == "\\protected_separator"
1086 || next_token == "~") {
1087 par->insertChar(pos, ' ', font);
1089 lex.printError("Token `$$Token' "
1091 "paragraph layout!");
1096 Inset * inset = new InsetSpecialChar;
1097 inset->read(this, lex);
1098 par->insertInset(pos, inset, font);
1101 } else if (token == "\\newline") {
1102 #ifndef NO_COMPABILITY
1103 if (!ert_comp.in_tabular && ert_comp.active) {
1104 ert_comp.contents += char(Paragraph::META_NEWLINE);
1106 // Since we cannot know it this is only a regular
1107 // newline or a tabular cell delimter we have to
1108 // handle the ERT here.
1109 insertErtContents(par, pos, false);
1111 par->insertChar(pos, Paragraph::META_NEWLINE, font);
1115 par->insertChar(pos, Paragraph::META_NEWLINE, font);
1118 } else if (token == "\\LyXTable") {
1119 #ifndef NO_COMPABILITY
1120 ert_comp.in_tabular = true;
1122 Inset * inset = new InsetTabular(*this);
1123 inset->read(this, lex);
1124 par->insertInset(pos, inset, font);
1126 } else if (token == "\\hfill") {
1127 par->insertChar(pos, Paragraph::META_HFILL, font);
1129 } else if (token == "\\protected_separator") { // obsolete
1130 // This is a backward compability thingie. (Lgb)
1131 // Remove it later some time...introduced with fileformat
1133 LyXLayout const & layout =
1134 textclasslist[params.textclass][par->layout()];
1136 if (layout.free_spacing || par->isFreeSpacing()) {
1137 par->insertChar(pos, ' ', font);
1139 Inset * inset = new InsetSpecialChar(InsetSpecialChar::PROTECTED_SEPARATOR);
1140 par->insertInset(pos, inset, font);
1143 } else if (token == "\\bibitem") { // ale970302
1145 InsetCommandParams p("bibitem", "dummy");
1146 par->bibkey = new InsetBibKey(p);
1148 par->bibkey->read(this, lex);
1149 } else if (token == "\\backslash") {
1150 #ifndef NO_COMPABILITY
1151 if (ert_comp.active) {
1152 ert_comp.contents += "\\";
1155 par->insertChar(pos, '\\', font);
1157 #ifndef NO_COMPABILITY
1160 } else if (token == "\\the_end") {
1161 #ifndef NO_COMPABILITY
1162 // If we still have some ert active here we have to insert
1163 // it so we don't loose it. (Lgb)
1164 insertErtContents(par, pos);
1166 the_end_read = true;
1167 #ifndef NO_COMPABILITY
1168 #ifndef NO_PEXTRA_REALLY
1169 minipar = parBeforeMinipage = 0;
1173 #ifndef NO_COMPABILITY
1174 if (ert_comp.active) {
1175 ert_comp.contents += token;
1178 // This should be insurance for the future: (Asger)
1181 string const s = _("Unknown token: ") + token
1182 + " " + lex.text() + "\n";
1184 InsetError * new_inset = new InsetError(s);
1185 par->insertInset(pos, new_inset, LyXFont(LyXFont::ALL_INHERIT,
1188 #ifndef NO_COMPABILITY
1193 #ifndef NO_COMPABILITY
1194 #ifndef NO_PEXTRA_REALLY
1195 // I wonder if we could use this blanket fix for all the
1196 // checkminipage cases...
1197 // don't forget about ert paragraphs and compatibility read for'em
1198 if (par && (par->size() || !ert_comp.contents.empty())) {
1199 // It is possible that this will check to often,
1200 // but that should not be an correctness issue.
1201 // Only a speed issue.
1202 checkminipage = true;
1205 // now check if we have a minipage paragraph as at this
1206 // point we already read all the necessary data!
1207 // this cannot be done in layout because there we did
1208 // not read yet the paragraph PEXTRA-params (Jug)
1210 // BEGIN pextra_minipage compability
1211 // This should be removed in 1.3.x (Lgb)
1212 // I don't think we should remove this so fast (Jug)
1214 // This compability code is not perfect. In a couple
1215 // of rand cases it fails. When the minipage par is
1216 // the first par in the document, and when there are
1217 // none or only one regular paragraphs after the
1218 // minipage. Currently I am not investing any effort
1219 // in fixing those cases.
1221 //lyxerr << "Call depth: " << call_depth << endl;
1222 if (checkminipage && (call_depth == 1)) {
1223 checkminipage = false;
1224 if (minipar && (minipar != par) &&
1225 (par->params().pextraType() == Paragraph::PEXTRA_MINIPAGE)) {
1226 lyxerr << "minipages in a row" << endl;
1227 if (par->params().pextraStartMinipage()) {
1228 lyxerr << "start new minipage" << endl;
1229 // minipages in a row
1230 par->previous()->next(0);
1233 Paragraph * tmp = minipar;
1235 tmp->params().pextraType(0);
1236 tmp->params().pextraWidth(string());
1237 tmp->params().pextraWidthp(string());
1238 tmp->params().pextraAlignment(0);
1239 tmp->params().pextraHfill(false);
1240 tmp->params().pextraStartMinipage(false);
1243 // create a new paragraph to insert the
1244 // minipages in the following case
1245 if (par->params().pextraStartMinipage() &&
1246 !par->params().pextraHfill()) {
1247 Paragraph * p = new Paragraph;
1248 p->layout(textclasslist[params.textclass].defaultLayoutName());
1250 p->previous(parBeforeMinipage);
1251 parBeforeMinipage->next(p);
1253 p->params().depth(parBeforeMinipage->params().depth());
1254 parBeforeMinipage = p;
1256 InsetMinipage * mini = new InsetMinipage(params);
1257 mini->pos(static_cast<InsetMinipage::Position>(par->params().pextraAlignment()));
1258 mini->pageWidth(LyXLength(par->params().pextraWidth()));
1259 if (!par->params().pextraWidthp().empty()) {
1260 lyxerr << "WP:" << mini->pageWidth().asString() << endl;
1261 mini->pageWidth(LyXLength((par->params().pextraWidthp())+"%"));
1263 Paragraph * op = mini->firstParagraph();
1264 mini->inset.paragraph(par);
1266 // and free the old ones!
1269 Paragraph * pp = op->next();
1273 // Insert the minipage last in the
1274 // previous paragraph.
1275 if (par->params().pextraHfill()) {
1276 parBeforeMinipage->insertChar
1277 (parBeforeMinipage->size(), Paragraph::META_HFILL);
1279 parBeforeMinipage->insertInset
1280 (parBeforeMinipage->size(), mini);
1284 lyxerr << "new minipage par" << endl;
1285 //nothing to do just continue reading
1288 } else if (minipar && (minipar != par)) {
1289 lyxerr << "last minipage par read" << endl;
1290 // The last paragraph read was not part of a
1291 // minipage but the par linked list is...
1292 // So we need to remove the last par from the
1294 if (par->previous())
1295 par->previous()->next(0);
1296 par->previous(parBeforeMinipage);
1297 parBeforeMinipage->next(par);
1298 Paragraph * tmp = minipar;
1300 tmp->params().pextraType(0);
1301 tmp->params().pextraWidth(string());
1302 tmp->params().pextraWidthp(string());
1303 tmp->params().pextraAlignment(0);
1304 tmp->params().pextraHfill(false);
1305 tmp->params().pextraStartMinipage(false);
1308 depth = parBeforeMinipage->params().depth();
1309 // and set this depth on the par as it has not been set already
1310 par->params().depth(depth);
1311 minipar = parBeforeMinipage = 0;
1312 } else if (!minipar &&
1313 (par->params().pextraType() == Paragraph::PEXTRA_MINIPAGE))
1315 // par is the first paragraph in a minipage
1316 lyxerr << "begin minipage" << endl;
1317 // To minimize problems for
1318 // the users we will insert
1319 // the first minipage in
1320 // a sequence of minipages
1321 // in its own paragraph.
1322 Paragraph * p = new Paragraph;
1323 p->layout(textclasslist[params.textclass].defaultLayoutName());
1324 p->previous(par->previous());
1326 p->params().depth(depth);
1327 par->params().depth(0);
1329 if (par->previous())
1330 par->previous()->next(p);
1332 parBeforeMinipage = p;
1334 if (!first_par || (first_par == par))
1337 InsetMinipage * mini = new InsetMinipage(params);
1338 mini->pos(static_cast<InsetMinipage::Position>(minipar->params().pextraAlignment()));
1339 mini->pageWidth(LyXLength(minipar->params().pextraWidth()));
1340 if (!par->params().pextraWidthp().empty()) {
1341 lyxerr << "WP:" << mini->pageWidth().asString() << endl;
1342 mini->pageWidth(LyXLength((par->params().pextraWidthp())+"%"));
1344 mini->inset.paragraph(minipar);
1346 // Insert the minipage last in the
1347 // previous paragraph.
1348 if (minipar->params().pextraHfill()) {
1349 parBeforeMinipage->insertChar
1350 (parBeforeMinipage->size(),Paragraph::META_HFILL);
1352 parBeforeMinipage->insertInset
1353 (parBeforeMinipage->size(), mini);
1356 // End of pextra_minipage compability
1360 return the_end_read;
1363 // needed to insert the selection
1364 void Buffer::insertStringAsLines(Paragraph *& par, pos_type & pos,
1365 LyXFont const & fn,string const & str) const
1367 LyXLayout const & layout =
1368 textclasslist[params.textclass][par->layout()];
1371 par->checkInsertChar(font);
1372 // insert the string, don't insert doublespace
1373 bool space_inserted = true;
1374 for(string::const_iterator cit = str.begin();
1375 cit != str.end(); ++cit) {
1377 if (par->size() || layout.keepempty) {
1378 par->breakParagraph(params, pos,
1379 layout.isEnvironment());
1382 space_inserted = true;
1386 // do not insert consecutive spaces if !free_spacing
1387 } else if ((*cit == ' ' || *cit == '\t') &&
1388 space_inserted && !layout.free_spacing &&
1389 !par->isFreeSpacing())
1392 } else if (*cit == '\t') {
1393 if (!layout.free_spacing && !par->isFreeSpacing()) {
1394 // tabs are like spaces here
1395 par->insertChar(pos, ' ', font);
1397 space_inserted = true;
1399 const pos_type nb = 8 - pos % 8;
1400 for (pos_type a = 0; a < nb ; ++a) {
1401 par->insertChar(pos, ' ', font);
1404 space_inserted = true;
1406 } else if (!IsPrintable(*cit)) {
1407 // Ignore unprintables
1410 // just insert the character
1411 par->insertChar(pos, *cit, font);
1413 space_inserted = (*cit == ' ');
1420 void Buffer::readInset(LyXLex & lex, Paragraph *& par,
1421 int & pos, LyXFont & font)
1423 // consistency check
1424 if (lex.getString() != "\\begin_inset") {
1425 lyxerr << "Buffer::readInset: Consistency check failed."
1432 string const tmptok = lex.getString();
1433 last_inset_read = tmptok;
1435 // test the different insets
1436 if (tmptok == "LatexCommand") {
1437 InsetCommandParams inscmd;
1440 string const cmdName = inscmd.getCmdName();
1442 // This strange command allows LyX to recognize "natbib" style
1443 // citations: citet, citep, Citet etc.
1444 if (compare_no_case(cmdName, "cite", 4) == 0) {
1445 inset = new InsetCitation(inscmd);
1446 } else if (cmdName == "bibitem") {
1447 lex.printError("Wrong place for bibitem");
1448 inset = new InsetBibKey(inscmd);
1449 } else if (cmdName == "BibTeX") {
1450 inset = new InsetBibtex(inscmd);
1451 } else if (cmdName == "index") {
1452 inset = new InsetIndex(inscmd);
1453 } else if (cmdName == "include") {
1454 inset = new InsetInclude(inscmd, *this);
1455 } else if (cmdName == "label") {
1456 inset = new InsetLabel(inscmd);
1457 } else if (cmdName == "url"
1458 || cmdName == "htmlurl") {
1459 inset = new InsetUrl(inscmd);
1460 } else if (cmdName == "ref"
1461 || cmdName == "pageref"
1462 || cmdName == "vref"
1463 || cmdName == "vpageref"
1464 || cmdName == "prettyref") {
1465 if (!inscmd.getOptions().empty()
1466 || !inscmd.getContents().empty()) {
1467 inset = new InsetRef(inscmd, *this);
1469 } else if (cmdName == "tableofcontents") {
1470 inset = new InsetTOC(inscmd);
1471 } else if (cmdName == "listofalgorithms") {
1472 inset = new InsetFloatList("algorithm");
1473 } else if (cmdName == "listoffigures") {
1474 inset = new InsetFloatList("figure");
1475 } else if (cmdName == "listoftables") {
1476 inset = new InsetFloatList("table");
1477 } else if (cmdName == "printindex") {
1478 inset = new InsetPrintIndex(inscmd);
1479 } else if (cmdName == "lyxparent") {
1480 inset = new InsetParent(inscmd, *this);
1483 bool alreadyread = false;
1484 if (tmptok == "Quotes") {
1485 inset = new InsetQuotes;
1486 } else if (tmptok == "External") {
1487 inset = new InsetExternal;
1488 } else if (tmptok == "FormulaMacro") {
1489 inset = new InsetFormulaMacro;
1490 } else if (tmptok == "Formula") {
1491 inset = new InsetFormula;
1492 } else if (tmptok == "Figure") { // Backward compatibility
1493 // inset = new InsetFig(100, 100, *this);
1494 inset = new InsetGraphics;
1495 } else if (tmptok == "Graphics") {
1496 inset = new InsetGraphics;
1497 } else if (tmptok == "Info") {// backwards compatibility
1498 inset = new InsetNote(this,
1499 lex.getLongString("\\end_inset"),
1502 } else if (tmptok == "Note") {
1503 inset = new InsetNote(params);
1504 } else if (tmptok == "Include") {
1505 InsetCommandParams p("Include");
1506 inset = new InsetInclude(p, *this);
1507 } else if (tmptok == "ERT") {
1508 inset = new InsetERT(params);
1509 } else if (tmptok == "Tabular") {
1510 inset = new InsetTabular(*this);
1511 } else if (tmptok == "Text") {
1512 inset = new InsetText(params);
1513 } else if (tmptok == "Foot") {
1514 inset = new InsetFoot(params);
1515 } else if (tmptok == "Marginal") {
1516 inset = new InsetMarginal(params);
1517 } else if (tmptok == "Minipage") {
1518 inset = new InsetMinipage(params);
1519 } else if (tmptok == "Float") {
1521 string tmptok = lex.getString();
1522 inset = new InsetFloat(params, tmptok);
1524 } else if (tmptok == "List") {
1525 inset = new InsetList;
1526 } else if (tmptok == "Theorem") {
1527 inset = new InsetList;
1529 } else if (tmptok == "Caption") {
1530 inset = new InsetCaption(params);
1531 } else if (tmptok == "FloatList") {
1532 inset = new InsetFloatList;
1535 if (inset && !alreadyread) inset->read(this, lex);
1539 par->insertInset(pos, inset, font);
1545 bool Buffer::readFile(LyXLex & lex, Paragraph * par)
1549 string const token(lex.getString());
1550 if (token == "\\lyxformat") { // the first token _must_ be...
1552 string tmp_format = lex.getString();
1553 //lyxerr << "LyX Format: `" << tmp_format << "'" << endl;
1554 // if present remove ".," from string.
1555 string::size_type dot = tmp_format.find_first_of(".,");
1556 //lyxerr << " dot found at " << dot << endl;
1557 if (dot != string::npos)
1558 tmp_format.erase(dot, 1);
1559 file_format = strToInt(tmp_format);
1560 if (file_format == LYX_FORMAT) {
1562 } else if (file_format > LYX_FORMAT) {
1564 Alert::alert(_("Warning!"),
1565 _("LyX file format is newer that what"),
1566 _("is supported in this LyX version. Expect some problems."));
1568 } else if (file_format < LYX_FORMAT) {
1570 if (file_format < 200) {
1571 Alert::alert(_("ERROR!"),
1572 _("Old LyX file format found. "
1573 "Use LyX 0.10.x to read this!"));
1577 bool the_end = readLyXformat2(lex, par);
1578 params.setPaperStuff();
1579 // the_end was added in 213
1580 if (file_format < 213)
1584 Alert::alert(_("Warning!"),
1585 _("Reading of document is not complete"),
1586 _("Maybe the document is truncated"));
1589 } else { // "\\lyxformat" not found
1590 Alert::alert(_("ERROR!"), _("Not a LyX file!"));
1593 Alert::alert(_("ERROR!"), _("Unable to read file!"));
1598 // Should probably be moved to somewhere else: BufferView? LyXView?
1599 bool Buffer::save() const
1601 // We don't need autosaves in the immediate future. (Asger)
1602 resetAutosaveTimers();
1606 if (lyxrc.make_backup) {
1607 s = fileName() + '~';
1608 if (!lyxrc.backupdir_path.empty())
1609 s = AddName(lyxrc.backupdir_path,
1610 subst(os::slashify_path(s),'/','!'));
1612 // Rename is the wrong way of making a backup,
1613 // this is the correct way.
1614 /* truss cp fil fil2:
1615 lstat("LyXVC3.lyx", 0xEFFFF898) Err#2 ENOENT
1616 stat("LyXVC.lyx", 0xEFFFF688) = 0
1617 open("LyXVC.lyx", O_RDONLY) = 3
1618 open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
1619 fstat(4, 0xEFFFF508) = 0
1620 fstat(3, 0xEFFFF508) = 0
1621 read(3, " # T h i s f i l e w".., 8192) = 5579
1622 write(4, " # T h i s f i l e w".., 5579) = 5579
1623 read(3, 0xEFFFD4A0, 8192) = 0
1626 chmod("LyXVC3.lyx", 0100644) = 0
1627 lseek(0, 0, SEEK_CUR) = 46440
1631 // Should probably have some more error checking here.
1632 // Should be cleaned up in 0.13, at least a bit.
1633 // Doing it this way, also makes the inodes stay the same.
1634 // This is still not a very good solution, in particular we
1635 // might loose the owner of the backup.
1636 FileInfo finfo(fileName());
1637 if (finfo.exist()) {
1638 mode_t fmode = finfo.getMode();
1639 struct utimbuf times = {
1640 finfo.getAccessTime(),
1641 finfo.getModificationTime() };
1643 ifstream ifs(fileName().c_str());
1644 ofstream ofs(s.c_str(), ios::out|ios::trunc);
1649 ::chmod(s.c_str(), fmode);
1651 if (::utime(s.c_str(), ×)) {
1652 lyxerr << "utime error." << endl;
1655 lyxerr << "LyX was not able to make "
1656 "backup copy. Beware." << endl;
1661 if (writeFile(fileName(), false)) {
1663 removeAutosaveFile(fileName());
1665 // Saving failed, so backup is not backup
1666 if (lyxrc.make_backup) {
1667 lyx::rename(s, fileName());
1675 // Returns false if unsuccesful
1676 bool Buffer::writeFile(string const & fname, bool flag) const
1678 // if flag is false writeFile will not create any GUI
1679 // warnings, only cerr.
1680 // Needed for autosave in background or panic save (Matthias 120496)
1682 if (read_only && (fname == fileName())) {
1683 // Here we should come with a question if we should
1684 // perform the write anyway.
1686 lyxerr << _("Error! Document is read-only: ")
1689 Alert::alert(_("Error! Document is read-only: "),
1694 FileInfo finfo(fname);
1695 if (finfo.exist() && !finfo.writable()) {
1696 // Here we should come with a question if we should
1697 // try to do the save anyway. (i.e. do a chmod first)
1699 lyxerr << _("Error! Cannot write file: ")
1702 Alert::err_alert(_("Error! Cannot write file: "),
1707 ofstream ofs(fname.c_str());
1710 lyxerr << _("Error! Cannot open file: ")
1713 Alert::err_alert(_("Error! Cannot open file: "),
1719 // Use the standard "C" locale for file output.
1720 ofs.imbue(std::locale::classic());
1723 // The top of the file should not be written by params.
1725 // write out a comment in the top of the file
1726 ofs << '#' << lyx_docversion
1727 << " created this file. For more info see http://www.lyx.org/\n"
1728 << "\\lyxformat " << LYX_FORMAT << "\n";
1730 // now write out the buffer paramters.
1731 params.writeFile(ofs);
1733 Paragraph::depth_type depth = 0;
1735 // this will write out all the paragraphs
1736 // using recursive descent.
1737 paragraph->writeFile(this, ofs, params, depth);
1739 // Write marker that shows file is complete
1740 ofs << "\n\\the_end" << endl;
1744 // how to check if close went ok?
1745 // Following is an attempt... (BE 20001011)
1747 // good() returns false if any error occured, including some
1748 // formatting error.
1749 // bad() returns true if something bad happened in the buffer,
1750 // which should include file system full errors.
1757 lyxerr << "Buffer::writeFile: BAD ERROR!" << endl;
1759 lyxerr << "Buffer::writeFile: NOT SO BAD ERROR!"
1769 string const Buffer::asciiParagraph(Paragraph const * par,
1770 unsigned int linelen,
1771 bool noparbreak) const
1773 ostringstream buffer;
1775 Paragraph::depth_type depth = 0;
1777 Paragraph::depth_type ltype_depth = 0;
1778 string::size_type currlinelen = 0;
1779 bool ref_printed = false;
1780 // if (!par->previous()) {
1782 // begins or ends a deeper area ?
1783 if (depth != par->params().depth()) {
1784 if (par->params().depth() > depth) {
1785 while (par->params().depth() > depth) {
1789 while (par->params().depth() < depth) {
1795 depth = par->params().depth();
1798 // First write the layout
1799 string const & tmp = par->layout();
1800 if (compare_no_case(tmp, "itemize") == 0) {
1802 ltype_depth = depth + 1;
1803 } else if (compare_no_case(tmp, "enumerate") == 0) {
1805 ltype_depth = depth + 1;
1806 } else if (contains(lowercase(tmp), "ection")) {
1808 ltype_depth = depth + 1;
1809 } else if (contains(lowercase(tmp), "aragraph")) {
1811 ltype_depth = depth + 1;
1812 } else if (compare_no_case(tmp, "description") == 0) {
1814 ltype_depth = depth + 1;
1815 } else if (compare_no_case(tmp, "abstract") == 0) {
1818 } else if (compare_no_case(tmp, "bibliography") == 0) {
1826 /* maybe some vertical spaces */
1828 /* the labelwidthstring used in lists */
1832 /* some pagebreaks? */
1836 /* what about the alignment */
1838 // lyxerr << "Should this ever happen?" << endl;
1841 // linelen <= 0 is special and means we don't have pargraph breaks
1845 for (Paragraph::depth_type j = 0; j < depth; ++j)
1847 currlinelen = depth * 2;
1849 // we should probably change to the paragraph language in the
1850 // gettext here (if possible) so that strings are outputted in
1851 // the correct language! (20012712 Jug)
1855 case 4: // (Sub)Paragraph
1856 case 5: // Description
1860 buffer << _("Abstract") << "\n\n";
1862 buffer << _("Abstract: ");
1864 case 7: // Bibliography
1867 buffer << _("References") << "\n\n";
1869 buffer << _("References: ");
1874 buffer << par->params().labelString() << " ";
1878 string s = buffer.str();
1879 if (s.rfind('\n') != string::npos) {
1881 s = rsplit(buffer.str().c_str(), dummy, '\n');
1883 currlinelen = s.length();
1885 for (Paragraph::depth_type j = 0; j < depth; ++j)
1887 currlinelen = depth * 2;
1888 if (ltype_depth > depth) {
1889 for (Paragraph::depth_type j = ltype_depth;
1894 currlinelen += (ltype_depth-depth)*2;
1897 // this is to change the linebreak to do it by word a bit more intelligent
1898 // hopefully! (only in the case where we have a max linelenght!) (Jug)
1899 for (pos_type i = 0; i < par->size(); ++i) {
1900 char c = par->getUChar(params, i);
1902 case Paragraph::META_INSET:
1904 Inset const * inset = par->getInset(i);
1907 buffer << word.str();
1910 if (inset->ascii(this, buffer, linelen)) {
1911 // to be sure it breaks paragraph
1912 currlinelen += linelen;
1918 rsplit(buffer.str().c_str(),
1920 currlinelen = s.length();
1927 case Paragraph::META_NEWLINE:
1929 buffer << word.str() << "\n";
1931 for (Paragraph::depth_type j = 0;
1934 currlinelen = depth * 2;
1935 if (ltype_depth > depth) {
1936 for (Paragraph::depth_type j = ltype_depth;
1939 currlinelen += (ltype_depth - depth) * 2;
1944 case Paragraph::META_HFILL:
1945 buffer << word.str() << "\t";
1946 currlinelen += word.str().length() + 1;
1952 buffer << word.str() << ' ';
1953 currlinelen += word.str().length() + 1;
1959 lyxerr[Debug::INFO] <<
1960 "writeAsciiFile: NULL char in structure." << endl;
1962 if ((linelen > 0) &&
1963 (currlinelen+word.str().length()) > linelen)
1966 for (Paragraph::depth_type j = 0; j < depth; ++j)
1968 currlinelen = depth * 2;
1969 if (ltype_depth > depth) {
1970 for (Paragraph::depth_type j = ltype_depth;
1975 currlinelen += (ltype_depth-depth)*2;
1982 buffer << word.str();
1983 return buffer.str().c_str();
1987 void Buffer::writeFileAscii(string const & fname, int linelen)
1989 ofstream ofs(fname.c_str());
1991 Alert::err_alert(_("Error: Cannot write file:"), fname);
1994 writeFileAscii(ofs, linelen);
1998 void Buffer::writeFileAscii(ostream & ofs, int linelen)
2000 Paragraph * par = paragraph;
2002 ofs << asciiParagraph(par, linelen, par->previous() == 0);
2012 void Buffer::makeLaTeXFile(string const & fname,
2013 string const & original_path,
2014 bool nice, bool only_body)
2016 lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
2018 niceFile = nice; // this will be used by Insetincludes.
2020 tex_code_break_column = lyxrc.ascii_linelen;
2022 ofstream ofs(fname.c_str());
2024 Alert::err_alert(_("Error: Cannot open file: "), fname);
2028 // validate the buffer.
2029 lyxerr[Debug::LATEX] << " Validating buffer..." << endl;
2030 LaTeXFeatures features(params);
2032 lyxerr[Debug::LATEX] << " Buffer validation done." << endl;
2035 // The starting paragraph of the coming rows is the
2036 // first paragraph of the document. (Asger)
2037 texrow.start(paragraph, 0);
2039 if (!only_body && nice) {
2040 ofs << "%% " << lyx_docversion << " created this file. "
2041 "For more info, see http://www.lyx.org/.\n"
2042 "%% Do not edit unless you really know what "
2047 lyxerr[Debug::INFO] << "lyx header finished" << endl;
2048 // There are a few differences between nice LaTeX and usual files:
2049 // usual is \batchmode and has a
2050 // special input@path to allow the including of figures
2051 // with either \input or \includegraphics (what figinsets do).
2052 // batchmode is not set if there is a tex_code_break_column.
2053 // In this case somebody is interested in the generated LaTeX,
2054 // so this is OK. input@path is set when the actual parameter
2055 // original_path is set. This is done for usual tex-file, but not
2056 // for nice-latex-file. (Matthias 250696)
2059 // code for usual, NOT nice-latex-file
2060 ofs << "\\batchmode\n"; // changed
2061 // from \nonstopmode
2064 if (!original_path.empty()) {
2065 ofs << "\\makeatletter\n"
2066 << "\\def\\input@path{{"
2067 << os::external_path(original_path) << "/}}\n"
2068 << "\\makeatother\n";
2074 ofs << "\\documentclass";
2076 LyXTextClass const & tclass = textclasslist[params.textclass];
2078 ostringstream options; // the document class options.
2080 if (tokenPos(tclass.opt_fontsize(),
2081 '|', params.fontsize) >= 0) {
2082 // only write if existing in list (and not default)
2083 options << params.fontsize << "pt,";
2087 if (!params.use_geometry &&
2088 (params.paperpackage == BufferParams::PACKAGE_NONE)) {
2089 switch (params.papersize) {
2090 case BufferParams::PAPER_A4PAPER:
2091 options << "a4paper,";
2093 case BufferParams::PAPER_USLETTER:
2094 options << "letterpaper,";
2096 case BufferParams::PAPER_A5PAPER:
2097 options << "a5paper,";
2099 case BufferParams::PAPER_B5PAPER:
2100 options << "b5paper,";
2102 case BufferParams::PAPER_EXECUTIVEPAPER:
2103 options << "executivepaper,";
2105 case BufferParams::PAPER_LEGALPAPER:
2106 options << "legalpaper,";
2112 if (params.sides != tclass.sides()) {
2113 switch (params.sides) {
2114 case LyXTextClass::OneSide:
2115 options << "oneside,";
2117 case LyXTextClass::TwoSides:
2118 options << "twoside,";
2124 if (params.columns != tclass.columns()) {
2125 if (params.columns == 2)
2126 options << "twocolumn,";
2128 options << "onecolumn,";
2131 if (!params.use_geometry
2132 && params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
2133 options << "landscape,";
2135 // language should be a parameter to \documentclass
2137 ostringstream language_options;
2138 if (params.language->babel() == "hebrew"
2139 && default_language->babel() != "hebrew")
2140 // This seems necessary
2141 features.useLanguage(default_language);
2143 if (lyxrc.language_use_babel ||
2144 params.language->lang() != lyxrc.default_language ||
2145 !features.hasLanguages()) {
2147 language_options << features.getLanguages();
2148 language_options << params.language->babel();
2149 if (lyxrc.language_global_options)
2150 options << language_options.str() << ',';
2153 // the user-defined options
2154 if (!params.options.empty()) {
2155 options << params.options << ',';
2158 string strOptions(options.str().c_str());
2159 if (!strOptions.empty()) {
2160 strOptions = strip(strOptions, ',');
2161 ofs << '[' << strOptions << ']';
2164 ofs << '{' << tclass.latexname() << "}\n";
2166 // end of \documentclass defs
2168 // font selection must be done before loading fontenc.sty
2169 // The ae package is not needed when using OT1 font encoding.
2170 if (params.fonts != "default" &&
2171 (params.fonts != "ae" || lyxrc.fontenc != "default")) {
2172 ofs << "\\usepackage{" << params.fonts << "}\n";
2174 if (params.fonts == "ae") {
2175 ofs << "\\usepackage{aecompl}\n";
2179 // this one is not per buffer
2180 if (lyxrc.fontenc != "default") {
2181 ofs << "\\usepackage[" << lyxrc.fontenc
2186 if (params.inputenc == "auto") {
2187 string const doc_encoding =
2188 params.language->encoding()->LatexName();
2190 // Create a list with all the input encodings used
2192 set<string> encodings = features.getEncodingSet(doc_encoding);
2194 ofs << "\\usepackage[";
2195 std::copy(encodings.begin(), encodings.end(),
2196 std::ostream_iterator<string>(ofs, ","));
2197 ofs << doc_encoding << "]{inputenc}\n";
2199 } else if (params.inputenc != "default") {
2200 ofs << "\\usepackage[" << params.inputenc
2205 // At the very beginning the text parameters.
2206 if (params.paperpackage != BufferParams::PACKAGE_NONE) {
2207 switch (params.paperpackage) {
2208 case BufferParams::PACKAGE_A4:
2209 ofs << "\\usepackage{a4}\n";
2212 case BufferParams::PACKAGE_A4WIDE:
2213 ofs << "\\usepackage{a4wide}\n";
2216 case BufferParams::PACKAGE_WIDEMARGINSA4:
2217 ofs << "\\usepackage[widemargins]{a4}\n";
2222 if (params.use_geometry) {
2223 ofs << "\\usepackage{geometry}\n";
2225 ofs << "\\geometry{verbose";
2226 if (params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
2227 ofs << ",landscape";
2228 switch (params.papersize2) {
2229 case BufferParams::VM_PAPER_CUSTOM:
2230 if (!params.paperwidth.empty())
2231 ofs << ",paperwidth="
2232 << params.paperwidth;
2233 if (!params.paperheight.empty())
2234 ofs << ",paperheight="
2235 << params.paperheight;
2237 case BufferParams::VM_PAPER_USLETTER:
2238 ofs << ",letterpaper";
2240 case BufferParams::VM_PAPER_USLEGAL:
2241 ofs << ",legalpaper";
2243 case BufferParams::VM_PAPER_USEXECUTIVE:
2244 ofs << ",executivepaper";
2246 case BufferParams::VM_PAPER_A3:
2249 case BufferParams::VM_PAPER_A4:
2252 case BufferParams::VM_PAPER_A5:
2255 case BufferParams::VM_PAPER_B3:
2258 case BufferParams::VM_PAPER_B4:
2261 case BufferParams::VM_PAPER_B5:
2265 // default papersize ie BufferParams::VM_PAPER_DEFAULT
2266 switch (lyxrc.default_papersize) {
2267 case BufferParams::PAPER_DEFAULT: // keep compiler happy
2268 case BufferParams::PAPER_USLETTER:
2269 ofs << ",letterpaper";
2271 case BufferParams::PAPER_LEGALPAPER:
2272 ofs << ",legalpaper";
2274 case BufferParams::PAPER_EXECUTIVEPAPER:
2275 ofs << ",executivepaper";
2277 case BufferParams::PAPER_A3PAPER:
2280 case BufferParams::PAPER_A4PAPER:
2283 case BufferParams::PAPER_A5PAPER:
2286 case BufferParams::PAPER_B5PAPER:
2291 if (!params.topmargin.empty())
2292 ofs << ",tmargin=" << params.topmargin;
2293 if (!params.bottommargin.empty())
2294 ofs << ",bmargin=" << params.bottommargin;
2295 if (!params.leftmargin.empty())
2296 ofs << ",lmargin=" << params.leftmargin;
2297 if (!params.rightmargin.empty())
2298 ofs << ",rmargin=" << params.rightmargin;
2299 if (!params.headheight.empty())
2300 ofs << ",headheight=" << params.headheight;
2301 if (!params.headsep.empty())
2302 ofs << ",headsep=" << params.headsep;
2303 if (!params.footskip.empty())
2304 ofs << ",footskip=" << params.footskip;
2309 if (tokenPos(tclass.opt_pagestyle(),
2310 '|', params.pagestyle) >= 0) {
2311 if (params.pagestyle == "fancy") {
2312 ofs << "\\usepackage{fancyhdr}\n";
2315 ofs << "\\pagestyle{" << params.pagestyle << "}\n";
2319 if (params.secnumdepth != tclass.secnumdepth()) {
2320 ofs << "\\setcounter{secnumdepth}{"
2321 << params.secnumdepth
2325 if (params.tocdepth != tclass.tocdepth()) {
2326 ofs << "\\setcounter{tocdepth}{"
2332 if (params.paragraph_separation) {
2333 switch (params.defskip.kind()) {
2334 case VSpace::SMALLSKIP:
2335 ofs << "\\setlength\\parskip{\\smallskipamount}\n";
2337 case VSpace::MEDSKIP:
2338 ofs << "\\setlength\\parskip{\\medskipamount}\n";
2340 case VSpace::BIGSKIP:
2341 ofs << "\\setlength\\parskip{\\bigskipamount}\n";
2343 case VSpace::LENGTH:
2344 ofs << "\\setlength\\parskip{"
2345 << params.defskip.length().asLatexString()
2348 default: // should never happen // Then delete it.
2349 ofs << "\\setlength\\parskip{\\medskipamount}\n";
2354 ofs << "\\setlength\\parindent{0pt}\n";
2358 // Now insert the LyX specific LaTeX commands...
2360 // The optional packages;
2361 string preamble(features.getPackages());
2363 // this might be useful...
2364 preamble += "\n\\makeatletter\n";
2366 // Some macros LyX will need
2367 string tmppreamble(features.getMacros());
2369 if (!tmppreamble.empty()) {
2370 preamble += "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2371 "LyX specific LaTeX commands.\n"
2372 + tmppreamble + '\n';
2375 // the text class specific preamble
2376 tmppreamble = features.getTClassPreamble();
2377 if (!tmppreamble.empty()) {
2378 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2379 "Textclass specific LaTeX commands.\n"
2380 + tmppreamble + '\n';
2383 /* the user-defined preamble */
2384 if (!params.preamble.empty()) {
2385 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2386 "User specified LaTeX commands.\n"
2387 + params.preamble + '\n';
2390 preamble += "\\makeatother\n";
2392 // Itemize bullet settings need to be last in case the user
2393 // defines their own bullets that use a package included
2394 // in the user-defined preamble -- ARRae
2395 // Actually it has to be done much later than that
2396 // since some packages like frenchb make modifications
2397 // at \begin{document} time -- JMarc
2399 for (int i = 0; i < 4; ++i) {
2400 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
2401 if (bullets_def.empty())
2402 bullets_def="\\AtBeginDocument{\n";
2403 bullets_def += " \\renewcommand{\\labelitemi";
2405 // `i' is one less than the item to modify
2412 bullets_def += "ii";
2418 bullets_def += "}{" +
2419 params.user_defined_bullets[i].getText()
2424 if (!bullets_def.empty())
2425 preamble += bullets_def + "}\n\n";
2428 int(lyx::count(preamble.begin(), preamble.end(), '\n'));
2429 for (int j = 0; j != nlines; ++j) {
2435 // We try to load babel late, in case it interferes
2436 // with other packages.
2438 string tmp = lyxrc.language_package;
2439 if (!lyxrc.language_global_options
2440 && tmp == "\\usepackage{babel}")
2441 tmp = string("\\usepackage[") +
2442 language_options.str().c_str() +
2449 ofs << "\\begin{document}\n";
2452 lyxerr[Debug::INFO] << "preamble finished, now the body." << endl;
2454 if (!lyxrc.language_auto_begin) {
2455 ofs << subst(lyxrc.language_command_begin, "$$lang",
2456 params.language->babel())
2461 latexParagraphs(ofs, paragraph, 0, texrow);
2463 // add this just in case after all the paragraphs
2467 if (!lyxrc.language_auto_end) {
2468 ofs << subst(lyxrc.language_command_end, "$$lang",
2469 params.language->babel())
2475 ofs << "\\end{document}\n";
2478 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
2480 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
2484 // Just to be sure. (Asger)
2487 // tex_code_break_column's value is used to decide
2488 // if we are in batchmode or not (within mathed_write()
2489 // in math_write.C) so we must set it to a non-zero
2490 // value when we leave otherwise we save incorrect .lyx files.
2491 tex_code_break_column = lyxrc.ascii_linelen;
2495 lyxerr << "File was not closed properly." << endl;
2498 lyxerr[Debug::INFO] << "Finished making latex file." << endl;
2499 lyxerr[Debug::INFO] << "Row count was " << texrow.rows()-1 << "." << endl;
2504 // LaTeX all paragraphs from par to endpar, if endpar == 0 then to the end
2506 void Buffer::latexParagraphs(ostream & ofs, Paragraph * par,
2507 Paragraph * endpar, TexRow & texrow) const
2509 bool was_title = false;
2510 bool already_title = false;
2513 while (par != endpar) {
2514 Inset * in = par->inInset();
2515 // well we have to check if we are in an inset with unlimited
2516 // lenght (all in one row) if that is true then we don't allow
2517 // any special options in the paragraph and also we don't allow
2518 // any environment other then "Standard" to be valid!
2519 if ((in == 0) || !in->forceDefaultParagraphs(in)) {
2520 LyXLayout const & layout =
2521 textclasslist[params.textclass][par->layout()];
2523 if (layout.intitle) {
2524 if (already_title) {
2525 lyxerr <<"Error in latexParagraphs: You"
2526 " should not mix title layouts"
2527 " with normal ones." << endl;
2530 } else if (was_title && !already_title) {
2531 ofs << "\\maketitle\n";
2533 already_title = true;
2537 if (layout.isEnvironment()) {
2538 par = par->TeXEnvironment(this, params, ofs, texrow);
2540 par = par->TeXOnePar(this, params, ofs, texrow, false);
2543 par = par->TeXOnePar(this, params, ofs, texrow, false);
2546 // It might be that we only have a title in this document
2547 if (was_title && !already_title) {
2548 ofs << "\\maketitle\n";
2554 bool Buffer::isLatex() const
2556 return textclasslist[params.textclass].outputType() == LATEX;
2560 bool Buffer::isLinuxDoc() const
2562 return textclasslist[params.textclass].outputType() == LINUXDOC;
2566 bool Buffer::isLiterate() const
2568 return textclasslist[params.textclass].outputType() == LITERATE;
2572 bool Buffer::isDocBook() const
2574 return textclasslist[params.textclass].outputType() == DOCBOOK;
2578 bool Buffer::isSGML() const
2580 LyXTextClass const & tclass = textclasslist[params.textclass];
2582 return tclass.outputType() == LINUXDOC ||
2583 tclass.outputType() == DOCBOOK;
2587 void Buffer::sgmlOpenTag(ostream & os, Paragraph::depth_type,
2588 string const & latexname) const
2590 if (!latexname.empty() && latexname != "!-- --")
2591 //os << "<!-- " << depth << " -->" << "<" << latexname << ">";
2592 os << "<" << latexname << ">";
2596 void Buffer::sgmlCloseTag(ostream & os, Paragraph::depth_type,
2597 string const & latexname) const
2599 if (!latexname.empty() && latexname != "!-- --")
2600 //os << "<!-- " << depth << " -->" << "</" << latexname << ">\n";
2601 os << "</" << latexname << ">";
2605 void Buffer::makeLinuxDocFile(string const & fname, bool nice, bool body_only)
2607 ofstream ofs(fname.c_str());
2610 Alert::alert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2614 niceFile = nice; // this will be used by included files.
2616 LaTeXFeatures features(params);
2622 LyXTextClass const & tclass = textclasslist[params.textclass];
2624 string top_element = tclass.latexname();
2627 ofs << "<!doctype linuxdoc system";
2629 string preamble = params.preamble;
2630 const string name = nice ? ChangeExtension(filename_, ".sgml")
2632 preamble += features.getIncludedFiles(name);
2633 preamble += features.getLyXSGMLEntities();
2635 if (!preamble.empty()) {
2636 ofs << " [ " << preamble << " ]";
2640 if (params.options.empty())
2641 sgmlOpenTag(ofs, 0, top_element);
2643 string top = top_element;
2645 top += params.options;
2646 sgmlOpenTag(ofs, 0, top);
2650 ofs << "<!-- " << lyx_docversion
2651 << " created this file. For more info see http://www.lyx.org/"
2654 Paragraph::depth_type depth = 0; // paragraph depth
2655 Paragraph * par = paragraph;
2657 vector<string> environment_stack(5);
2660 LyXLayout const & style = tclass[par->layout()];
2662 // treat <toc> as a special case for compatibility with old code
2663 if (par->isInset(0)) {
2664 Inset * inset = par->getInset(0);
2665 Inset::Code lyx_code = inset->lyxCode();
2666 if (lyx_code == Inset::TOC_CODE) {
2667 string const temp = "toc";
2668 sgmlOpenTag(ofs, depth, temp);
2675 // environment tag closing
2676 for (; depth > par->params().depth(); --depth) {
2677 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2678 environment_stack[depth].erase();
2681 // write opening SGML tags
2682 switch (style.latextype) {
2683 case LATEX_PARAGRAPH:
2684 if (depth == par->params().depth()
2685 && !environment_stack[depth].empty()) {
2686 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2687 environment_stack[depth].erase();
2693 sgmlOpenTag(ofs, depth, style.latexname());
2699 _("Error : Wrong depth for"
2700 " LatexType Command.\n"));
2702 if (!environment_stack[depth].empty()) {
2703 sgmlCloseTag(ofs, depth,
2704 environment_stack[depth]);
2708 environment_stack[depth].erase();
2709 sgmlOpenTag(ofs, depth, style.latexname());
2712 case LATEX_ENVIRONMENT:
2713 case LATEX_ITEM_ENVIRONMENT:
2714 if (depth == par->params().depth()
2715 && environment_stack[depth] != style.latexname()) {
2716 sgmlCloseTag(ofs, depth,
2717 environment_stack[depth]);
2718 environment_stack[depth].erase();
2720 if (depth < par->params().depth()) {
2721 depth = par->params().depth();
2722 environment_stack[depth].erase();
2724 if (environment_stack[depth] != style.latexname()) {
2726 sgmlOpenTag(ofs, depth, "p");
2728 sgmlOpenTag(ofs, depth, style.latexname());
2730 if (environment_stack.size() == depth + 1)
2731 environment_stack.push_back("!-- --");
2732 environment_stack[depth] = style.latexname();
2735 if (style.latexparam() == "CDATA")
2738 if (style.latextype == LATEX_ENVIRONMENT) break;
2740 if (style.labeltype == LABEL_MANUAL)
2745 sgmlOpenTag(ofs, depth + 1, item_name);
2748 sgmlOpenTag(ofs, depth, style.latexname());
2752 simpleLinuxDocOnePar(ofs, par, depth);
2757 // write closing SGML tags
2758 switch (style.latextype) {
2761 case LATEX_ENVIRONMENT:
2762 case LATEX_ITEM_ENVIRONMENT:
2763 if (style.latexparam() == "CDATA")
2767 sgmlCloseTag(ofs, depth, style.latexname());
2773 for (int i=depth; i >= 0; --i)
2774 sgmlCloseTag(ofs, depth, environment_stack[i]);
2778 sgmlCloseTag(ofs, 0, top_element);
2782 // How to check for successful close
2786 // checks, if newcol chars should be put into this line
2787 // writes newline, if necessary.
2790 void sgmlLineBreak(ostream & os, string::size_type & colcount,
2791 string::size_type newcol)
2794 if (colcount > lyxrc.ascii_linelen) {
2796 colcount = newcol; // assume write after this call
2811 string tag_name(PAR_TAG const & pt) {
2813 case NONE: return "!-- --";
2814 case TT: return "tt";
2815 case SF: return "sf";
2816 case BF: return "bf";
2817 case IT: return "it";
2818 case SL: return "sl";
2819 case EM: return "em";
2826 void operator|=(PAR_TAG & p1, PAR_TAG const & p2)
2828 p1 = static_cast<PAR_TAG>(p1 | p2);
2833 void reset(PAR_TAG & p1, PAR_TAG const & p2)
2835 p1 = static_cast<PAR_TAG>(p1 & ~p2);
2841 // Handle internal paragraph parsing -- layout already processed.
2842 void Buffer::simpleLinuxDocOnePar(ostream & os,
2844 Paragraph::depth_type /*depth*/)
2846 LyXLayout const & style =
2847 textclasslist[params.textclass][par->layout()];
2848 string::size_type char_line_count = 5; // Heuristic choice ;-)
2850 // gets paragraph main font
2853 if (style.labeltype == LABEL_MANUAL) {
2854 font_old = style.labelfont;
2857 font_old = style.font;
2861 LyXFont::FONT_FAMILY family_type = LyXFont::ROMAN_FAMILY;
2862 LyXFont::FONT_SERIES series_type = LyXFont::MEDIUM_SERIES;
2863 LyXFont::FONT_SHAPE shape_type = LyXFont::UP_SHAPE;
2866 stack<PAR_TAG> tag_state;
2867 // parsing main loop
2868 for (pos_type i = 0; i < par->size(); ++i) {
2870 PAR_TAG tag_close = NONE;
2871 list < PAR_TAG > tag_open;
2873 LyXFont const font = par->getFont(params, i);
2875 if (font_old.family() != font.family()) {
2876 switch (family_type) {
2877 case LyXFont::SANS_FAMILY:
2880 case LyXFont::TYPEWRITER_FAMILY:
2887 family_type = font.family();
2889 switch (family_type) {
2890 case LyXFont::SANS_FAMILY:
2891 tag_open.push_back(SF);
2893 case LyXFont::TYPEWRITER_FAMILY:
2894 tag_open.push_back(TT);
2901 if (font_old.series() != font.series()) {
2902 switch (series_type) {
2903 case LyXFont::BOLD_SERIES:
2910 series_type = font.series();
2912 switch (series_type) {
2913 case LyXFont::BOLD_SERIES:
2914 tag_open.push_back(BF);
2922 if (font_old.shape() != font.shape()) {
2923 switch (shape_type) {
2924 case LyXFont::ITALIC_SHAPE:
2927 case LyXFont::SLANTED_SHAPE:
2934 shape_type = font.shape();
2936 switch (shape_type) {
2937 case LyXFont::ITALIC_SHAPE:
2938 tag_open.push_back(IT);
2940 case LyXFont::SLANTED_SHAPE:
2941 tag_open.push_back(SL);
2948 if (font_old.emph() != font.emph()) {
2949 if (font.emph() == LyXFont::ON) {
2950 tag_open.push_back(EM);
2959 list < PAR_TAG > temp;
2960 while (!tag_state.empty() && tag_close) {
2961 PAR_TAG k = tag_state.top();
2963 os << "</" << tag_name(k) << ">";
2970 for(list< PAR_TAG >::const_iterator j = temp.begin();
2971 j != temp.end(); ++j) {
2973 os << "<" << tag_name(*j) << ">";
2976 for(list< PAR_TAG >::const_iterator j = tag_open.begin();
2977 j != tag_open.end(); ++j) {
2979 os << "<" << tag_name(*j) << ">";
2982 char c = par->getChar(i);
2984 if (c == Paragraph::META_INSET) {
2985 Inset * inset = par->getInset(i);
2986 inset->linuxdoc(this, os);
2991 if (style.latexparam() == "CDATA") {
2992 // "TeX"-Mode on == > SGML-Mode on.
2998 if (par->sgmlConvertChar(c, sgml_string)
2999 && !style.free_spacing && !par->isFreeSpacing())
3001 // in freespacing mode, spaces are
3002 // non-breaking characters
3003 if (desc_on) {// if char is ' ' then...
3006 sgmlLineBreak(os, char_line_count, 6);
3010 sgmlLineBreak(os, char_line_count, 1);
3015 char_line_count += sgml_string.length();
3021 while (!tag_state.empty()) {
3022 os << "</" << tag_name(tag_state.top()) << ">";
3026 // resets description flag correctly
3028 // <tag> not closed...
3029 sgmlLineBreak(os, char_line_count, 6);
3035 // Print an error message.
3036 void Buffer::sgmlError(Paragraph * par, int pos,
3037 string const & message) const
3039 // insert an error marker in text
3040 InsetError * new_inset = new InsetError(message);
3041 par->insertInset(pos, new_inset, LyXFont(LyXFont::ALL_INHERIT,
3046 void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
3048 ofstream ofs(fname.c_str());
3050 Alert::alert(_("LYX_ERROR:"), _("Cannot write file"), fname);
3054 Paragraph * par = paragraph;
3056 niceFile = nice; // this will be used by Insetincludes.
3058 LaTeXFeatures features(params);
3063 LyXTextClass const & tclass = textclasslist[params.textclass];
3064 string top_element = tclass.latexname();
3067 ofs << "<!DOCTYPE " << top_element
3068 << " PUBLIC \"-//OASIS//DTD DocBook V4.1//EN\"";
3070 string preamble = params.preamble;
3071 const string name = nice ? ChangeExtension(filename_, ".sgml")
3073 preamble += features.getIncludedFiles(name);
3074 preamble += features.getLyXSGMLEntities();
3076 if (!preamble.empty()) {
3077 ofs << "\n [ " << preamble << " ]";
3082 string top = top_element;
3084 top += params.language->code();
3087 if (!params.options.empty()) {
3089 top += params.options;
3091 sgmlOpenTag(ofs, 0, top);
3093 ofs << "<!-- DocBook file was created by " << lyx_docversion
3094 << "\n See http://www.lyx.org/ for more information -->\n";
3096 vector<string> environment_stack(10);
3097 vector<string> environment_inner(10);
3098 vector<string> command_stack(10);
3100 bool command_flag = false;
3101 Paragraph::depth_type command_depth = 0;
3102 Paragraph::depth_type command_base = 0;
3103 Paragraph::depth_type cmd_depth = 0;
3104 Paragraph::depth_type depth = 0; // paragraph depth
3107 string command_name;
3113 int desc_on = 0; // description mode
3115 LyXLayout const & style = tclass[par->layout()];
3117 // environment tag closing
3118 for (; depth > par->params().depth(); --depth) {
3119 if (environment_inner[depth] != "!-- --") {
3120 item_name = "listitem";
3121 sgmlCloseTag(ofs, command_depth + depth,
3123 if (environment_inner[depth] == "varlistentry")
3124 sgmlCloseTag(ofs, depth+command_depth,
3125 environment_inner[depth]);
3127 sgmlCloseTag(ofs, depth + command_depth,
3128 environment_stack[depth]);
3129 environment_stack[depth].erase();
3130 environment_inner[depth].erase();
3133 if (depth == par->params().depth()
3134 && environment_stack[depth] != style.latexname()
3135 && !environment_stack[depth].empty()) {
3136 if (environment_inner[depth] != "!-- --") {
3137 item_name= "listitem";
3138 sgmlCloseTag(ofs, command_depth+depth,
3140 if (environment_inner[depth] == "varlistentry")
3142 depth + command_depth,
3143 environment_inner[depth]);
3146 sgmlCloseTag(ofs, depth + command_depth,
3147 environment_stack[depth]);
3149 environment_stack[depth].erase();
3150 environment_inner[depth].erase();
3153 // Write opening SGML tags.
3154 switch (style.latextype) {
3155 case LATEX_PARAGRAPH:
3156 sgmlOpenTag(ofs, depth + command_depth,
3163 _("Error : Wrong depth for "
3164 "LatexType Command.\n"));
3166 command_name = style.latexname();
3168 sgmlparam = style.latexparam();
3169 c_params = split(sgmlparam, c_depth,'|');
3171 cmd_depth = lyx::atoi(c_depth);
3174 if (cmd_depth < command_base) {
3175 for (Paragraph::depth_type j = command_depth; j >= command_base; --j)
3176 sgmlCloseTag(ofs, j, command_stack[j]);
3177 command_depth = command_base = cmd_depth;
3178 } else if (cmd_depth <= command_depth) {
3179 for (int j = command_depth; j >= int(cmd_depth); --j)
3180 sgmlCloseTag(ofs, j, command_stack[j]);
3181 command_depth = cmd_depth;
3183 command_depth = cmd_depth;
3185 command_depth = command_base = cmd_depth;
3186 command_flag = true;
3188 if (command_stack.size() == command_depth + 1)
3189 command_stack.push_back(string());
3190 command_stack[command_depth] = command_name;
3192 // treat label as a special case for
3193 // more WYSIWYM handling.
3194 // This is a hack while paragraphs can't have
3195 // attributes, like id in this case.
3196 if (par->isInset(0)) {
3197 Inset * inset = par->getInset(0);
3198 Inset::Code lyx_code = inset->lyxCode();
3199 if (lyx_code == Inset::LABEL_CODE) {
3200 command_name += " id=\"";
3201 command_name += (static_cast<InsetCommand *>(inset))->getContents();
3202 command_name += "\"";
3207 sgmlOpenTag(ofs, depth + command_depth, command_name);
3208 if (c_params.empty())
3209 item_name = "title";
3211 item_name = c_params;
3212 sgmlOpenTag(ofs, depth + 1 + command_depth, item_name);
3215 case LATEX_ENVIRONMENT:
3216 case LATEX_ITEM_ENVIRONMENT:
3217 if (depth < par->params().depth()) {
3218 depth = par->params().depth();
3219 environment_stack[depth].erase();
3222 if (environment_stack[depth] != style.latexname()) {
3223 if (environment_stack.size() == depth + 1) {
3224 environment_stack.push_back("!-- --");
3225 environment_inner.push_back("!-- --");
3227 environment_stack[depth] = style.latexname();
3228 environment_inner[depth] = "!-- --";
3229 sgmlOpenTag(ofs, depth + command_depth,
3230 environment_stack[depth]);
3232 if (environment_inner[depth] != "!-- --") {
3233 item_name= "listitem";
3235 command_depth + depth,
3237 if (environment_inner[depth] == "varlistentry")
3239 depth + command_depth,
3240 environment_inner[depth]);
3244 if (style.latextype == LATEX_ENVIRONMENT) {
3245 if (!style.latexparam().empty()) {
3246 if (style.latexparam() == "CDATA")
3249 sgmlOpenTag(ofs, depth + command_depth,
3250 style.latexparam());
3255 desc_on = (style.labeltype == LABEL_MANUAL);
3258 environment_inner[depth]= "varlistentry";
3260 environment_inner[depth]= "listitem";
3262 sgmlOpenTag(ofs, depth + 1 + command_depth,
3263 environment_inner[depth]);
3267 sgmlOpenTag(ofs, depth + 1 + command_depth,
3271 sgmlOpenTag(ofs, depth + 1 + command_depth,
3276 sgmlOpenTag(ofs, depth + command_depth,
3281 simpleDocBookOnePar(ofs, par, desc_on, depth+1+command_depth);
3285 // write closing SGML tags
3286 switch (style.latextype) {
3288 if (c_params.empty())
3292 sgmlCloseTag(ofs, depth + command_depth, end_tag);
3294 case LATEX_ENVIRONMENT:
3295 if (!style.latexparam().empty()) {
3296 if (style.latexparam() == "CDATA")
3299 sgmlCloseTag(ofs, depth + command_depth,
3300 style.latexparam());
3303 case LATEX_ITEM_ENVIRONMENT:
3304 if (desc_on == 1) break;
3306 sgmlCloseTag(ofs, depth + 1 + command_depth, end_tag);
3308 case LATEX_PARAGRAPH:
3309 sgmlCloseTag(ofs, depth + command_depth, style.latexname());
3312 sgmlCloseTag(ofs, depth + command_depth, style.latexname());
3318 for (int d = depth; d >= 0; --d) {
3319 if (!environment_stack[depth].empty()) {
3320 if (environment_inner[depth] != "!-- --") {
3321 item_name = "listitem";
3322 sgmlCloseTag(ofs, command_depth + depth,
3324 if (environment_inner[depth] == "varlistentry")
3325 sgmlCloseTag(ofs, depth + command_depth,
3326 environment_inner[depth]);
3329 sgmlCloseTag(ofs, depth + command_depth,
3330 environment_stack[depth]);
3334 for (int j = command_depth; j >= 0 ; --j)
3335 if (!command_stack[j].empty())
3336 sgmlCloseTag(ofs, j, command_stack[j]);
3339 sgmlCloseTag(ofs, 0, top_element);
3342 // How to check for successful close
3346 void Buffer::simpleDocBookOnePar(ostream & os,
3347 Paragraph * par, int & desc_on,
3348 Paragraph::depth_type depth) const
3350 bool emph_flag = false;
3352 LyXLayout const & style =
3353 textclasslist[params.textclass][par->layout()];
3355 LyXFont font_old = style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
3357 int char_line_count = depth;
3358 //if (!style.free_spacing)
3359 // os << string(depth,' ');
3361 // parsing main loop
3362 for (pos_type i = 0; i < par->size(); ++i) {
3363 LyXFont font = par->getFont(params, i);
3365 // handle <emphasis> tag
3366 if (font_old.emph() != font.emph()) {
3367 if (font.emph() == LyXFont::ON) {
3371 os << "</emphasis>";
3377 if (par->isInset(i)) {
3378 Inset * inset = par->getInset(i);
3379 // don't print the inset in position 0 if desc_on == 3 (label)
3380 if ( i || desc_on != 3) {
3381 if(style.latexparam() == "CDATA")
3383 inset->docbook(this, os);
3384 if(style.latexparam() == "CDATA")
3388 char c = par->getChar(i);
3390 par->sgmlConvertChar(c, sgml_string);
3392 if (style.pass_thru) {
3394 } else if (style.free_spacing || par->isFreeSpacing() || c != ' ') {
3396 } else if (desc_on ==1) {
3398 os << "\n</term><listitem><para>";
3408 os << "</emphasis>";
3411 // resets description flag correctly
3413 // <term> not closed...
3416 if (style.free_spacing) os << '\n';
3420 // This should be enabled when the Chktex class is implemented. (Asger)
3421 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
3422 // Other flags: -wall -v0 -x
3423 int Buffer::runChktex()
3425 if (!users->text) return 0;
3427 users->owner()->prohibitInput();
3429 // get LaTeX-Filename
3430 string const name = getLatexName();
3431 string path = filePath();
3433 string const org_path = path;
3434 if (lyxrc.use_tempdir || !IsDirWriteable(path)) {
3438 Path p(path); // path to LaTeX file
3439 users->owner()->message(_("Running chktex..."));
3441 // Remove all error insets
3442 bool const removedErrorInsets = users->removeAutoInsets();
3444 // Generate the LaTeX file if neccessary
3445 makeLaTeXFile(name, org_path, false);
3448 Chktex chktex(lyxrc.chktex_command, name, filePath());
3449 int res = chktex.run(terr); // run chktex
3452 Alert::alert(_("chktex did not work!"),
3453 _("Could not run with file:"), name);
3454 } else if (res > 0) {
3455 // Insert all errors as errors boxes
3456 users->insertErrors(terr);
3459 // if we removed error insets before we ran chktex or if we inserted
3460 // error insets after we ran chktex, this must be run:
3461 if (removedErrorInsets || res) {
3465 users->owner()->allowInput();
3471 void Buffer::validate(LaTeXFeatures & features) const
3473 Paragraph * par = paragraph;
3474 LyXTextClass const & tclass = textclasslist[params.textclass];
3476 // AMS Style is at document level
3477 if (params.use_amsmath || tclass.provides(LyXTextClass::amsmath))
3478 features.require("amsmath");
3481 // We don't use "lyxerr.debug" because of speed. (Asger)
3482 if (lyxerr.debugging(Debug::LATEX))
3483 lyxerr << "Paragraph: " << par << endl;
3485 // Now just follow the list of paragraphs and run
3486 // validate on each of them.
3487 par->validate(features);
3489 // and then the next paragraph
3493 // the bullet shapes are buffer level not paragraph level
3494 // so they are tested here
3495 for (int i = 0; i < 4; ++i) {
3496 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
3497 int const font = params.user_defined_bullets[i].getFont();
3499 int const c = params
3500 .user_defined_bullets[i]
3507 features.require("latexsym");
3509 } else if (font == 1) {
3510 features.require("amssymb");
3511 } else if ((font >= 2 && font <= 5)) {
3512 features.require("pifont");
3517 if (lyxerr.debugging(Debug::LATEX)) {
3518 features.showStruct();
3523 // This function should be in Buffer because it's a buffer's property (ale)
3524 string const Buffer::getIncludeonlyList(char delim)
3527 for (inset_iterator it = inset_iterator_begin();
3528 it != inset_iterator_end(); ++it) {
3529 if ((*it)->lyxCode() == Inset::INCLUDE_CODE) {
3530 InsetInclude * insetinc =
3531 static_cast<InsetInclude *>(*it);
3532 if (insetinc->isIncludeOnly()) {
3535 lst += insetinc->getRelFileBaseName();
3539 lyxerr[Debug::INFO] << "Includeonly(" << lst << ')' << endl;
3544 vector<string> const Buffer::getLabelList()
3546 /// if this is a child document and the parent is already loaded
3547 /// Use the parent's list instead [ale990407]
3548 if (!params.parentname.empty()
3549 && bufferlist.exists(params.parentname)) {
3550 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3552 return tmp->getLabelList();
3555 vector<string> label_list;
3556 for (inset_iterator it = inset_iterator_begin();
3557 it != inset_iterator_end(); ++it) {
3558 vector<string> const l = (*it)->getLabelList();
3559 label_list.insert(label_list.end(), l.begin(), l.end());
3565 Buffer::Lists const Buffer::getLists() const
3568 Paragraph * par = paragraph;
3570 LyXTextClass const & textclass = textclasslist[params.textclass];
3571 bool found = textclass.hasLayout("caption");
3572 string const layout("caption");
3575 char const labeltype = textclass[par->layout()].labeltype;
3577 if (labeltype >= LABEL_COUNTER_CHAPTER
3578 && labeltype <= LABEL_COUNTER_CHAPTER + params.tocdepth) {
3579 // insert this into the table of contents
3580 SingleList & item = l["TOC"];
3583 textclass.maxcounter());
3584 item.push_back(TocItem(par, depth, par->asString(this, true)));
3586 // For each paragrph, traverse its insets and look for
3590 Paragraph::inset_iterator it =
3591 par->inset_iterator_begin();
3592 Paragraph::inset_iterator end =
3593 par->inset_iterator_end();
3595 for (; it != end; ++it) {
3596 if ((*it)->lyxCode() == Inset::FLOAT_CODE) {
3598 static_cast<InsetFloat*>(*it);
3600 string const type = il->type();
3602 // Now find the caption in the float...
3603 // We now tranverse the paragraphs of
3605 Paragraph * tmp = il->inset.paragraph();
3607 if (tmp->layout() == layout) {
3608 SingleList & item = l[type];
3610 tostr(item.size()+1) + ". " + tmp->asString(this, false);
3611 item.push_back(TocItem(tmp, 0 , str));
3618 lyxerr << "caption not found" << endl;
3627 // This is also a buffer property (ale)
3628 vector<pair<string, string> > const Buffer::getBibkeyList()
3630 /// if this is a child document and the parent is already loaded
3631 /// Use the parent's list instead [ale990412]
3632 if (!params.parentname.empty() && bufferlist.exists(params.parentname)) {
3633 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3635 return tmp->getBibkeyList();
3638 vector<pair<string, string> > keys;
3639 Paragraph * par = paragraph;
3642 keys.push_back(pair<string, string>(par->bibkey->getContents(),
3643 par->asString(this, false)));
3647 // Might be either using bibtex or a child has bibliography
3649 for (inset_iterator it = inset_iterator_begin();
3650 it != inset_iterator_end(); ++it) {
3651 // Search for Bibtex or Include inset
3652 if ((*it)->lyxCode() == Inset::BIBTEX_CODE) {
3653 vector<pair<string,string> > tmp =
3654 static_cast<InsetBibtex*>(*it)->getKeys(this);
3655 keys.insert(keys.end(), tmp.begin(), tmp.end());
3656 } else if ((*it)->lyxCode() == Inset::INCLUDE_CODE) {
3657 vector<pair<string,string> > const tmp =
3658 static_cast<InsetInclude*>(*it)->getKeys();
3659 keys.insert(keys.end(), tmp.begin(), tmp.end());
3668 bool Buffer::isDepClean(string const & name) const
3670 DEPCLEAN * item = dep_clean;
3671 while (item && item->master != name)
3673 if (!item) return true;
3678 void Buffer::markDepClean(string const & name)
3681 dep_clean = new DEPCLEAN;
3682 dep_clean->clean = true;
3683 dep_clean->master = name;
3684 dep_clean->next = 0;
3686 DEPCLEAN * item = dep_clean;
3687 while (item && item->master != name)
3692 item = new DEPCLEAN;
3694 item->master = name;
3701 bool Buffer::dispatch(string const & command)
3703 // Split command string into command and argument
3705 string line = frontStrip(command);
3706 string const arg = strip(frontStrip(split(line, cmd, ' ')));
3708 return dispatch(lyxaction.LookupFunc(cmd), arg);
3712 bool Buffer::dispatch(int action, string const & argument)
3714 bool dispatched = true;
3717 Exporter::Export(this, argument, false);
3727 void Buffer::resizeInsets(BufferView * bv)
3729 /// then remove all LyXText in text-insets
3730 Paragraph * par = paragraph;
3731 for (; par; par = par->next()) {
3732 par->resizeInsetsLyXText(bv);
3737 void Buffer::redraw()
3744 void Buffer::changeLanguage(Language const * from, Language const * to)
3747 ParIterator end = par_iterator_end();
3748 for (ParIterator it = par_iterator_begin(); it != end; ++it)
3749 (*it)->changeLanguage(params, from, to);
3753 bool Buffer::isMultiLingual()
3755 ParIterator end = par_iterator_end();
3756 for (ParIterator it = par_iterator_begin(); it != end; ++it)
3757 if ((*it)->isMultiLingual(params))
3764 Buffer::inset_iterator::inset_iterator(Paragraph * paragraph, pos_type pos)
3767 it = par->InsetIterator(pos);
3768 if (it == par->inset_iterator_end()) {
3775 void Buffer::inset_iterator::setParagraph()
3778 it = par->inset_iterator_begin();
3779 if (it != par->inset_iterator_end())
3784 // We maintain an invariant that whenever par = 0 then it = 0
3788 Inset * Buffer::getInsetFromID(int id_arg) const
3790 for (inset_iterator it = inset_const_iterator_begin();
3791 it != inset_const_iterator_end(); ++it)
3793 if ((*it)->id() == id_arg)
3795 Inset * in = (*it)->getInsetFromID(id_arg);
3803 Paragraph * Buffer::getParFromID(int id) const
3805 if (id < 0) return 0;
3806 Paragraph * par = paragraph;
3808 if (par->id() == id) {
3811 Paragraph * tmp = par->getParFromID(id);
3821 ParIterator Buffer::par_iterator_begin()
3823 return ParIterator(paragraph);
3827 ParIterator Buffer::par_iterator_end()
3829 return ParIterator();