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.language, ert_comp.contents, true);
409 par->insertInset(pos++, inset, ert_comp.font);
410 ert_comp.contents.erase();
413 ert_comp.active = false;
420 Buffer::parseSingleLyXformat2Token(LyXLex & lex, Paragraph *& par,
421 Paragraph *& first_par,
422 string const & token, int & pos,
423 Paragraph::depth_type & depth,
427 bool the_end_read = false;
428 #ifndef NO_COMPABILITY
429 #ifndef NO_PEXTRA_REALLY
430 // This is super temporary but is needed to get the compability
431 // mode for minipages work correctly together with new tabulars.
432 static int call_depth;
434 bool checkminipage = false;
435 static Paragraph * minipar;
436 static Paragraph * parBeforeMinipage;
439 if (token[0] != '\\') {
440 #ifndef NO_COMPABILITY
441 if (ert_comp.active) {
442 ert_comp.contents += token;
445 for (string::const_iterator cit = token.begin();
446 cit != token.end(); ++cit) {
447 par->insertChar(pos, (*cit), font);
450 #ifndef NO_COMPABILITY
453 } else if (token == "\\i") {
454 Inset * inset = new InsetLatexAccent;
455 inset->read(this, lex);
456 par->insertInset(pos, inset, font);
458 } else if (token == "\\layout") {
459 #ifndef NO_COMPABILITY
460 ert_comp.in_tabular = false;
462 insertErtContents(par, pos);
465 string const layoutname = lex.getString();
466 //lyxerr << "Looking for layout '"
467 // << layoutname << "'!" << endl;
469 //lyxerr << "Result: " << pp.first << "/" << pp.second << endl;
471 #ifndef NO_COMPABILITY
472 if (compare_no_case(layoutname, "latex") == 0) {
473 ert_comp.active = true;
474 ert_comp.font = font;
478 // The is the compability reading of layout caption.
479 // It can be removed in LyX version 1.3.0. (Lgb)
480 if (compare_no_case(layoutname, "caption") == 0) {
481 // We expect that the par we are now working on is
482 // really inside a InsetText inside a InsetFloat.
483 // We also know that captions can only be
484 // one paragraph. (Lgb)
486 // We should now read until the next "\layout"
488 // This is probably not good enough, what if the
489 // caption is the last par in the document (Lgb)
490 istream & ist = lex.getStream();
496 if (prefixIs(line, "\\layout")) {
500 if (prefixIs(line, "\\begin_inset"))
502 if (prefixIs(line, "\\end_inset")) {
513 // Now we should have the whole layout in ss
514 // we should now be able to give this to the
516 ss << "\\end_inset\n";
518 // This seems like a bug in stringstream.
519 // We really should be able to use ss
521 istringstream is(ss.str());
523 tmplex.setStream(is);
524 Inset * inset = new InsetCaption;
525 inset->Read(this, tmplex);
526 par->InsertInset(pos, inset, font);
533 par = new Paragraph(par);
536 par->layout(layoutname);
537 // Test whether the layout is obsolete.
538 LyXLayout const & layout =
539 textclasslist[params.textclass][par->layout()];
540 if (!layout.obsoleted_by().empty())
541 par->layout(layout.obsoleted_by());
542 par->params().depth(depth);
543 font = LyXFont(LyXFont::ALL_INHERIT, params.language);
544 if (file_format < 216
545 && params.language->lang() == "hebrew")
546 font.setLanguage(default_language);
551 #ifndef NO_COMPABILITY
552 } else if (token == "\\begin_float") {
553 insertErtContents(par, pos);
554 //insertErtContents(par, pos, false);
555 //ert_stack.push(ert_comp);
556 //ert_comp = ErtComp();
558 // This is the compability reader. It can be removed in
559 // LyX version 1.3.0. (Lgb)
561 string const tmptok = lex.getString();
562 //lyxerr << "old float: " << tmptok << endl;
565 stringstream old_float;
567 if (tmptok == "footnote") {
568 inset = new InsetFoot;
569 old_float << "collapsed true\n";
570 } else if (tmptok == "margin") {
571 inset = new InsetMarginal;
572 old_float << "collapsed true\n";
573 } else if (tmptok == "fig") {
574 inset = new InsetFloat("figure");
575 old_float << "placement htbp\n"
577 << "collapsed false\n";
578 } else if (tmptok == "tab") {
579 inset = new InsetFloat("table");
580 old_float << "placement htbp\n"
582 << "collapsed false\n";
583 } else if (tmptok == "alg") {
584 inset = new InsetFloat("algorithm");
585 old_float << "placement htbp\n"
587 << "collapsed false\n";
588 } else if (tmptok == "wide-fig") {
589 inset = new InsetFloat("figure");
590 //InsetFloat * tmp = new InsetFloat("figure");
593 old_float << "placement htbp\n"
595 << "collapsed false\n";
596 } else if (tmptok == "wide-tab") {
597 inset = new InsetFloat("table");
598 //InsetFloat * tmp = new InsetFloat("table");
601 old_float << "placement htbp\n"
603 << "collapsed false\n";
607 #ifndef NO_PEXTRA_REALLY
610 return false; // no end read yet
613 // Here we need to check for \end_deeper and handle that
614 // before we do the footnote parsing.
615 // This _is_ a hack! (Lgb)
618 string const tmp = lex.getString();
619 if (tmp == "\\end_deeper") {
620 //lyxerr << "\\end_deeper caught!" << endl;
622 lex.printError("\\end_deeper: "
623 "depth is already null");
628 old_float << tmp << ' ';
633 old_float << lex.getLongString("\\end_float")
634 << "\n\\end_inset\n";
635 //lyxerr << "Float Body:\n" << old_float.str() << endl;
636 // That this does not work seems like a bug
637 // in stringstream. (Lgb)
638 istringstream istr(old_float.str());
640 nylex.setStream(istr);
641 inset->read(this, nylex);
642 par->insertInset(pos, inset, font);
644 insertErtContents(par, pos);
646 } else if (token == "\\begin_deeper") {
648 } else if (token == "\\end_deeper") {
650 lex.printError("\\end_deeper: "
651 "depth is already null");
655 } else if (token == "\\begin_preamble") {
656 params.readPreamble(lex);
657 } else if (token == "\\textclass") {
659 pair<bool, textclass_type> pp =
660 textclasslist.NumberOfClass(lex.getString());
662 params.textclass = pp.second;
664 Alert::alert(string(_("Textclass error")),
665 string(_("The document uses an unknown textclass \"")) +
666 lex.getString() + string("\"."),
667 string(_("LyX will not be able to produce output correctly.")));
668 params.textclass = 0;
670 if (!textclasslist[params.textclass].load()) {
671 // if the textclass wasn't loaded properly
672 // we need to either substitute another
673 // or stop loading the file.
674 // I can substitute but I don't see how I can
675 // stop loading... ideas?? ARRae980418
676 Alert::alert(_("Textclass Loading Error!"),
677 string(_("Can't load textclass ")) +
678 textclasslist[params.textclass].name(),
679 _("-- substituting default"));
680 params.textclass = 0;
682 } else if (token == "\\options") {
684 params.options = lex.getString();
685 } else if (token == "\\language") {
686 params.readLanguage(lex);
687 } else if (token == "\\fontencoding") {
689 } else if (token == "\\inputencoding") {
691 params.inputenc = lex.getString();
692 } else if (token == "\\graphics") {
693 params.readGraphicsDriver(lex);
694 } else if (token == "\\fontscheme") {
696 params.fonts = lex.getString();
697 } else if (token == "\\noindent") {
698 par->params().noindent(true);
699 } else if (token == "\\fill_top") {
700 par->params().spaceTop(VSpace(VSpace::VFILL));
701 } else if (token == "\\fill_bottom") {
702 par->params().spaceBottom(VSpace(VSpace::VFILL));
703 } else if (token == "\\line_top") {
704 par->params().lineTop(true);
705 } else if (token == "\\line_bottom") {
706 par->params().lineBottom(true);
707 } else if (token == "\\pagebreak_top") {
708 par->params().pagebreakTop(true);
709 } else if (token == "\\pagebreak_bottom") {
710 par->params().pagebreakBottom(true);
711 } else if (token == "\\start_of_appendix") {
712 par->params().startOfAppendix(true);
713 } else if (token == "\\paragraph_separation") {
714 int tmpret = lex.findToken(string_paragraph_separation);
717 if (tmpret != LYX_LAYOUT_DEFAULT)
718 params.paragraph_separation =
719 static_cast<BufferParams::PARSEP>(tmpret);
720 } else if (token == "\\defskip") {
722 params.defskip = VSpace(lex.getString());
723 #ifndef NO_COMPABILITY
724 } else if (token == "\\epsfig") { // obsolete
725 // Indeed it is obsolete, but we HAVE to be backwards
726 // compatible until 0.14, because otherwise all figures
727 // in existing documents are irretrivably lost. (Asger)
728 params.readGraphicsDriver(lex);
730 } else if (token == "\\quotes_language") {
731 int tmpret = lex.findToken(string_quotes_language);
734 if (tmpret != LYX_LAYOUT_DEFAULT) {
735 InsetQuotes::quote_language tmpl =
736 InsetQuotes::EnglishQ;
739 tmpl = InsetQuotes::EnglishQ;
742 tmpl = InsetQuotes::SwedishQ;
745 tmpl = InsetQuotes::GermanQ;
748 tmpl = InsetQuotes::PolishQ;
751 tmpl = InsetQuotes::FrenchQ;
754 tmpl = InsetQuotes::DanishQ;
757 params.quotes_language = tmpl;
759 } else if (token == "\\quotes_times") {
761 switch (lex.getInteger()) {
763 params.quotes_times = InsetQuotes::SingleQ;
766 params.quotes_times = InsetQuotes::DoubleQ;
769 } else if (token == "\\papersize") {
770 int tmpret = lex.findToken(string_papersize);
774 params.papersize2 = tmpret;
775 } else if (token == "\\paperpackage") {
776 int tmpret = lex.findToken(string_paperpackages);
779 params.paperpackage = BufferParams::PACKAGE_NONE;
781 params.paperpackage = tmpret;
782 } else if (token == "\\use_geometry") {
784 params.use_geometry = lex.getInteger();
785 } else if (token == "\\use_amsmath") {
787 params.use_amsmath = lex.getInteger();
788 } else if (token == "\\use_natbib") {
790 params.use_natbib = lex.getInteger();
791 } else if (token == "\\use_numerical_citations") {
793 params.use_numerical_citations = lex.getInteger();
794 } else if (token == "\\paperorientation") {
795 int tmpret = lex.findToken(string_orientation);
798 if (tmpret != LYX_LAYOUT_DEFAULT)
799 params.orientation = static_cast<BufferParams::PAPER_ORIENTATION>(tmpret);
800 } else if (token == "\\paperwidth") {
802 params.paperwidth = lex.getString();
803 } else if (token == "\\paperheight") {
805 params.paperheight = lex.getString();
806 } else if (token == "\\leftmargin") {
808 params.leftmargin = lex.getString();
809 } else if (token == "\\topmargin") {
811 params.topmargin = lex.getString();
812 } else if (token == "\\rightmargin") {
814 params.rightmargin = lex.getString();
815 } else if (token == "\\bottommargin") {
817 params.bottommargin = lex.getString();
818 } else if (token == "\\headheight") {
820 params.headheight = lex.getString();
821 } else if (token == "\\headsep") {
823 params.headsep = lex.getString();
824 } else if (token == "\\footskip") {
826 params.footskip = lex.getString();
827 } else if (token == "\\paperfontsize") {
829 params.fontsize = strip(lex.getString());
830 } else if (token == "\\papercolumns") {
832 params.columns = lex.getInteger();
833 } else if (token == "\\papersides") {
835 switch (lex.getInteger()) {
837 case 1: params.sides = LyXTextClass::OneSide; break;
838 case 2: params.sides = LyXTextClass::TwoSides; break;
840 } else if (token == "\\paperpagestyle") {
842 params.pagestyle = strip(lex.getString());
843 } else if (token == "\\bullet") {
845 int const index = lex.getInteger();
847 int temp_int = lex.getInteger();
848 params.user_defined_bullets[index].setFont(temp_int);
849 params.temp_bullets[index].setFont(temp_int);
851 temp_int = lex.getInteger();
852 params.user_defined_bullets[index].setCharacter(temp_int);
853 params.temp_bullets[index].setCharacter(temp_int);
855 temp_int = lex.getInteger();
856 params.user_defined_bullets[index].setSize(temp_int);
857 params.temp_bullets[index].setSize(temp_int);
859 string const temp_str = lex.getString();
860 if (temp_str != "\\end_bullet") {
861 // this element isn't really necessary for
862 // parsing but is easier for humans
863 // to understand bullets. Put it back and
864 // set a debug message?
865 lex.printError("\\end_bullet expected, got" + temp_str);
866 //how can I put it back?
868 } else if (token == "\\bulletLaTeX") {
869 // The bullet class should be able to read this.
871 int const index = lex.getInteger();
873 string temp_str = lex.getString();
875 while (temp_str != "\\end_bullet") {
876 // this loop structure is needed when user
877 // enters an empty string since the first
878 // thing returned will be the \\end_bullet
880 // if the LaTeX entry has spaces. Each element
881 // therefore needs to be read in turn
884 temp_str = lex.getString();
887 params.user_defined_bullets[index].setText(sum_str);
888 params.temp_bullets[index].setText(sum_str);
889 } else if (token == "\\secnumdepth") {
891 params.secnumdepth = lex.getInteger();
892 } else if (token == "\\tocdepth") {
894 params.tocdepth = lex.getInteger();
895 } else if (token == "\\spacing") {
897 string const tmp = strip(lex.getString());
898 Spacing::Space tmp_space = Spacing::Default;
900 if (tmp == "single") {
901 tmp_space = Spacing::Single;
902 } else if (tmp == "onehalf") {
903 tmp_space = Spacing::Onehalf;
904 } else if (tmp == "double") {
905 tmp_space = Spacing::Double;
906 } else if (tmp == "other") {
908 tmp_space = Spacing::Other;
909 tmp_val = lex.getFloat();
911 lex.printError("Unknown spacing token: '$$Token'");
913 // Small hack so that files written with klyx will be
916 par->params().spacing(Spacing(tmp_space, tmp_val));
918 params.spacing.set(tmp_space, tmp_val);
920 } else if (token == "\\paragraph_spacing") {
922 string const tmp = strip(lex.getString());
923 if (tmp == "single") {
924 par->params().spacing(Spacing(Spacing::Single));
925 } else if (tmp == "onehalf") {
926 par->params().spacing(Spacing(Spacing::Onehalf));
927 } else if (tmp == "double") {
928 par->params().spacing(Spacing(Spacing::Double));
929 } else if (tmp == "other") {
931 par->params().spacing(Spacing(Spacing::Other,
934 lex.printError("Unknown spacing token: '$$Token'");
936 } else if (token == "\\float_placement") {
938 params.float_placement = lex.getString();
939 } else if (token == "\\family") {
941 font.setLyXFamily(lex.getString());
942 } else if (token == "\\series") {
944 font.setLyXSeries(lex.getString());
945 } else if (token == "\\shape") {
947 font.setLyXShape(lex.getString());
948 } else if (token == "\\size") {
950 font.setLyXSize(lex.getString());
951 #ifndef NO_COMPABILITY
952 } else if (token == "\\latex") {
954 string const tok = lex.getString();
955 if (tok == "no_latex") {
957 insertErtContents(par, pos);
958 } else if (tok == "latex") {
959 ert_comp.active = true;
960 ert_comp.font = font;
961 } else if (tok == "default") {
963 insertErtContents(par, pos);
965 lex.printError("Unknown LaTeX font flag "
969 } else if (token == "\\lang") {
971 string const tok = lex.getString();
972 Language const * lang = languages.getLanguage(tok);
974 font.setLanguage(lang);
976 font.setLanguage(params.language);
977 lex.printError("Unknown language `$$Token'");
979 } else if (token == "\\numeric") {
981 font.setNumber(font.setLyXMisc(lex.getString()));
982 } else if (token == "\\emph") {
984 font.setEmph(font.setLyXMisc(lex.getString()));
985 } else if (token == "\\bar") {
987 string const tok = lex.getString();
988 // This is dirty, but gone with LyX3. (Asger)
990 font.setUnderbar(LyXFont::ON);
991 else if (tok == "no")
992 font.setUnderbar(LyXFont::OFF);
993 else if (tok == "default")
994 font.setUnderbar(LyXFont::INHERIT);
996 lex.printError("Unknown bar font flag "
998 } else if (token == "\\noun") {
1000 font.setNoun(font.setLyXMisc(lex.getString()));
1001 } else if (token == "\\color") {
1003 font.setLyXColor(lex.getString());
1004 } else if (token == "\\align") {
1005 int tmpret = lex.findToken(string_align);
1006 if (tmpret == -1) ++tmpret;
1007 if (tmpret != LYX_LAYOUT_DEFAULT) { // tmpret != 99 ???
1008 int const tmpret2 = int(pow(2.0, tmpret));
1009 //lyxerr << "Tmpret2 = " << tmpret2 << endl;
1010 par->params().align(LyXAlignment(tmpret2));
1012 } else if (token == "\\added_space_top") {
1014 VSpace value = VSpace(lex.getString());
1015 if ((value.length().len().value() != 0) ||
1016 (value.kind() != VSpace::LENGTH))
1017 par->params().spaceTop(value);
1018 } else if (token == "\\added_space_bottom") {
1020 VSpace value = VSpace(lex.getString());
1021 if ((value.length().len().value() != 0) ||
1022 (value.kind() != VSpace::LENGTH))
1023 par->params().spaceBottom(value);
1024 #ifndef NO_COMPABILITY
1025 #ifndef NO_PEXTRA_REALLY
1026 } else if (token == "\\pextra_type") {
1028 par->params().pextraType(lex.getInteger());
1029 } else if (token == "\\pextra_width") {
1031 par->params().pextraWidth(lex.getString());
1032 } else if (token == "\\pextra_widthp") {
1034 par->params().pextraWidthp(lex.getString());
1035 } else if (token == "\\pextra_alignment") {
1037 par->params().pextraAlignment(lex.getInteger());
1038 } else if (token == "\\pextra_hfill") {
1040 par->params().pextraHfill(lex.getInteger());
1041 } else if (token == "\\pextra_start_minipage") {
1043 par->params().pextraStartMinipage(lex.getInteger());
1046 } else if (token == "\\labelwidthstring") {
1048 par->params().labelWidthString(lex.getString());
1049 // do not delete this token, it is still needed!
1050 } else if (token == "\\end_inset") {
1051 lyxerr << "Solitary \\end_inset. Missing \\begin_inset?.\n"
1052 << "Last inset read was: " << last_inset_read
1054 // Simply ignore this. The insets do not have
1056 // But insets should read it, it is a part of
1057 // the inset isn't it? Lgb.
1058 } else if (token == "\\begin_inset") {
1059 #ifndef NO_COMPABILITY
1060 insertErtContents(par, pos, false);
1061 ert_stack.push(ert_comp);
1062 ert_comp = ErtComp();
1064 readInset(lex, par, pos, font);
1065 #ifndef NO_COMPABILITY
1066 ert_comp = ert_stack.top();
1068 insertErtContents(par, pos);
1070 } else if (token == "\\SpecialChar") {
1071 LyXLayout const & layout =
1072 textclasslist[params.textclass][par->layout()];
1074 // Insets don't make sense in a free-spacing context! ---Kayvan
1075 if (layout.free_spacing || par->isFreeSpacing()) {
1078 string next_token = lex.getString();
1079 if (next_token == "\\-") {
1080 par->insertChar(pos, '-', font);
1081 } else if (next_token == "\\protected_separator"
1082 || next_token == "~") {
1083 par->insertChar(pos, ' ', font);
1085 lex.printError("Token `$$Token' "
1087 "paragraph layout!");
1092 Inset * inset = new InsetSpecialChar;
1093 inset->read(this, lex);
1094 par->insertInset(pos, inset, font);
1097 } else if (token == "\\newline") {
1098 #ifndef NO_COMPABILITY
1099 if (!ert_comp.in_tabular && ert_comp.active) {
1100 ert_comp.contents += char(Paragraph::META_NEWLINE);
1102 // Since we cannot know it this is only a regular
1103 // newline or a tabular cell delimter we have to
1104 // handle the ERT here.
1105 insertErtContents(par, pos, false);
1107 par->insertChar(pos, Paragraph::META_NEWLINE, font);
1111 par->insertChar(pos, Paragraph::META_NEWLINE, font);
1114 } else if (token == "\\LyXTable") {
1115 #ifndef NO_COMPABILITY
1116 ert_comp.in_tabular = true;
1118 Inset * inset = new InsetTabular(*this);
1119 inset->read(this, lex);
1120 par->insertInset(pos, inset, font);
1122 } else if (token == "\\hfill") {
1123 par->insertChar(pos, Paragraph::META_HFILL, font);
1125 } else if (token == "\\protected_separator") { // obsolete
1126 // This is a backward compability thingie. (Lgb)
1127 // Remove it later some time...introduced with fileformat
1129 LyXLayout const & layout =
1130 textclasslist[params.textclass][par->layout()];
1132 if (layout.free_spacing || par->isFreeSpacing()) {
1133 par->insertChar(pos, ' ', font);
1135 Inset * inset = new InsetSpecialChar(InsetSpecialChar::PROTECTED_SEPARATOR);
1136 par->insertInset(pos, inset, font);
1139 } else if (token == "\\bibitem") { // ale970302
1141 InsetCommandParams p("bibitem", "dummy");
1142 par->bibkey = new InsetBibKey(p);
1144 par->bibkey->read(this, lex);
1145 } else if (token == "\\backslash") {
1146 #ifndef NO_COMPABILITY
1147 if (ert_comp.active) {
1148 ert_comp.contents += "\\";
1151 par->insertChar(pos, '\\', font);
1153 #ifndef NO_COMPABILITY
1156 } else if (token == "\\the_end") {
1157 #ifndef NO_COMPABILITY
1158 // If we still have some ert active here we have to insert
1159 // it so we don't loose it. (Lgb)
1160 insertErtContents(par, pos);
1162 the_end_read = true;
1163 #ifndef NO_COMPABILITY
1164 #ifndef NO_PEXTRA_REALLY
1165 minipar = parBeforeMinipage = 0;
1169 #ifndef NO_COMPABILITY
1170 if (ert_comp.active) {
1171 ert_comp.contents += token;
1174 // This should be insurance for the future: (Asger)
1177 string const s = _("Unknown token: ") + token
1178 + " " + lex.text() + "\n";
1180 InsetError * new_inset = new InsetError(s);
1181 par->insertInset(pos, new_inset, LyXFont(LyXFont::ALL_INHERIT,
1184 #ifndef NO_COMPABILITY
1189 #ifndef NO_COMPABILITY
1190 #ifndef NO_PEXTRA_REALLY
1191 // I wonder if we could use this blanket fix for all the
1192 // checkminipage cases...
1193 // don't forget about ert paragraphs and compatibility read for'em
1194 if (par && (par->size() || !ert_comp.contents.empty())) {
1195 // It is possible that this will check to often,
1196 // but that should not be an correctness issue.
1197 // Only a speed issue.
1198 checkminipage = true;
1201 // now check if we have a minipage paragraph as at this
1202 // point we already read all the necessary data!
1203 // this cannot be done in layout because there we did
1204 // not read yet the paragraph PEXTRA-params (Jug)
1206 // BEGIN pextra_minipage compability
1207 // This should be removed in 1.3.x (Lgb)
1208 // I don't think we should remove this so fast (Jug)
1210 // This compability code is not perfect. In a couple
1211 // of rand cases it fails. When the minipage par is
1212 // the first par in the document, and when there are
1213 // none or only one regular paragraphs after the
1214 // minipage. Currently I am not investing any effort
1215 // in fixing those cases.
1217 //lyxerr << "Call depth: " << call_depth << endl;
1218 if (checkminipage && (call_depth == 1)) {
1219 checkminipage = false;
1220 if (minipar && (minipar != par) &&
1221 (par->params().pextraType() == Paragraph::PEXTRA_MINIPAGE)) {
1222 lyxerr << "minipages in a row" << endl;
1223 if (par->params().pextraStartMinipage()) {
1224 lyxerr << "start new minipage" << endl;
1225 // minipages in a row
1226 par->previous()->next(0);
1229 Paragraph * tmp = minipar;
1231 tmp->params().pextraType(0);
1232 tmp->params().pextraWidth(string());
1233 tmp->params().pextraWidthp(string());
1234 tmp->params().pextraAlignment(0);
1235 tmp->params().pextraHfill(false);
1236 tmp->params().pextraStartMinipage(false);
1239 // create a new paragraph to insert the
1240 // minipages in the following case
1241 if (par->params().pextraStartMinipage() &&
1242 !par->params().pextraHfill()) {
1243 Paragraph * p = new Paragraph;
1244 p->layout(textclasslist[params.textclass].defaultLayoutName());
1246 p->previous(parBeforeMinipage);
1247 parBeforeMinipage->next(p);
1249 p->params().depth(parBeforeMinipage->params().depth());
1250 parBeforeMinipage = p;
1252 InsetMinipage * mini = new InsetMinipage;
1253 mini->pos(static_cast<InsetMinipage::Position>(par->params().pextraAlignment()));
1254 mini->pageWidth(LyXLength(par->params().pextraWidth()));
1255 if (!par->params().pextraWidthp().empty()) {
1256 lyxerr << "WP:" << mini->pageWidth().asString() << endl;
1257 mini->pageWidth(LyXLength((par->params().pextraWidthp())+"%"));
1259 Paragraph * op = mini->firstParagraph();
1260 mini->inset.paragraph(par);
1262 // and free the old ones!
1265 Paragraph * pp = op->next();
1269 // Insert the minipage last in the
1270 // previous paragraph.
1271 if (par->params().pextraHfill()) {
1272 parBeforeMinipage->insertChar
1273 (parBeforeMinipage->size(), Paragraph::META_HFILL);
1275 parBeforeMinipage->insertInset
1276 (parBeforeMinipage->size(), mini);
1280 lyxerr << "new minipage par" << endl;
1281 //nothing to do just continue reading
1284 } else if (minipar && (minipar != par)) {
1285 lyxerr << "last minipage par read" << endl;
1286 // The last paragraph read was not part of a
1287 // minipage but the par linked list is...
1288 // So we need to remove the last par from the
1290 if (par->previous())
1291 par->previous()->next(0);
1292 par->previous(parBeforeMinipage);
1293 parBeforeMinipage->next(par);
1294 Paragraph * tmp = minipar;
1296 tmp->params().pextraType(0);
1297 tmp->params().pextraWidth(string());
1298 tmp->params().pextraWidthp(string());
1299 tmp->params().pextraAlignment(0);
1300 tmp->params().pextraHfill(false);
1301 tmp->params().pextraStartMinipage(false);
1304 depth = parBeforeMinipage->params().depth();
1305 // and set this depth on the par as it has not been set already
1306 par->params().depth(depth);
1307 minipar = parBeforeMinipage = 0;
1308 } else if (!minipar &&
1309 (par->params().pextraType() == Paragraph::PEXTRA_MINIPAGE))
1311 // par is the first paragraph in a minipage
1312 lyxerr << "begin minipage" << endl;
1313 // To minimize problems for
1314 // the users we will insert
1315 // the first minipage in
1316 // a sequence of minipages
1317 // in its own paragraph.
1318 Paragraph * p = new Paragraph;
1319 p->layout(textclasslist[params.textclass].defaultLayoutName());
1320 p->previous(par->previous());
1322 p->params().depth(depth);
1323 par->params().depth(0);
1325 if (par->previous())
1326 par->previous()->next(p);
1328 parBeforeMinipage = p;
1330 if (!first_par || (first_par == par))
1333 InsetMinipage * mini = new InsetMinipage;
1334 mini->pos(static_cast<InsetMinipage::Position>(minipar->params().pextraAlignment()));
1335 mini->pageWidth(LyXLength(minipar->params().pextraWidth()));
1336 if (!par->params().pextraWidthp().empty()) {
1337 lyxerr << "WP:" << mini->pageWidth().asString() << endl;
1338 mini->pageWidth(LyXLength((par->params().pextraWidthp())+"%"));
1340 mini->inset.paragraph(minipar);
1342 // Insert the minipage last in the
1343 // previous paragraph.
1344 if (minipar->params().pextraHfill()) {
1345 parBeforeMinipage->insertChar
1346 (parBeforeMinipage->size(),Paragraph::META_HFILL);
1348 parBeforeMinipage->insertInset
1349 (parBeforeMinipage->size(), mini);
1352 // End of pextra_minipage compability
1356 return the_end_read;
1359 // needed to insert the selection
1360 void Buffer::insertStringAsLines(Paragraph *& par, pos_type & pos,
1361 LyXFont const & fn,string const & str) const
1363 LyXLayout const & layout =
1364 textclasslist[params.textclass][par->layout()];
1367 par->checkInsertChar(font);
1368 // insert the string, don't insert doublespace
1369 bool space_inserted = true;
1370 for(string::const_iterator cit = str.begin();
1371 cit != str.end(); ++cit) {
1373 if (par->size() || layout.keepempty) {
1374 par->breakParagraph(params, pos,
1375 layout.isEnvironment());
1378 space_inserted = true;
1382 // do not insert consecutive spaces if !free_spacing
1383 } else if ((*cit == ' ' || *cit == '\t') &&
1384 space_inserted && !layout.free_spacing &&
1385 !par->isFreeSpacing())
1388 } else if (*cit == '\t') {
1389 if (!layout.free_spacing && !par->isFreeSpacing()) {
1390 // tabs are like spaces here
1391 par->insertChar(pos, ' ', font);
1393 space_inserted = true;
1395 const pos_type nb = 8 - pos % 8;
1396 for (pos_type a = 0; a < nb ; ++a) {
1397 par->insertChar(pos, ' ', font);
1400 space_inserted = true;
1402 } else if (!IsPrintable(*cit)) {
1403 // Ignore unprintables
1406 // just insert the character
1407 par->insertChar(pos, *cit, font);
1409 space_inserted = (*cit == ' ');
1416 void Buffer::readInset(LyXLex & lex, Paragraph *& par,
1417 int & pos, LyXFont & font)
1419 // consistency check
1420 if (lex.getString() != "\\begin_inset") {
1421 lyxerr << "Buffer::readInset: Consistency check failed."
1428 string const tmptok = lex.getString();
1429 last_inset_read = tmptok;
1431 // test the different insets
1432 if (tmptok == "LatexCommand") {
1433 InsetCommandParams inscmd;
1436 string const cmdName = inscmd.getCmdName();
1438 // This strange command allows LyX to recognize "natbib" style
1439 // citations: citet, citep, Citet etc.
1440 if (compare_no_case(cmdName, "cite", 4) == 0) {
1441 inset = new InsetCitation(inscmd);
1442 } else if (cmdName == "bibitem") {
1443 lex.printError("Wrong place for bibitem");
1444 inset = new InsetBibKey(inscmd);
1445 } else if (cmdName == "BibTeX") {
1446 inset = new InsetBibtex(inscmd);
1447 } else if (cmdName == "index") {
1448 inset = new InsetIndex(inscmd);
1449 } else if (cmdName == "include") {
1450 inset = new InsetInclude(inscmd, *this);
1451 } else if (cmdName == "label") {
1452 inset = new InsetLabel(inscmd);
1453 } else if (cmdName == "url"
1454 || cmdName == "htmlurl") {
1455 inset = new InsetUrl(inscmd);
1456 } else if (cmdName == "ref"
1457 || cmdName == "pageref"
1458 || cmdName == "vref"
1459 || cmdName == "vpageref"
1460 || cmdName == "prettyref") {
1461 if (!inscmd.getOptions().empty()
1462 || !inscmd.getContents().empty()) {
1463 inset = new InsetRef(inscmd, *this);
1465 } else if (cmdName == "tableofcontents") {
1466 inset = new InsetTOC(inscmd);
1467 } else if (cmdName == "listofalgorithms") {
1468 inset = new InsetFloatList("algorithm");
1469 } else if (cmdName == "listoffigures") {
1470 inset = new InsetFloatList("figure");
1471 } else if (cmdName == "listoftables") {
1472 inset = new InsetFloatList("table");
1473 } else if (cmdName == "printindex") {
1474 inset = new InsetPrintIndex(inscmd);
1475 } else if (cmdName == "lyxparent") {
1476 inset = new InsetParent(inscmd, *this);
1479 bool alreadyread = false;
1480 if (tmptok == "Quotes") {
1481 inset = new InsetQuotes;
1482 } else if (tmptok == "External") {
1483 inset = new InsetExternal;
1484 } else if (tmptok == "FormulaMacro") {
1485 inset = new InsetFormulaMacro;
1486 } else if (tmptok == "Formula") {
1487 inset = new InsetFormula;
1488 } else if (tmptok == "Figure") { // Backward compatibility
1489 // inset = new InsetFig(100, 100, *this);
1490 inset = new InsetGraphics;
1491 } else if (tmptok == "Graphics") {
1492 inset = new InsetGraphics;
1493 } else if (tmptok == "Info") {// backwards compatibility
1494 inset = new InsetNote(this,
1495 lex.getLongString("\\end_inset"),
1498 } else if (tmptok == "Note") {
1499 inset = new InsetNote;
1500 } else if (tmptok == "Include") {
1501 InsetCommandParams p("Include");
1502 inset = new InsetInclude(p, *this);
1503 } else if (tmptok == "ERT") {
1504 inset = new InsetERT;
1505 } else if (tmptok == "Tabular") {
1506 inset = new InsetTabular(*this);
1507 } else if (tmptok == "Text") {
1508 inset = new InsetText;
1509 } else if (tmptok == "Foot") {
1510 inset = new InsetFoot;
1511 } else if (tmptok == "Marginal") {
1512 inset = new InsetMarginal;
1513 } else if (tmptok == "Minipage") {
1514 inset = new InsetMinipage;
1515 } else if (tmptok == "Float") {
1517 string tmptok = lex.getString();
1518 inset = new InsetFloat(tmptok);
1520 } else if (tmptok == "List") {
1521 inset = new InsetList;
1522 } else if (tmptok == "Theorem") {
1523 inset = new InsetList;
1525 } else if (tmptok == "Caption") {
1526 inset = new InsetCaption;
1527 } else if (tmptok == "FloatList") {
1528 inset = new InsetFloatList;
1531 if (inset && !alreadyread) inset->read(this, lex);
1535 par->insertInset(pos, inset, font);
1541 bool Buffer::readFile(LyXLex & lex, Paragraph * par)
1545 string const token(lex.getString());
1546 if (token == "\\lyxformat") { // the first token _must_ be...
1548 string tmp_format = lex.getString();
1549 //lyxerr << "LyX Format: `" << tmp_format << "'" << endl;
1550 // if present remove ".," from string.
1551 string::size_type dot = tmp_format.find_first_of(".,");
1552 //lyxerr << " dot found at " << dot << endl;
1553 if (dot != string::npos)
1554 tmp_format.erase(dot, 1);
1555 file_format = strToInt(tmp_format);
1556 if (file_format == LYX_FORMAT) {
1558 } else if (file_format > LYX_FORMAT) {
1560 Alert::alert(_("Warning!"),
1561 _("LyX file format is newer that what"),
1562 _("is supported in this LyX version. Expect some problems."));
1564 } else if (file_format < LYX_FORMAT) {
1566 if (file_format < 200) {
1567 Alert::alert(_("ERROR!"),
1568 _("Old LyX file format found. "
1569 "Use LyX 0.10.x to read this!"));
1573 bool the_end = readLyXformat2(lex, par);
1574 params.setPaperStuff();
1575 // the_end was added in 213
1576 if (file_format < 213)
1580 Alert::alert(_("Warning!"),
1581 _("Reading of document is not complete"),
1582 _("Maybe the document is truncated"));
1585 } else { // "\\lyxformat" not found
1586 Alert::alert(_("ERROR!"), _("Not a LyX file!"));
1589 Alert::alert(_("ERROR!"), _("Unable to read file!"));
1594 // Should probably be moved to somewhere else: BufferView? LyXView?
1595 bool Buffer::save() const
1597 // We don't need autosaves in the immediate future. (Asger)
1598 resetAutosaveTimers();
1602 if (lyxrc.make_backup) {
1603 s = fileName() + '~';
1604 if (!lyxrc.backupdir_path.empty())
1605 s = AddName(lyxrc.backupdir_path,
1606 subst(os::slashify_path(s),'/','!'));
1608 // Rename is the wrong way of making a backup,
1609 // this is the correct way.
1610 /* truss cp fil fil2:
1611 lstat("LyXVC3.lyx", 0xEFFFF898) Err#2 ENOENT
1612 stat("LyXVC.lyx", 0xEFFFF688) = 0
1613 open("LyXVC.lyx", O_RDONLY) = 3
1614 open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
1615 fstat(4, 0xEFFFF508) = 0
1616 fstat(3, 0xEFFFF508) = 0
1617 read(3, " # T h i s f i l e w".., 8192) = 5579
1618 write(4, " # T h i s f i l e w".., 5579) = 5579
1619 read(3, 0xEFFFD4A0, 8192) = 0
1622 chmod("LyXVC3.lyx", 0100644) = 0
1623 lseek(0, 0, SEEK_CUR) = 46440
1627 // Should probably have some more error checking here.
1628 // Should be cleaned up in 0.13, at least a bit.
1629 // Doing it this way, also makes the inodes stay the same.
1630 // This is still not a very good solution, in particular we
1631 // might loose the owner of the backup.
1632 FileInfo finfo(fileName());
1633 if (finfo.exist()) {
1634 mode_t fmode = finfo.getMode();
1635 struct utimbuf times = {
1636 finfo.getAccessTime(),
1637 finfo.getModificationTime() };
1639 ifstream ifs(fileName().c_str());
1640 ofstream ofs(s.c_str(), ios::out|ios::trunc);
1645 ::chmod(s.c_str(), fmode);
1647 if (::utime(s.c_str(), ×)) {
1648 lyxerr << "utime error." << endl;
1651 lyxerr << "LyX was not able to make "
1652 "backup copy. Beware." << endl;
1657 if (writeFile(fileName(), false)) {
1659 removeAutosaveFile(fileName());
1661 // Saving failed, so backup is not backup
1662 if (lyxrc.make_backup) {
1663 lyx::rename(s, fileName());
1671 // Returns false if unsuccesful
1672 bool Buffer::writeFile(string const & fname, bool flag) const
1674 // if flag is false writeFile will not create any GUI
1675 // warnings, only cerr.
1676 // Needed for autosave in background or panic save (Matthias 120496)
1678 if (read_only && (fname == fileName())) {
1679 // Here we should come with a question if we should
1680 // perform the write anyway.
1682 lyxerr << _("Error! Document is read-only: ")
1685 Alert::alert(_("Error! Document is read-only: "),
1690 FileInfo finfo(fname);
1691 if (finfo.exist() && !finfo.writable()) {
1692 // Here we should come with a question if we should
1693 // try to do the save anyway. (i.e. do a chmod first)
1695 lyxerr << _("Error! Cannot write file: ")
1698 Alert::err_alert(_("Error! Cannot write file: "),
1703 ofstream ofs(fname.c_str());
1706 lyxerr << _("Error! Cannot open file: ")
1709 Alert::err_alert(_("Error! Cannot open file: "),
1715 // Use the standard "C" locale for file output.
1716 ofs.imbue(std::locale::classic());
1719 // The top of the file should not be written by params.
1721 // write out a comment in the top of the file
1722 ofs << '#' << lyx_docversion
1723 << " created this file. For more info see http://www.lyx.org/\n"
1724 << "\\lyxformat " << LYX_FORMAT << "\n";
1726 // now write out the buffer paramters.
1727 params.writeFile(ofs);
1729 Paragraph::depth_type depth = 0;
1731 // this will write out all the paragraphs
1732 // using recursive descent.
1733 paragraph->writeFile(this, ofs, params, depth);
1735 // Write marker that shows file is complete
1736 ofs << "\n\\the_end" << endl;
1740 // how to check if close went ok?
1741 // Following is an attempt... (BE 20001011)
1743 // good() returns false if any error occured, including some
1744 // formatting error.
1745 // bad() returns true if something bad happened in the buffer,
1746 // which should include file system full errors.
1753 lyxerr << "Buffer::writeFile: BAD ERROR!" << endl;
1755 lyxerr << "Buffer::writeFile: NOT SO BAD ERROR!"
1765 string const Buffer::asciiParagraph(Paragraph const * par,
1766 unsigned int linelen,
1767 bool noparbreak) const
1769 ostringstream buffer;
1771 Paragraph::depth_type depth = 0;
1773 Paragraph::depth_type ltype_depth = 0;
1774 string::size_type currlinelen = 0;
1775 bool ref_printed = false;
1776 // if (!par->previous()) {
1778 // begins or ends a deeper area ?
1779 if (depth != par->params().depth()) {
1780 if (par->params().depth() > depth) {
1781 while (par->params().depth() > depth) {
1785 while (par->params().depth() < depth) {
1791 depth = par->params().depth();
1794 // First write the layout
1795 string const & tmp = lowercase(par->layout());
1796 if (tmp == "itemize") {
1798 ltype_depth = depth + 1;
1799 } else if (tmp == "enumerate") {
1801 ltype_depth = depth + 1;
1802 } else if (contains(tmp, "ection")) {
1804 ltype_depth = depth + 1;
1805 } else if (contains(tmp, "aragraph")) {
1807 ltype_depth = depth + 1;
1808 } else if (tmp == "description") {
1810 ltype_depth = depth + 1;
1811 } else if (tmp == "abstract") {
1814 } else if (tmp == "bibliography") {
1822 /* maybe some vertical spaces */
1824 /* the labelwidthstring used in lists */
1828 /* some pagebreaks? */
1832 /* what about the alignment */
1834 // lyxerr << "Should this ever happen?" << endl;
1837 // linelen <= 0 is special and means we don't have pargraph breaks
1841 for (Paragraph::depth_type j = 0; j < depth; ++j)
1843 currlinelen = depth * 2;
1845 // we should probably change to the paragraph language in the
1846 // gettext here (if possible) so that strings are outputted in
1847 // the correct language! (20012712 Jug)
1851 case 4: // (Sub)Paragraph
1852 case 5: // Description
1856 buffer << _("Abstract") << "\n\n";
1858 buffer << _("Abstract: ");
1860 case 7: // Bibliography
1863 buffer << _("References") << "\n\n";
1865 buffer << _("References: ");
1870 buffer << par->params().labelString() << " ";
1874 string s = buffer.str();
1875 if (s.rfind('\n') != string::npos) {
1877 s = rsplit(buffer.str().c_str(), dummy, '\n');
1879 currlinelen = s.length();
1881 for (Paragraph::depth_type j = 0; j < depth; ++j)
1883 currlinelen = depth * 2;
1884 if (ltype_depth > depth) {
1885 for (Paragraph::depth_type j = ltype_depth;
1890 currlinelen += (ltype_depth-depth)*2;
1893 // this is to change the linebreak to do it by word a bit more intelligent
1894 // hopefully! (only in the case where we have a max linelenght!) (Jug)
1895 for (pos_type i = 0; i < par->size(); ++i) {
1896 char c = par->getUChar(params, i);
1898 case Paragraph::META_INSET:
1900 Inset const * inset = par->getInset(i);
1903 buffer << word.str();
1906 if (inset->ascii(this, buffer, linelen)) {
1907 // to be sure it breaks paragraph
1908 currlinelen += linelen;
1914 rsplit(buffer.str().c_str(),
1916 currlinelen = s.length();
1923 case Paragraph::META_NEWLINE:
1925 buffer << word.str() << "\n";
1927 for (Paragraph::depth_type j = 0;
1930 currlinelen = depth * 2;
1931 if (ltype_depth > depth) {
1932 for (Paragraph::depth_type j = ltype_depth;
1935 currlinelen += (ltype_depth - depth) * 2;
1940 case Paragraph::META_HFILL:
1941 buffer << word.str() << "\t";
1942 currlinelen += word.str().length() + 1;
1948 buffer << word.str() << ' ';
1949 currlinelen += word.str().length() + 1;
1955 lyxerr[Debug::INFO] <<
1956 "writeAsciiFile: NULL char in structure." << endl;
1958 if ((linelen > 0) &&
1959 (currlinelen+word.str().length()) > linelen)
1962 for (Paragraph::depth_type j = 0; j < depth; ++j)
1964 currlinelen = depth * 2;
1965 if (ltype_depth > depth) {
1966 for (Paragraph::depth_type j = ltype_depth;
1971 currlinelen += (ltype_depth-depth)*2;
1978 buffer << word.str();
1979 return buffer.str().c_str();
1983 void Buffer::writeFileAscii(string const & fname, int linelen)
1985 ofstream ofs(fname.c_str());
1987 Alert::err_alert(_("Error: Cannot write file:"), fname);
1990 writeFileAscii(ofs, linelen);
1994 void Buffer::writeFileAscii(ostream & ofs, int linelen)
1996 Paragraph * par = paragraph;
1998 ofs << asciiParagraph(par, linelen, par->previous() == 0);
2008 void Buffer::makeLaTeXFile(string const & fname,
2009 string const & original_path,
2010 bool nice, bool only_body)
2012 lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
2014 niceFile = nice; // this will be used by Insetincludes.
2016 tex_code_break_column = lyxrc.ascii_linelen;
2018 LyXTextClass const & tclass =
2019 textclasslist[params.textclass];
2021 ofstream ofs(fname.c_str());
2023 Alert::err_alert(_("Error: Cannot open file: "), fname);
2027 // validate the buffer.
2028 lyxerr[Debug::LATEX] << " Validating buffer..." << endl;
2029 LaTeXFeatures features(params, tclass.size());
2031 lyxerr[Debug::LATEX] << " Buffer validation done." << endl;
2034 // The starting paragraph of the coming rows is the
2035 // first paragraph of the document. (Asger)
2036 texrow.start(paragraph, 0);
2038 if (!only_body && nice) {
2039 ofs << "%% " << lyx_docversion << " created this file. "
2040 "For more info, see http://www.lyx.org/.\n"
2041 "%% Do not edit unless you really know what "
2046 lyxerr[Debug::INFO] << "lyx header finished" << endl;
2047 // There are a few differences between nice LaTeX and usual files:
2048 // usual is \batchmode and has a
2049 // special input@path to allow the including of figures
2050 // with either \input or \includegraphics (what figinsets do).
2051 // batchmode is not set if there is a tex_code_break_column.
2052 // In this case somebody is interested in the generated LaTeX,
2053 // so this is OK. input@path is set when the actual parameter
2054 // original_path is set. This is done for usual tex-file, but not
2055 // for nice-latex-file. (Matthias 250696)
2058 // code for usual, NOT nice-latex-file
2059 ofs << "\\batchmode\n"; // changed
2060 // from \nonstopmode
2063 if (!original_path.empty()) {
2064 ofs << "\\makeatletter\n"
2065 << "\\def\\input@path{{"
2066 << os::external_path(original_path) << "/}}\n"
2067 << "\\makeatother\n";
2073 ofs << "\\documentclass";
2075 ostringstream options; // the document class options.
2077 if (tokenPos(tclass.opt_fontsize(),
2078 '|', params.fontsize) >= 0) {
2079 // only write if existing in list (and not default)
2080 options << params.fontsize << "pt,";
2084 if (!params.use_geometry &&
2085 (params.paperpackage == BufferParams::PACKAGE_NONE)) {
2086 switch (params.papersize) {
2087 case BufferParams::PAPER_A4PAPER:
2088 options << "a4paper,";
2090 case BufferParams::PAPER_USLETTER:
2091 options << "letterpaper,";
2093 case BufferParams::PAPER_A5PAPER:
2094 options << "a5paper,";
2096 case BufferParams::PAPER_B5PAPER:
2097 options << "b5paper,";
2099 case BufferParams::PAPER_EXECUTIVEPAPER:
2100 options << "executivepaper,";
2102 case BufferParams::PAPER_LEGALPAPER:
2103 options << "legalpaper,";
2109 if (params.sides != tclass.sides()) {
2110 switch (params.sides) {
2111 case LyXTextClass::OneSide:
2112 options << "oneside,";
2114 case LyXTextClass::TwoSides:
2115 options << "twoside,";
2121 if (params.columns != tclass.columns()) {
2122 if (params.columns == 2)
2123 options << "twocolumn,";
2125 options << "onecolumn,";
2128 if (!params.use_geometry
2129 && params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
2130 options << "landscape,";
2132 // language should be a parameter to \documentclass
2134 ostringstream language_options;
2135 if (params.language->babel() == "hebrew"
2136 && default_language->babel() != "hebrew")
2137 // This seems necessary
2138 features.useLanguage(default_language);
2140 if (lyxrc.language_use_babel ||
2141 params.language->lang() != lyxrc.default_language ||
2142 !features.hasLanguages()) {
2144 language_options << features.getLanguages();
2145 language_options << params.language->babel();
2146 if (lyxrc.language_global_options)
2147 options << language_options.str() << ',';
2150 // the user-defined options
2151 if (!params.options.empty()) {
2152 options << params.options << ',';
2155 string strOptions(options.str().c_str());
2156 if (!strOptions.empty()) {
2157 strOptions = strip(strOptions, ',');
2158 ofs << '[' << strOptions << ']';
2162 << textclasslist[params.textclass].latexname()
2165 // end of \documentclass defs
2167 // font selection must be done before loading fontenc.sty
2168 // The ae package is not needed when using OT1 font encoding.
2169 if (params.fonts != "default" &&
2170 (params.fonts != "ae" || lyxrc.fontenc != "default")) {
2171 ofs << "\\usepackage{" << params.fonts << "}\n";
2173 if (params.fonts == "ae") {
2174 ofs << "\\usepackage{aecompl}\n";
2178 // this one is not per buffer
2179 if (lyxrc.fontenc != "default") {
2180 ofs << "\\usepackage[" << lyxrc.fontenc
2185 if (params.inputenc == "auto") {
2186 string const doc_encoding =
2187 params.language->encoding()->LatexName();
2189 // Create a list with all the input encodings used
2191 set<string> encodings = features.getEncodingSet(doc_encoding);
2193 ofs << "\\usepackage[";
2194 std::copy(encodings.begin(), encodings.end(),
2195 std::ostream_iterator<string>(ofs, ","));
2196 ofs << doc_encoding << "]{inputenc}\n";
2198 } else if (params.inputenc != "default") {
2199 ofs << "\\usepackage[" << params.inputenc
2204 // At the very beginning the text parameters.
2205 if (params.paperpackage != BufferParams::PACKAGE_NONE) {
2206 switch (params.paperpackage) {
2207 case BufferParams::PACKAGE_A4:
2208 ofs << "\\usepackage{a4}\n";
2211 case BufferParams::PACKAGE_A4WIDE:
2212 ofs << "\\usepackage{a4wide}\n";
2215 case BufferParams::PACKAGE_WIDEMARGINSA4:
2216 ofs << "\\usepackage[widemargins]{a4}\n";
2221 if (params.use_geometry) {
2222 ofs << "\\usepackage{geometry}\n";
2224 ofs << "\\geometry{verbose";
2225 if (params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
2226 ofs << ",landscape";
2227 switch (params.papersize2) {
2228 case BufferParams::VM_PAPER_CUSTOM:
2229 if (!params.paperwidth.empty())
2230 ofs << ",paperwidth="
2231 << params.paperwidth;
2232 if (!params.paperheight.empty())
2233 ofs << ",paperheight="
2234 << params.paperheight;
2236 case BufferParams::VM_PAPER_USLETTER:
2237 ofs << ",letterpaper";
2239 case BufferParams::VM_PAPER_USLEGAL:
2240 ofs << ",legalpaper";
2242 case BufferParams::VM_PAPER_USEXECUTIVE:
2243 ofs << ",executivepaper";
2245 case BufferParams::VM_PAPER_A3:
2248 case BufferParams::VM_PAPER_A4:
2251 case BufferParams::VM_PAPER_A5:
2254 case BufferParams::VM_PAPER_B3:
2257 case BufferParams::VM_PAPER_B4:
2260 case BufferParams::VM_PAPER_B5:
2264 // default papersize ie BufferParams::VM_PAPER_DEFAULT
2265 switch (lyxrc.default_papersize) {
2266 case BufferParams::PAPER_DEFAULT: // keep compiler happy
2267 case BufferParams::PAPER_USLETTER:
2268 ofs << ",letterpaper";
2270 case BufferParams::PAPER_LEGALPAPER:
2271 ofs << ",legalpaper";
2273 case BufferParams::PAPER_EXECUTIVEPAPER:
2274 ofs << ",executivepaper";
2276 case BufferParams::PAPER_A3PAPER:
2279 case BufferParams::PAPER_A4PAPER:
2282 case BufferParams::PAPER_A5PAPER:
2285 case BufferParams::PAPER_B5PAPER:
2290 if (!params.topmargin.empty())
2291 ofs << ",tmargin=" << params.topmargin;
2292 if (!params.bottommargin.empty())
2293 ofs << ",bmargin=" << params.bottommargin;
2294 if (!params.leftmargin.empty())
2295 ofs << ",lmargin=" << params.leftmargin;
2296 if (!params.rightmargin.empty())
2297 ofs << ",rmargin=" << params.rightmargin;
2298 if (!params.headheight.empty())
2299 ofs << ",headheight=" << params.headheight;
2300 if (!params.headsep.empty())
2301 ofs << ",headsep=" << params.headsep;
2302 if (!params.footskip.empty())
2303 ofs << ",footskip=" << params.footskip;
2308 if (tokenPos(tclass.opt_pagestyle(),
2309 '|', params.pagestyle) >= 0) {
2310 if (params.pagestyle == "fancy") {
2311 ofs << "\\usepackage{fancyhdr}\n";
2314 ofs << "\\pagestyle{" << params.pagestyle << "}\n";
2318 if (params.secnumdepth != tclass.secnumdepth()) {
2319 ofs << "\\setcounter{secnumdepth}{"
2320 << params.secnumdepth
2324 if (params.tocdepth != tclass.tocdepth()) {
2325 ofs << "\\setcounter{tocdepth}{"
2331 if (params.paragraph_separation) {
2332 switch (params.defskip.kind()) {
2333 case VSpace::SMALLSKIP:
2334 ofs << "\\setlength\\parskip{\\smallskipamount}\n";
2336 case VSpace::MEDSKIP:
2337 ofs << "\\setlength\\parskip{\\medskipamount}\n";
2339 case VSpace::BIGSKIP:
2340 ofs << "\\setlength\\parskip{\\bigskipamount}\n";
2342 case VSpace::LENGTH:
2343 ofs << "\\setlength\\parskip{"
2344 << params.defskip.length().asLatexString()
2347 default: // should never happen // Then delete it.
2348 ofs << "\\setlength\\parskip{\\medskipamount}\n";
2353 ofs << "\\setlength\\parindent{0pt}\n";
2357 // Now insert the LyX specific LaTeX commands...
2359 // The optional packages;
2360 string preamble(features.getPackages());
2362 // this might be useful...
2363 preamble += "\n\\makeatletter\n";
2365 // Some macros LyX will need
2366 string tmppreamble(features.getMacros());
2368 if (!tmppreamble.empty()) {
2369 preamble += "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2370 "LyX specific LaTeX commands.\n"
2371 + tmppreamble + '\n';
2374 // the text class specific preamble
2375 tmppreamble = features.getTClassPreamble();
2376 if (!tmppreamble.empty()) {
2377 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2378 "Textclass specific LaTeX commands.\n"
2379 + tmppreamble + '\n';
2382 /* the user-defined preamble */
2383 if (!params.preamble.empty()) {
2384 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2385 "User specified LaTeX commands.\n"
2386 + params.preamble + '\n';
2389 preamble += "\\makeatother\n";
2391 // Itemize bullet settings need to be last in case the user
2392 // defines their own bullets that use a package included
2393 // in the user-defined preamble -- ARRae
2394 // Actually it has to be done much later than that
2395 // since some packages like frenchb make modifications
2396 // at \begin{document} time -- JMarc
2398 for (int i = 0; i < 4; ++i) {
2399 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
2400 if (bullets_def.empty())
2401 bullets_def="\\AtBeginDocument{\n";
2402 bullets_def += " \\renewcommand{\\labelitemi";
2404 // `i' is one less than the item to modify
2411 bullets_def += "ii";
2417 bullets_def += "}{" +
2418 params.user_defined_bullets[i].getText()
2423 if (!bullets_def.empty())
2424 preamble += bullets_def + "}\n\n";
2427 int(lyx::count(preamble.begin(), preamble.end(), '\n'));
2428 for (int j = 0; j != nlines; ++j) {
2434 // We try to load babel late, in case it interferes
2435 // with other packages.
2437 string tmp = lyxrc.language_package;
2438 if (!lyxrc.language_global_options
2439 && tmp == "\\usepackage{babel}")
2440 tmp = string("\\usepackage[") +
2441 language_options.str().c_str() +
2448 ofs << "\\begin{document}\n";
2451 lyxerr[Debug::INFO] << "preamble finished, now the body." << endl;
2453 if (!lyxrc.language_auto_begin) {
2454 ofs << subst(lyxrc.language_command_begin, "$$lang",
2455 params.language->babel())
2460 latexParagraphs(ofs, paragraph, 0, texrow);
2462 // add this just in case after all the paragraphs
2466 if (!lyxrc.language_auto_end) {
2467 ofs << subst(lyxrc.language_command_end, "$$lang",
2468 params.language->babel())
2474 ofs << "\\end{document}\n";
2477 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
2479 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
2483 // Just to be sure. (Asger)
2486 // tex_code_break_column's value is used to decide
2487 // if we are in batchmode or not (within mathed_write()
2488 // in math_write.C) so we must set it to a non-zero
2489 // value when we leave otherwise we save incorrect .lyx files.
2490 tex_code_break_column = lyxrc.ascii_linelen;
2494 lyxerr << "File was not closed properly." << endl;
2497 lyxerr[Debug::INFO] << "Finished making latex file." << endl;
2498 lyxerr[Debug::INFO] << "Row count was " << texrow.rows()-1 << "." << endl;
2503 // LaTeX all paragraphs from par to endpar, if endpar == 0 then to the end
2505 void Buffer::latexParagraphs(ostream & ofs, Paragraph * par,
2506 Paragraph * endpar, TexRow & texrow) const
2508 bool was_title = false;
2509 bool already_title = false;
2512 while (par != endpar) {
2513 Inset * in = par->inInset();
2514 // well we have to check if we are in an inset with unlimited
2515 // lenght (all in one row) if that is true then we don't allow
2516 // any special options in the paragraph and also we don't allow
2517 // any environment other then "Standard" to be valid!
2518 if ((in == 0) || !in->forceDefaultParagraphs(in)) {
2519 LyXLayout const & layout =
2520 textclasslist[params.textclass][par->layout()];
2522 if (layout.intitle) {
2523 if (already_title) {
2524 lyxerr <<"Error in latexParagraphs: You"
2525 " should not mix title layouts"
2526 " with normal ones." << endl;
2529 } else if (was_title && !already_title) {
2530 ofs << "\\maketitle\n";
2532 already_title = true;
2536 if (layout.isEnvironment()) {
2537 par = par->TeXEnvironment(this, params, ofs, texrow);
2539 par = par->TeXOnePar(this, params, ofs, texrow, false);
2542 par = par->TeXOnePar(this, params, ofs, texrow, false);
2545 // It might be that we only have a title in this document
2546 if (was_title && !already_title) {
2547 ofs << "\\maketitle\n";
2553 bool Buffer::isLatex() const
2555 return textclasslist[params.textclass].outputType() == LATEX;
2559 bool Buffer::isLinuxDoc() const
2561 return textclasslist[params.textclass].outputType() == LINUXDOC;
2565 bool Buffer::isLiterate() const
2567 return textclasslist[params.textclass].outputType() == LITERATE;
2571 bool Buffer::isDocBook() const
2573 return textclasslist[params.textclass].outputType() == DOCBOOK;
2577 bool Buffer::isSGML() const
2579 LyXTextClass const & tclass = textclasslist[params.textclass];
2581 return tclass.outputType() == LINUXDOC ||
2582 tclass.outputType() == DOCBOOK;
2586 void Buffer::sgmlOpenTag(ostream & os, Paragraph::depth_type depth,
2587 string const & latexname) const
2589 if (!latexname.empty() && latexname != "!-- --")
2590 //os << "<!-- " << depth << " -->" << "<" << latexname << ">";
2591 os << string(depth, ' ') << "<" << latexname << ">\n";
2595 void Buffer::sgmlCloseTag(ostream & os, Paragraph::depth_type depth,
2596 string const & latexname) const
2598 if (!latexname.empty() && latexname != "!-- --")
2599 //os << "<!-- " << depth << " -->" << "</" << latexname << ">\n";
2600 os << string(depth, ' ') << "</" << latexname << ">\n";
2604 void Buffer::makeLinuxDocFile(string const & fname, bool nice, bool body_only)
2606 ofstream ofs(fname.c_str());
2609 Alert::alert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2613 niceFile = nice; // this will be used by included files.
2615 LyXTextClass const & tclass = textclasslist[params.textclass];
2617 LaTeXFeatures features(params, tclass.size());
2623 string top_element = textclasslist[params.textclass].latexname();
2626 ofs << "<!doctype linuxdoc system";
2628 string preamble = params.preamble;
2629 preamble += features.getIncludedFiles(fname);
2630 preamble += features.getLyXSGMLEntities();
2632 if (!preamble.empty()) {
2633 ofs << " [ " << preamble << " ]";
2637 if (params.options.empty())
2638 sgmlOpenTag(ofs, 0, top_element);
2640 string top = top_element;
2642 top += params.options;
2643 sgmlOpenTag(ofs, 0, top);
2647 ofs << "<!-- " << lyx_docversion
2648 << " created this file. For more info see http://www.lyx.org/"
2651 Paragraph::depth_type depth = 0; // paragraph depth
2652 Paragraph * par = paragraph;
2654 vector<string> environment_stack(5);
2657 LyXLayout const & style =
2658 textclasslist[params.textclass][par->layout()];
2660 // treat <toc> as a special case for compatibility with old code
2661 if (par->isInset(0)) {
2662 Inset * inset = par->getInset(0);
2663 Inset::Code lyx_code = inset->lyxCode();
2664 if (lyx_code == Inset::TOC_CODE) {
2665 string const temp = "toc";
2666 sgmlOpenTag(ofs, depth, temp);
2673 // environment tag closing
2674 for (; depth > par->params().depth(); --depth) {
2675 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2676 environment_stack[depth].erase();
2679 // write opening SGML tags
2680 switch (style.latextype) {
2681 case LATEX_PARAGRAPH:
2682 if (depth == par->params().depth()
2683 && !environment_stack[depth].empty()) {
2684 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2685 environment_stack[depth].erase();
2691 sgmlOpenTag(ofs, depth, style.latexname());
2697 _("Error : Wrong depth for"
2698 " LatexType Command.\n"));
2700 if (!environment_stack[depth].empty()) {
2701 sgmlCloseTag(ofs, depth,
2702 environment_stack[depth]);
2706 environment_stack[depth].erase();
2707 sgmlOpenTag(ofs, depth, style.latexname());
2710 case LATEX_ENVIRONMENT:
2711 case LATEX_ITEM_ENVIRONMENT:
2712 if (depth == par->params().depth()
2713 && environment_stack[depth] != style.latexname()) {
2714 sgmlCloseTag(ofs, depth,
2715 environment_stack[depth]);
2716 environment_stack[depth].erase();
2718 if (depth < par->params().depth()) {
2719 depth = par->params().depth();
2720 environment_stack[depth].erase();
2722 if (environment_stack[depth] != style.latexname()) {
2724 sgmlOpenTag(ofs, depth, "p");
2726 sgmlOpenTag(ofs, depth, style.latexname());
2728 if (environment_stack.size() == depth + 1)
2729 environment_stack.push_back("!-- --");
2730 environment_stack[depth] = style.latexname();
2733 if (style.latexparam() == "CDATA")
2736 if (style.latextype == LATEX_ENVIRONMENT) break;
2738 if (style.labeltype == LABEL_MANUAL)
2743 sgmlOpenTag(ofs, depth + 1, item_name);
2746 sgmlOpenTag(ofs, depth, style.latexname());
2750 simpleLinuxDocOnePar(ofs, par, depth);
2755 // write closing SGML tags
2756 switch (style.latextype) {
2759 case LATEX_ENVIRONMENT:
2760 case LATEX_ITEM_ENVIRONMENT:
2761 if (style.latexparam() == "CDATA")
2765 sgmlCloseTag(ofs, depth, style.latexname());
2771 for (int i=depth; i >= 0; --i)
2772 sgmlCloseTag(ofs, depth, environment_stack[i]);
2776 sgmlCloseTag(ofs, 0, top_element);
2780 // How to check for successful close
2784 // checks, if newcol chars should be put into this line
2785 // writes newline, if necessary.
2788 void sgmlLineBreak(ostream & os, string::size_type & colcount,
2789 string::size_type newcol)
2792 if (colcount > lyxrc.ascii_linelen) {
2794 colcount = newcol; // assume write after this call
2809 string tag_name(PAR_TAG const & pt) {
2811 case NONE: return "!-- --";
2812 case TT: return "tt";
2813 case SF: return "sf";
2814 case BF: return "bf";
2815 case IT: return "it";
2816 case SL: return "sl";
2817 case EM: return "em";
2824 void operator|=(PAR_TAG & p1, PAR_TAG const & p2)
2826 p1 = static_cast<PAR_TAG>(p1 | p2);
2831 void reset(PAR_TAG & p1, PAR_TAG const & p2)
2833 p1 = static_cast<PAR_TAG>(p1 & ~p2);
2839 // Handle internal paragraph parsing -- layout already processed.
2840 void Buffer::simpleLinuxDocOnePar(ostream & os,
2842 Paragraph::depth_type /*depth*/)
2844 LyXLayout const & style =
2845 textclasslist[params.textclass][par->layout()];
2846 string::size_type char_line_count = 5; // Heuristic choice ;-)
2848 // gets paragraph main font
2851 if (style.labeltype == LABEL_MANUAL) {
2852 font_old = style.labelfont;
2855 font_old = style.font;
2859 LyXFont::FONT_FAMILY family_type = LyXFont::ROMAN_FAMILY;
2860 LyXFont::FONT_SERIES series_type = LyXFont::MEDIUM_SERIES;
2861 LyXFont::FONT_SHAPE shape_type = LyXFont::UP_SHAPE;
2864 stack<PAR_TAG> tag_state;
2865 // parsing main loop
2866 for (pos_type i = 0; i < par->size(); ++i) {
2868 PAR_TAG tag_close = NONE;
2869 list < PAR_TAG > tag_open;
2871 LyXFont const font = par->getFont(params, i);
2873 if (font_old.family() != font.family()) {
2874 switch (family_type) {
2875 case LyXFont::SANS_FAMILY:
2878 case LyXFont::TYPEWRITER_FAMILY:
2885 family_type = font.family();
2887 switch (family_type) {
2888 case LyXFont::SANS_FAMILY:
2889 tag_open.push_back(SF);
2891 case LyXFont::TYPEWRITER_FAMILY:
2892 tag_open.push_back(TT);
2899 if (font_old.series() != font.series()) {
2900 switch (series_type) {
2901 case LyXFont::BOLD_SERIES:
2908 series_type = font.series();
2910 switch (series_type) {
2911 case LyXFont::BOLD_SERIES:
2912 tag_open.push_back(BF);
2920 if (font_old.shape() != font.shape()) {
2921 switch (shape_type) {
2922 case LyXFont::ITALIC_SHAPE:
2925 case LyXFont::SLANTED_SHAPE:
2932 shape_type = font.shape();
2934 switch (shape_type) {
2935 case LyXFont::ITALIC_SHAPE:
2936 tag_open.push_back(IT);
2938 case LyXFont::SLANTED_SHAPE:
2939 tag_open.push_back(SL);
2946 if (font_old.emph() != font.emph()) {
2947 if (font.emph() == LyXFont::ON) {
2948 tag_open.push_back(EM);
2957 list < PAR_TAG > temp;
2958 while (!tag_state.empty() && tag_close) {
2959 PAR_TAG k = tag_state.top();
2961 os << "</" << tag_name(k) << ">";
2968 for(list< PAR_TAG >::const_iterator j = temp.begin();
2969 j != temp.end(); ++j) {
2971 os << "<" << tag_name(*j) << ">";
2974 for(list< PAR_TAG >::const_iterator j = tag_open.begin();
2975 j != tag_open.end(); ++j) {
2977 os << "<" << tag_name(*j) << ">";
2980 char c = par->getChar(i);
2982 if (c == Paragraph::META_INSET) {
2983 Inset * inset = par->getInset(i);
2984 inset->linuxdoc(this, os);
2989 if (style.latexparam() == "CDATA") {
2990 // "TeX"-Mode on == > SGML-Mode on.
2996 if (par->sgmlConvertChar(c, sgml_string)
2997 && !style.free_spacing && !par->isFreeSpacing())
2999 // in freespacing mode, spaces are
3000 // non-breaking characters
3001 if (desc_on) {// if char is ' ' then...
3004 sgmlLineBreak(os, char_line_count, 6);
3008 sgmlLineBreak(os, char_line_count, 1);
3013 char_line_count += sgml_string.length();
3019 while (!tag_state.empty()) {
3020 os << "</" << tag_name(tag_state.top()) << ">";
3024 // resets description flag correctly
3026 // <tag> not closed...
3027 sgmlLineBreak(os, char_line_count, 6);
3033 // Print an error message.
3034 void Buffer::sgmlError(Paragraph * par, int pos,
3035 string const & message) const
3037 // insert an error marker in text
3038 InsetError * new_inset = new InsetError(message);
3039 par->insertInset(pos, new_inset, LyXFont(LyXFont::ALL_INHERIT,
3044 void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
3046 ofstream ofs(fname.c_str());
3048 Alert::alert(_("LYX_ERROR:"), _("Cannot write file"), fname);
3052 Paragraph * par = paragraph;
3054 niceFile = nice; // this will be used by Insetincludes.
3056 LyXTextClass const & tclass =
3057 textclasslist[params.textclass];
3059 LaTeXFeatures features(params, tclass.size());
3064 string top_element = textclasslist[params.textclass].latexname();
3067 ofs << "<!DOCTYPE " << top_element
3068 << " PUBLIC \"-//OASIS//DTD DocBook V4.1//EN\"";
3070 string preamble = params.preamble;
3071 preamble += features.getIncludedFiles(fname);
3072 preamble += features.getLyXSGMLEntities();
3074 if (!preamble.empty()) {
3075 ofs << "\n [ " << preamble << " ]";
3080 string top = top_element;
3082 top += params.language->code();
3085 if (!params.options.empty()) {
3087 top += params.options;
3089 sgmlOpenTag(ofs, 0, top);
3091 ofs << "<!-- DocBook file was created by " << lyx_docversion
3092 << "\n See http://www.lyx.org/ for more information -->\n";
3094 vector<string> environment_stack(10);
3095 vector<string> environment_inner(10);
3096 vector<string> command_stack(10);
3098 bool command_flag = false;
3099 Paragraph::depth_type command_depth = 0;
3100 Paragraph::depth_type command_base = 0;
3101 Paragraph::depth_type cmd_depth = 0;
3102 Paragraph::depth_type depth = 0; // paragraph depth
3105 string command_name;
3111 int desc_on = 0; // description mode
3113 LyXLayout const & style =
3114 textclasslist[params.textclass][par->layout()];
3116 // environment tag closing
3117 for (; depth > par->params().depth(); --depth) {
3118 if (environment_inner[depth] != "!-- --") {
3119 item_name = "listitem";
3120 sgmlCloseTag(ofs, command_depth + depth,
3122 if (environment_inner[depth] == "varlistentry")
3123 sgmlCloseTag(ofs, depth+command_depth,
3124 environment_inner[depth]);
3126 sgmlCloseTag(ofs, depth + command_depth,
3127 environment_stack[depth]);
3128 environment_stack[depth].erase();
3129 environment_inner[depth].erase();
3132 if (depth == par->params().depth()
3133 && environment_stack[depth] != style.latexname()
3134 && !environment_stack[depth].empty()) {
3135 if (environment_inner[depth] != "!-- --") {
3136 item_name= "listitem";
3137 sgmlCloseTag(ofs, command_depth+depth,
3139 if (environment_inner[depth] == "varlistentry")
3141 depth + command_depth,
3142 environment_inner[depth]);
3145 sgmlCloseTag(ofs, depth + command_depth,
3146 environment_stack[depth]);
3148 environment_stack[depth].erase();
3149 environment_inner[depth].erase();
3152 // Write opening SGML tags.
3153 switch (style.latextype) {
3154 case LATEX_PARAGRAPH:
3155 sgmlOpenTag(ofs, depth + command_depth,
3162 _("Error : Wrong depth for "
3163 "LatexType Command.\n"));
3165 command_name = style.latexname();
3167 sgmlparam = style.latexparam();
3168 c_params = split(sgmlparam, c_depth,'|');
3170 cmd_depth = lyx::atoi(c_depth);
3173 if (cmd_depth < command_base) {
3174 for (Paragraph::depth_type j = command_depth; j >= command_base; --j)
3175 sgmlCloseTag(ofs, j, command_stack[j]);
3176 command_depth = command_base = cmd_depth;
3177 } else if (cmd_depth <= command_depth) {
3178 for (int j = command_depth; j >= int(cmd_depth); --j)
3179 sgmlCloseTag(ofs, j, command_stack[j]);
3180 command_depth = cmd_depth;
3182 command_depth = cmd_depth;
3184 command_depth = command_base = cmd_depth;
3185 command_flag = true;
3187 if (command_stack.size() == command_depth + 1)
3188 command_stack.push_back(string());
3189 command_stack[command_depth] = command_name;
3191 // treat label as a special case for
3192 // more WYSIWYM handling.
3193 // This is a hack while paragraphs can't have
3194 // attributes, like id in this case.
3195 if (par->isInset(0)) {
3196 Inset * inset = par->getInset(0);
3197 Inset::Code lyx_code = inset->lyxCode();
3198 if (lyx_code == Inset::LABEL_CODE) {
3199 command_name += " id=\"";
3200 command_name += (static_cast<InsetCommand *>(inset))->getContents();
3201 command_name += "\"";
3206 sgmlOpenTag(ofs, depth + command_depth, command_name);
3207 if (c_params.empty())
3208 item_name = "title";
3210 item_name = c_params;
3211 sgmlOpenTag(ofs, depth + 1 + command_depth, item_name);
3214 case LATEX_ENVIRONMENT:
3215 case LATEX_ITEM_ENVIRONMENT:
3216 if (depth < par->params().depth()) {
3217 depth = par->params().depth();
3218 environment_stack[depth].erase();
3221 if (environment_stack[depth] != style.latexname()) {
3222 if (environment_stack.size() == depth + 1) {
3223 environment_stack.push_back("!-- --");
3224 environment_inner.push_back("!-- --");
3226 environment_stack[depth] = style.latexname();
3227 environment_inner[depth] = "!-- --";
3228 sgmlOpenTag(ofs, depth + command_depth,
3229 environment_stack[depth]);
3231 if (environment_inner[depth] != "!-- --") {
3232 item_name= "listitem";
3234 command_depth + depth,
3236 if (environment_inner[depth] == "varlistentry")
3238 depth + command_depth,
3239 environment_inner[depth]);
3243 if (style.latextype == LATEX_ENVIRONMENT) {
3244 if (!style.latexparam().empty()) {
3245 if (style.latexparam() == "CDATA")
3248 sgmlOpenTag(ofs, depth + command_depth,
3249 style.latexparam());
3254 desc_on = (style.labeltype == LABEL_MANUAL);
3257 environment_inner[depth]= "varlistentry";
3259 environment_inner[depth]= "listitem";
3261 sgmlOpenTag(ofs, depth + 1 + command_depth,
3262 environment_inner[depth]);
3266 sgmlOpenTag(ofs, depth + 1 + command_depth,
3270 sgmlOpenTag(ofs, depth + 1 + command_depth,
3275 sgmlOpenTag(ofs, depth + command_depth,
3280 simpleDocBookOnePar(ofs, par, desc_on, depth+1+command_depth);
3284 // write closing SGML tags
3285 switch (style.latextype) {
3287 if (c_params.empty())
3291 sgmlCloseTag(ofs, depth + command_depth, end_tag);
3293 case LATEX_ENVIRONMENT:
3294 if (!style.latexparam().empty()) {
3295 if (style.latexparam() == "CDATA")
3298 sgmlCloseTag(ofs, depth + command_depth,
3299 style.latexparam());
3302 case LATEX_ITEM_ENVIRONMENT:
3303 if (desc_on == 1) break;
3305 sgmlCloseTag(ofs, depth + 1 + command_depth, end_tag);
3307 case LATEX_PARAGRAPH:
3308 sgmlCloseTag(ofs, depth + command_depth, style.latexname());
3311 sgmlCloseTag(ofs, depth + command_depth, style.latexname());
3317 for (int d = depth; d >= 0; --d) {
3318 if (!environment_stack[depth].empty()) {
3319 if (environment_inner[depth] != "!-- --") {
3320 item_name = "listitem";
3321 sgmlCloseTag(ofs, command_depth + depth,
3323 if (environment_inner[depth] == "varlistentry")
3324 sgmlCloseTag(ofs, depth + command_depth,
3325 environment_inner[depth]);
3328 sgmlCloseTag(ofs, depth + command_depth,
3329 environment_stack[depth]);
3333 for (int j = command_depth; j >= 0 ; --j)
3334 if (!command_stack[j].empty())
3335 sgmlCloseTag(ofs, j, command_stack[j]);
3338 sgmlCloseTag(ofs, 0, top_element);
3341 // How to check for successful close
3345 void Buffer::simpleDocBookOnePar(ostream & os,
3346 Paragraph * par, int & desc_on,
3347 Paragraph::depth_type depth) const
3349 bool emph_flag = false;
3351 LyXLayout const & style =
3352 textclasslist[params.textclass][par->layout()];
3354 LyXFont font_old = style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
3356 int char_line_count = depth;
3357 //if (!style.free_spacing)
3358 // os << string(depth,' ');
3360 // parsing main loop
3361 for (pos_type i = 0; i < par->size(); ++i) {
3362 LyXFont font = par->getFont(params, i);
3364 // handle <emphasis> tag
3365 if (font_old.emph() != font.emph()) {
3366 if (font.emph() == LyXFont::ON) {
3370 os << "</emphasis>";
3376 if (par->isInset(i)) {
3377 Inset * inset = par->getInset(i);
3378 // don't print the inset in position 0 if desc_on == 3 (label)
3379 if ( i || desc_on != 3) {
3380 if(style.latexparam() == "CDATA")
3382 inset->docbook(this, os);
3383 if(style.latexparam() == "CDATA")
3387 char c = par->getChar(i);
3389 par->sgmlConvertChar(c, sgml_string);
3391 if (style.pass_thru) {
3393 } else if (style.free_spacing || par->isFreeSpacing() || c != ' ') {
3395 } else if (desc_on ==1) {
3397 os << "\n</term><listitem><para>";
3407 os << "</emphasis>";
3410 // resets description flag correctly
3412 // <term> not closed...
3415 if (style.free_spacing) os << '\n';
3419 // This should be enabled when the Chktex class is implemented. (Asger)
3420 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
3421 // Other flags: -wall -v0 -x
3422 int Buffer::runChktex()
3424 if (!users->text) return 0;
3426 users->owner()->prohibitInput();
3428 // get LaTeX-Filename
3429 string const name = getLatexName();
3430 string path = filePath();
3432 string const org_path = path;
3433 if (lyxrc.use_tempdir || !IsDirWriteable(path)) {
3437 Path p(path); // path to LaTeX file
3438 users->owner()->message(_("Running chktex..."));
3440 // Remove all error insets
3441 bool const removedErrorInsets = users->removeAutoInsets();
3443 // Generate the LaTeX file if neccessary
3444 makeLaTeXFile(name, org_path, false);
3447 Chktex chktex(lyxrc.chktex_command, name, filePath());
3448 int res = chktex.run(terr); // run chktex
3451 Alert::alert(_("chktex did not work!"),
3452 _("Could not run with file:"), name);
3453 } else if (res > 0) {
3454 // Insert all errors as errors boxes
3455 users->insertErrors(terr);
3458 // if we removed error insets before we ran chktex or if we inserted
3459 // error insets after we ran chktex, this must be run:
3460 if (removedErrorInsets || res) {
3464 users->owner()->allowInput();
3470 void Buffer::validate(LaTeXFeatures & features) const
3472 Paragraph * par = paragraph;
3473 LyXTextClass const & tclass = textclasslist[params.textclass];
3475 // AMS Style is at document level
3476 if (params.use_amsmath || tclass.provides(LyXTextClass::amsmath))
3477 features.require("amsmath");
3480 // We don't use "lyxerr.debug" because of speed. (Asger)
3481 if (lyxerr.debugging(Debug::LATEX))
3482 lyxerr << "Paragraph: " << par << endl;
3484 // Now just follow the list of paragraphs and run
3485 // validate on each of them.
3486 par->validate(features);
3488 // and then the next paragraph
3492 // the bullet shapes are buffer level not paragraph level
3493 // so they are tested here
3494 for (int i = 0; i < 4; ++i) {
3495 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
3496 int const font = params.user_defined_bullets[i].getFont();
3498 int const c = params
3499 .user_defined_bullets[i]
3506 features.require("latexsym");
3508 } else if (font == 1) {
3509 features.require("amssymb");
3510 } else if ((font >= 2 && font <= 5)) {
3511 features.require("pifont");
3516 if (lyxerr.debugging(Debug::LATEX)) {
3517 features.showStruct();
3522 // This function should be in Buffer because it's a buffer's property (ale)
3523 string const Buffer::getIncludeonlyList(char delim)
3526 for (inset_iterator it = inset_iterator_begin();
3527 it != inset_iterator_end(); ++it) {
3528 if ((*it)->lyxCode() == Inset::INCLUDE_CODE) {
3529 InsetInclude * insetinc =
3530 static_cast<InsetInclude *>(*it);
3531 if (insetinc->isIncludeOnly()) {
3534 lst += insetinc->getRelFileBaseName();
3538 lyxerr[Debug::INFO] << "Includeonly(" << lst << ')' << endl;
3543 vector<string> const Buffer::getLabelList()
3545 /// if this is a child document and the parent is already loaded
3546 /// Use the parent's list instead [ale990407]
3547 if (!params.parentname.empty()
3548 && bufferlist.exists(params.parentname)) {
3549 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3551 return tmp->getLabelList();
3554 vector<string> label_list;
3555 for (inset_iterator it = inset_iterator_begin();
3556 it != inset_iterator_end(); ++it) {
3557 vector<string> const l = (*it)->getLabelList();
3558 label_list.insert(label_list.end(), l.begin(), l.end());
3564 Buffer::Lists const Buffer::getLists() const
3567 Paragraph * par = paragraph;
3569 LyXTextClass const & textclass = textclasslist[params.textclass];
3570 bool found = textclass.hasLayout("caption");
3571 string const layout("caption");
3574 char const labeltype = textclass[par->layout()].labeltype;
3576 if (labeltype >= LABEL_COUNTER_CHAPTER
3577 && labeltype <= LABEL_COUNTER_CHAPTER + params.tocdepth) {
3578 // insert this into the table of contents
3579 SingleList & item = l["TOC"];
3582 textclass.maxcounter());
3583 item.push_back(TocItem(par, depth, par->asString(this, true)));
3585 // For each paragrph, traverse its insets and look for
3589 Paragraph::inset_iterator it =
3590 par->inset_iterator_begin();
3591 Paragraph::inset_iterator end =
3592 par->inset_iterator_end();
3594 for (; it != end; ++it) {
3595 if ((*it)->lyxCode() == Inset::FLOAT_CODE) {
3597 static_cast<InsetFloat*>(*it);
3599 string const type = il->type();
3601 // Now find the caption in the float...
3602 // We now tranverse the paragraphs of
3604 Paragraph * tmp = il->inset.paragraph();
3606 if (tmp->layout() == layout) {
3607 SingleList & item = l[type];
3609 tostr(item.size()+1) + ". " + tmp->asString(this, false);
3610 item.push_back(TocItem(tmp, 0 , str));
3617 lyxerr << "caption not found" << endl;
3626 // This is also a buffer property (ale)
3627 vector<pair<string, string> > const Buffer::getBibkeyList()
3629 /// if this is a child document and the parent is already loaded
3630 /// Use the parent's list instead [ale990412]
3631 if (!params.parentname.empty() && bufferlist.exists(params.parentname)) {
3632 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3634 return tmp->getBibkeyList();
3637 vector<pair<string, string> > keys;
3638 Paragraph * par = paragraph;
3641 keys.push_back(pair<string, string>(par->bibkey->getContents(),
3642 par->asString(this, false)));
3646 // Might be either using bibtex or a child has bibliography
3648 for (inset_iterator it = inset_iterator_begin();
3649 it != inset_iterator_end(); ++it) {
3650 // Search for Bibtex or Include inset
3651 if ((*it)->lyxCode() == Inset::BIBTEX_CODE) {
3652 vector<pair<string,string> > tmp =
3653 static_cast<InsetBibtex*>(*it)->getKeys(this);
3654 keys.insert(keys.end(), tmp.begin(), tmp.end());
3655 } else if ((*it)->lyxCode() == Inset::INCLUDE_CODE) {
3656 vector<pair<string,string> > const tmp =
3657 static_cast<InsetInclude*>(*it)->getKeys();
3658 keys.insert(keys.end(), tmp.begin(), tmp.end());
3667 bool Buffer::isDepClean(string const & name) const
3669 DEPCLEAN * item = dep_clean;
3670 while (item && item->master != name)
3672 if (!item) return true;
3677 void Buffer::markDepClean(string const & name)
3680 dep_clean = new DEPCLEAN;
3681 dep_clean->clean = true;
3682 dep_clean->master = name;
3683 dep_clean->next = 0;
3685 DEPCLEAN * item = dep_clean;
3686 while (item && item->master != name)
3691 item = new DEPCLEAN;
3693 item->master = name;
3700 bool Buffer::dispatch(string const & command)
3702 // Split command string into command and argument
3704 string line = frontStrip(command);
3705 string const arg = strip(frontStrip(split(line, cmd, ' ')));
3707 return dispatch(lyxaction.LookupFunc(cmd), arg);
3711 bool Buffer::dispatch(int action, string const & argument)
3713 bool dispatched = true;
3716 Exporter::Export(this, argument, false);
3726 void Buffer::resizeInsets(BufferView * bv)
3728 /// then remove all LyXText in text-insets
3729 Paragraph * par = paragraph;
3730 for (; par; par = par->next()) {
3731 par->resizeInsetsLyXText(bv);
3736 void Buffer::redraw()
3743 void Buffer::changeLanguage(Language const * from, Language const * to)
3746 ParIterator end = par_iterator_end();
3747 for (ParIterator it = par_iterator_begin(); it != end; ++it)
3748 (*it)->changeLanguage(params, from, to);
3752 bool Buffer::isMultiLingual()
3754 ParIterator end = par_iterator_end();
3755 for (ParIterator it = par_iterator_begin(); it != end; ++it)
3756 if ((*it)->isMultiLingual(params))
3763 Buffer::inset_iterator::inset_iterator(Paragraph * paragraph, pos_type pos)
3766 it = par->InsetIterator(pos);
3767 if (it == par->inset_iterator_end()) {
3774 void Buffer::inset_iterator::setParagraph()
3777 it = par->inset_iterator_begin();
3778 if (it != par->inset_iterator_end())
3783 // We maintain an invariant that whenever par = 0 then it = 0
3787 Inset * Buffer::getInsetFromID(int id_arg) const
3789 for (inset_iterator it = inset_const_iterator_begin();
3790 it != inset_const_iterator_end(); ++it)
3792 if ((*it)->id() == id_arg)
3794 Inset * in = (*it)->getInsetFromID(id_arg);
3802 Paragraph * Buffer::getParFromID(int id) const
3804 if (id < 0) return 0;
3805 Paragraph * par = paragraph;
3807 if (par->id() == id) {
3810 Paragraph * tmp = par->getParFromID(id);
3820 ParIterator Buffer::par_iterator_begin()
3822 return ParIterator(paragraph);
3826 ParIterator Buffer::par_iterator_end()
3828 return ParIterator();