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 ofstream ofs(fname.c_str());
2020 Alert::err_alert(_("Error: Cannot open file: "), fname);
2024 // validate the buffer.
2025 lyxerr[Debug::LATEX] << " Validating buffer..." << endl;
2026 LaTeXFeatures features(params);
2028 lyxerr[Debug::LATEX] << " Buffer validation done." << endl;
2031 // The starting paragraph of the coming rows is the
2032 // first paragraph of the document. (Asger)
2033 texrow.start(paragraph, 0);
2035 if (!only_body && nice) {
2036 ofs << "%% " << lyx_docversion << " created this file. "
2037 "For more info, see http://www.lyx.org/.\n"
2038 "%% Do not edit unless you really know what "
2043 lyxerr[Debug::INFO] << "lyx header finished" << endl;
2044 // There are a few differences between nice LaTeX and usual files:
2045 // usual is \batchmode and has a
2046 // special input@path to allow the including of figures
2047 // with either \input or \includegraphics (what figinsets do).
2048 // batchmode is not set if there is a tex_code_break_column.
2049 // In this case somebody is interested in the generated LaTeX,
2050 // so this is OK. input@path is set when the actual parameter
2051 // original_path is set. This is done for usual tex-file, but not
2052 // for nice-latex-file. (Matthias 250696)
2055 // code for usual, NOT nice-latex-file
2056 ofs << "\\batchmode\n"; // changed
2057 // from \nonstopmode
2060 if (!original_path.empty()) {
2061 ofs << "\\makeatletter\n"
2062 << "\\def\\input@path{{"
2063 << os::external_path(original_path) << "/}}\n"
2064 << "\\makeatother\n";
2070 ofs << "\\documentclass";
2072 LyXTextClass const & tclass = textclasslist[params.textclass];
2074 ostringstream options; // the document class options.
2076 if (tokenPos(tclass.opt_fontsize(),
2077 '|', params.fontsize) >= 0) {
2078 // only write if existing in list (and not default)
2079 options << params.fontsize << "pt,";
2083 if (!params.use_geometry &&
2084 (params.paperpackage == BufferParams::PACKAGE_NONE)) {
2085 switch (params.papersize) {
2086 case BufferParams::PAPER_A4PAPER:
2087 options << "a4paper,";
2089 case BufferParams::PAPER_USLETTER:
2090 options << "letterpaper,";
2092 case BufferParams::PAPER_A5PAPER:
2093 options << "a5paper,";
2095 case BufferParams::PAPER_B5PAPER:
2096 options << "b5paper,";
2098 case BufferParams::PAPER_EXECUTIVEPAPER:
2099 options << "executivepaper,";
2101 case BufferParams::PAPER_LEGALPAPER:
2102 options << "legalpaper,";
2108 if (params.sides != tclass.sides()) {
2109 switch (params.sides) {
2110 case LyXTextClass::OneSide:
2111 options << "oneside,";
2113 case LyXTextClass::TwoSides:
2114 options << "twoside,";
2120 if (params.columns != tclass.columns()) {
2121 if (params.columns == 2)
2122 options << "twocolumn,";
2124 options << "onecolumn,";
2127 if (!params.use_geometry
2128 && params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
2129 options << "landscape,";
2131 // language should be a parameter to \documentclass
2133 ostringstream language_options;
2134 if (params.language->babel() == "hebrew"
2135 && default_language->babel() != "hebrew")
2136 // This seems necessary
2137 features.useLanguage(default_language);
2139 if (lyxrc.language_use_babel ||
2140 params.language->lang() != lyxrc.default_language ||
2141 !features.hasLanguages()) {
2143 language_options << features.getLanguages();
2144 language_options << params.language->babel();
2145 if (lyxrc.language_global_options)
2146 options << language_options.str() << ',';
2149 // the user-defined options
2150 if (!params.options.empty()) {
2151 options << params.options << ',';
2154 string strOptions(options.str().c_str());
2155 if (!strOptions.empty()) {
2156 strOptions = strip(strOptions, ',');
2157 ofs << '[' << strOptions << ']';
2160 ofs << '{' << tclass.latexname() << "}\n";
2162 // end of \documentclass defs
2164 // font selection must be done before loading fontenc.sty
2165 // The ae package is not needed when using OT1 font encoding.
2166 if (params.fonts != "default" &&
2167 (params.fonts != "ae" || lyxrc.fontenc != "default")) {
2168 ofs << "\\usepackage{" << params.fonts << "}\n";
2170 if (params.fonts == "ae") {
2171 ofs << "\\usepackage{aecompl}\n";
2175 // this one is not per buffer
2176 if (lyxrc.fontenc != "default") {
2177 ofs << "\\usepackage[" << lyxrc.fontenc
2182 if (params.inputenc == "auto") {
2183 string const doc_encoding =
2184 params.language->encoding()->LatexName();
2186 // Create a list with all the input encodings used
2188 set<string> encodings = features.getEncodingSet(doc_encoding);
2190 ofs << "\\usepackage[";
2191 std::copy(encodings.begin(), encodings.end(),
2192 std::ostream_iterator<string>(ofs, ","));
2193 ofs << doc_encoding << "]{inputenc}\n";
2195 } else if (params.inputenc != "default") {
2196 ofs << "\\usepackage[" << params.inputenc
2201 // At the very beginning the text parameters.
2202 if (params.paperpackage != BufferParams::PACKAGE_NONE) {
2203 switch (params.paperpackage) {
2204 case BufferParams::PACKAGE_A4:
2205 ofs << "\\usepackage{a4}\n";
2208 case BufferParams::PACKAGE_A4WIDE:
2209 ofs << "\\usepackage{a4wide}\n";
2212 case BufferParams::PACKAGE_WIDEMARGINSA4:
2213 ofs << "\\usepackage[widemargins]{a4}\n";
2218 if (params.use_geometry) {
2219 ofs << "\\usepackage{geometry}\n";
2221 ofs << "\\geometry{verbose";
2222 if (params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
2223 ofs << ",landscape";
2224 switch (params.papersize2) {
2225 case BufferParams::VM_PAPER_CUSTOM:
2226 if (!params.paperwidth.empty())
2227 ofs << ",paperwidth="
2228 << params.paperwidth;
2229 if (!params.paperheight.empty())
2230 ofs << ",paperheight="
2231 << params.paperheight;
2233 case BufferParams::VM_PAPER_USLETTER:
2234 ofs << ",letterpaper";
2236 case BufferParams::VM_PAPER_USLEGAL:
2237 ofs << ",legalpaper";
2239 case BufferParams::VM_PAPER_USEXECUTIVE:
2240 ofs << ",executivepaper";
2242 case BufferParams::VM_PAPER_A3:
2245 case BufferParams::VM_PAPER_A4:
2248 case BufferParams::VM_PAPER_A5:
2251 case BufferParams::VM_PAPER_B3:
2254 case BufferParams::VM_PAPER_B4:
2257 case BufferParams::VM_PAPER_B5:
2261 // default papersize ie BufferParams::VM_PAPER_DEFAULT
2262 switch (lyxrc.default_papersize) {
2263 case BufferParams::PAPER_DEFAULT: // keep compiler happy
2264 case BufferParams::PAPER_USLETTER:
2265 ofs << ",letterpaper";
2267 case BufferParams::PAPER_LEGALPAPER:
2268 ofs << ",legalpaper";
2270 case BufferParams::PAPER_EXECUTIVEPAPER:
2271 ofs << ",executivepaper";
2273 case BufferParams::PAPER_A3PAPER:
2276 case BufferParams::PAPER_A4PAPER:
2279 case BufferParams::PAPER_A5PAPER:
2282 case BufferParams::PAPER_B5PAPER:
2287 if (!params.topmargin.empty())
2288 ofs << ",tmargin=" << params.topmargin;
2289 if (!params.bottommargin.empty())
2290 ofs << ",bmargin=" << params.bottommargin;
2291 if (!params.leftmargin.empty())
2292 ofs << ",lmargin=" << params.leftmargin;
2293 if (!params.rightmargin.empty())
2294 ofs << ",rmargin=" << params.rightmargin;
2295 if (!params.headheight.empty())
2296 ofs << ",headheight=" << params.headheight;
2297 if (!params.headsep.empty())
2298 ofs << ",headsep=" << params.headsep;
2299 if (!params.footskip.empty())
2300 ofs << ",footskip=" << params.footskip;
2305 if (tokenPos(tclass.opt_pagestyle(),
2306 '|', params.pagestyle) >= 0) {
2307 if (params.pagestyle == "fancy") {
2308 ofs << "\\usepackage{fancyhdr}\n";
2311 ofs << "\\pagestyle{" << params.pagestyle << "}\n";
2315 if (params.secnumdepth != tclass.secnumdepth()) {
2316 ofs << "\\setcounter{secnumdepth}{"
2317 << params.secnumdepth
2321 if (params.tocdepth != tclass.tocdepth()) {
2322 ofs << "\\setcounter{tocdepth}{"
2328 if (params.paragraph_separation) {
2329 switch (params.defskip.kind()) {
2330 case VSpace::SMALLSKIP:
2331 ofs << "\\setlength\\parskip{\\smallskipamount}\n";
2333 case VSpace::MEDSKIP:
2334 ofs << "\\setlength\\parskip{\\medskipamount}\n";
2336 case VSpace::BIGSKIP:
2337 ofs << "\\setlength\\parskip{\\bigskipamount}\n";
2339 case VSpace::LENGTH:
2340 ofs << "\\setlength\\parskip{"
2341 << params.defskip.length().asLatexString()
2344 default: // should never happen // Then delete it.
2345 ofs << "\\setlength\\parskip{\\medskipamount}\n";
2350 ofs << "\\setlength\\parindent{0pt}\n";
2354 // Now insert the LyX specific LaTeX commands...
2356 // The optional packages;
2357 string preamble(features.getPackages());
2359 // this might be useful...
2360 preamble += "\n\\makeatletter\n";
2362 // Some macros LyX will need
2363 string tmppreamble(features.getMacros());
2365 if (!tmppreamble.empty()) {
2366 preamble += "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2367 "LyX specific LaTeX commands.\n"
2368 + tmppreamble + '\n';
2371 // the text class specific preamble
2372 tmppreamble = features.getTClassPreamble();
2373 if (!tmppreamble.empty()) {
2374 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2375 "Textclass specific LaTeX commands.\n"
2376 + tmppreamble + '\n';
2379 /* the user-defined preamble */
2380 if (!params.preamble.empty()) {
2381 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2382 "User specified LaTeX commands.\n"
2383 + params.preamble + '\n';
2386 preamble += "\\makeatother\n";
2388 // Itemize bullet settings need to be last in case the user
2389 // defines their own bullets that use a package included
2390 // in the user-defined preamble -- ARRae
2391 // Actually it has to be done much later than that
2392 // since some packages like frenchb make modifications
2393 // at \begin{document} time -- JMarc
2395 for (int i = 0; i < 4; ++i) {
2396 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
2397 if (bullets_def.empty())
2398 bullets_def="\\AtBeginDocument{\n";
2399 bullets_def += " \\renewcommand{\\labelitemi";
2401 // `i' is one less than the item to modify
2408 bullets_def += "ii";
2414 bullets_def += "}{" +
2415 params.user_defined_bullets[i].getText()
2420 if (!bullets_def.empty())
2421 preamble += bullets_def + "}\n\n";
2424 int(lyx::count(preamble.begin(), preamble.end(), '\n'));
2425 for (int j = 0; j != nlines; ++j) {
2431 // We try to load babel late, in case it interferes
2432 // with other packages.
2434 string tmp = lyxrc.language_package;
2435 if (!lyxrc.language_global_options
2436 && tmp == "\\usepackage{babel}")
2437 tmp = string("\\usepackage[") +
2438 language_options.str().c_str() +
2445 ofs << "\\begin{document}\n";
2448 lyxerr[Debug::INFO] << "preamble finished, now the body." << endl;
2450 if (!lyxrc.language_auto_begin) {
2451 ofs << subst(lyxrc.language_command_begin, "$$lang",
2452 params.language->babel())
2457 latexParagraphs(ofs, paragraph, 0, texrow);
2459 // add this just in case after all the paragraphs
2463 if (!lyxrc.language_auto_end) {
2464 ofs << subst(lyxrc.language_command_end, "$$lang",
2465 params.language->babel())
2471 ofs << "\\end{document}\n";
2474 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
2476 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
2480 // Just to be sure. (Asger)
2483 // tex_code_break_column's value is used to decide
2484 // if we are in batchmode or not (within mathed_write()
2485 // in math_write.C) so we must set it to a non-zero
2486 // value when we leave otherwise we save incorrect .lyx files.
2487 tex_code_break_column = lyxrc.ascii_linelen;
2491 lyxerr << "File was not closed properly." << endl;
2494 lyxerr[Debug::INFO] << "Finished making latex file." << endl;
2495 lyxerr[Debug::INFO] << "Row count was " << texrow.rows()-1 << "." << endl;
2500 // LaTeX all paragraphs from par to endpar, if endpar == 0 then to the end
2502 void Buffer::latexParagraphs(ostream & ofs, Paragraph * par,
2503 Paragraph * endpar, TexRow & texrow) const
2505 bool was_title = false;
2506 bool already_title = false;
2509 while (par != endpar) {
2510 Inset * in = par->inInset();
2511 // well we have to check if we are in an inset with unlimited
2512 // lenght (all in one row) if that is true then we don't allow
2513 // any special options in the paragraph and also we don't allow
2514 // any environment other then "Standard" to be valid!
2515 if ((in == 0) || !in->forceDefaultParagraphs(in)) {
2516 LyXLayout const & layout =
2517 textclasslist[params.textclass][par->layout()];
2519 if (layout.intitle) {
2520 if (already_title) {
2521 lyxerr <<"Error in latexParagraphs: You"
2522 " should not mix title layouts"
2523 " with normal ones." << endl;
2526 } else if (was_title && !already_title) {
2527 ofs << "\\maketitle\n";
2529 already_title = true;
2533 if (layout.isEnvironment()) {
2534 par = par->TeXEnvironment(this, params, ofs, texrow);
2536 par = par->TeXOnePar(this, params, ofs, texrow, false);
2539 par = par->TeXOnePar(this, params, ofs, texrow, false);
2542 // It might be that we only have a title in this document
2543 if (was_title && !already_title) {
2544 ofs << "\\maketitle\n";
2550 bool Buffer::isLatex() const
2552 return textclasslist[params.textclass].outputType() == LATEX;
2556 bool Buffer::isLinuxDoc() const
2558 return textclasslist[params.textclass].outputType() == LINUXDOC;
2562 bool Buffer::isLiterate() const
2564 return textclasslist[params.textclass].outputType() == LITERATE;
2568 bool Buffer::isDocBook() const
2570 return textclasslist[params.textclass].outputType() == DOCBOOK;
2574 bool Buffer::isSGML() const
2576 LyXTextClass const & tclass = textclasslist[params.textclass];
2578 return tclass.outputType() == LINUXDOC ||
2579 tclass.outputType() == DOCBOOK;
2583 void Buffer::sgmlOpenTag(ostream & os, Paragraph::depth_type depth,
2584 string const & latexname) const
2586 if (!latexname.empty() && latexname != "!-- --")
2587 //os << "<!-- " << depth << " -->" << "<" << latexname << ">";
2588 os << string(depth, ' ') << "<" << latexname << ">\n";
2592 void Buffer::sgmlCloseTag(ostream & os, Paragraph::depth_type depth,
2593 string const & latexname) const
2595 if (!latexname.empty() && latexname != "!-- --")
2596 //os << "<!-- " << depth << " -->" << "</" << latexname << ">\n";
2597 os << string(depth, ' ') << "</" << latexname << ">\n";
2601 void Buffer::makeLinuxDocFile(string const & fname, bool nice, bool body_only)
2603 ofstream ofs(fname.c_str());
2606 Alert::alert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2610 niceFile = nice; // this will be used by included files.
2612 LaTeXFeatures features(params);
2618 LyXTextClass const & tclass = textclasslist[params.textclass];
2620 string top_element = tclass.latexname();
2623 ofs << "<!doctype linuxdoc system";
2625 string preamble = params.preamble;
2626 preamble += features.getIncludedFiles(fname);
2627 preamble += features.getLyXSGMLEntities();
2629 if (!preamble.empty()) {
2630 ofs << " [ " << preamble << " ]";
2634 if (params.options.empty())
2635 sgmlOpenTag(ofs, 0, top_element);
2637 string top = top_element;
2639 top += params.options;
2640 sgmlOpenTag(ofs, 0, top);
2644 ofs << "<!-- " << lyx_docversion
2645 << " created this file. For more info see http://www.lyx.org/"
2648 Paragraph::depth_type depth = 0; // paragraph depth
2649 Paragraph * par = paragraph;
2651 vector<string> environment_stack(5);
2654 LyXLayout const & style = tclass[par->layout()];
2656 // treat <toc> as a special case for compatibility with old code
2657 if (par->isInset(0)) {
2658 Inset * inset = par->getInset(0);
2659 Inset::Code lyx_code = inset->lyxCode();
2660 if (lyx_code == Inset::TOC_CODE) {
2661 string const temp = "toc";
2662 sgmlOpenTag(ofs, depth, temp);
2669 // environment tag closing
2670 for (; depth > par->params().depth(); --depth) {
2671 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2672 environment_stack[depth].erase();
2675 // write opening SGML tags
2676 switch (style.latextype) {
2677 case LATEX_PARAGRAPH:
2678 if (depth == par->params().depth()
2679 && !environment_stack[depth].empty()) {
2680 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2681 environment_stack[depth].erase();
2687 sgmlOpenTag(ofs, depth, style.latexname());
2693 _("Error : Wrong depth for"
2694 " LatexType Command.\n"));
2696 if (!environment_stack[depth].empty()) {
2697 sgmlCloseTag(ofs, depth,
2698 environment_stack[depth]);
2702 environment_stack[depth].erase();
2703 sgmlOpenTag(ofs, depth, style.latexname());
2706 case LATEX_ENVIRONMENT:
2707 case LATEX_ITEM_ENVIRONMENT:
2708 if (depth == par->params().depth()
2709 && environment_stack[depth] != style.latexname()) {
2710 sgmlCloseTag(ofs, depth,
2711 environment_stack[depth]);
2712 environment_stack[depth].erase();
2714 if (depth < par->params().depth()) {
2715 depth = par->params().depth();
2716 environment_stack[depth].erase();
2718 if (environment_stack[depth] != style.latexname()) {
2720 sgmlOpenTag(ofs, depth, "p");
2722 sgmlOpenTag(ofs, depth, style.latexname());
2724 if (environment_stack.size() == depth + 1)
2725 environment_stack.push_back("!-- --");
2726 environment_stack[depth] = style.latexname();
2729 if (style.latexparam() == "CDATA")
2732 if (style.latextype == LATEX_ENVIRONMENT) break;
2734 if (style.labeltype == LABEL_MANUAL)
2739 sgmlOpenTag(ofs, depth + 1, item_name);
2742 sgmlOpenTag(ofs, depth, style.latexname());
2746 simpleLinuxDocOnePar(ofs, par, depth);
2751 // write closing SGML tags
2752 switch (style.latextype) {
2755 case LATEX_ENVIRONMENT:
2756 case LATEX_ITEM_ENVIRONMENT:
2757 if (style.latexparam() == "CDATA")
2761 sgmlCloseTag(ofs, depth, style.latexname());
2767 for (int i=depth; i >= 0; --i)
2768 sgmlCloseTag(ofs, depth, environment_stack[i]);
2772 sgmlCloseTag(ofs, 0, top_element);
2776 // How to check for successful close
2780 // checks, if newcol chars should be put into this line
2781 // writes newline, if necessary.
2784 void sgmlLineBreak(ostream & os, string::size_type & colcount,
2785 string::size_type newcol)
2788 if (colcount > lyxrc.ascii_linelen) {
2790 colcount = newcol; // assume write after this call
2805 string tag_name(PAR_TAG const & pt) {
2807 case NONE: return "!-- --";
2808 case TT: return "tt";
2809 case SF: return "sf";
2810 case BF: return "bf";
2811 case IT: return "it";
2812 case SL: return "sl";
2813 case EM: return "em";
2820 void operator|=(PAR_TAG & p1, PAR_TAG const & p2)
2822 p1 = static_cast<PAR_TAG>(p1 | p2);
2827 void reset(PAR_TAG & p1, PAR_TAG const & p2)
2829 p1 = static_cast<PAR_TAG>(p1 & ~p2);
2835 // Handle internal paragraph parsing -- layout already processed.
2836 void Buffer::simpleLinuxDocOnePar(ostream & os,
2838 Paragraph::depth_type /*depth*/)
2840 LyXLayout const & style =
2841 textclasslist[params.textclass][par->layout()];
2842 string::size_type char_line_count = 5; // Heuristic choice ;-)
2844 // gets paragraph main font
2847 if (style.labeltype == LABEL_MANUAL) {
2848 font_old = style.labelfont;
2851 font_old = style.font;
2855 LyXFont::FONT_FAMILY family_type = LyXFont::ROMAN_FAMILY;
2856 LyXFont::FONT_SERIES series_type = LyXFont::MEDIUM_SERIES;
2857 LyXFont::FONT_SHAPE shape_type = LyXFont::UP_SHAPE;
2860 stack<PAR_TAG> tag_state;
2861 // parsing main loop
2862 for (pos_type i = 0; i < par->size(); ++i) {
2864 PAR_TAG tag_close = NONE;
2865 list < PAR_TAG > tag_open;
2867 LyXFont const font = par->getFont(params, i);
2869 if (font_old.family() != font.family()) {
2870 switch (family_type) {
2871 case LyXFont::SANS_FAMILY:
2874 case LyXFont::TYPEWRITER_FAMILY:
2881 family_type = font.family();
2883 switch (family_type) {
2884 case LyXFont::SANS_FAMILY:
2885 tag_open.push_back(SF);
2887 case LyXFont::TYPEWRITER_FAMILY:
2888 tag_open.push_back(TT);
2895 if (font_old.series() != font.series()) {
2896 switch (series_type) {
2897 case LyXFont::BOLD_SERIES:
2904 series_type = font.series();
2906 switch (series_type) {
2907 case LyXFont::BOLD_SERIES:
2908 tag_open.push_back(BF);
2916 if (font_old.shape() != font.shape()) {
2917 switch (shape_type) {
2918 case LyXFont::ITALIC_SHAPE:
2921 case LyXFont::SLANTED_SHAPE:
2928 shape_type = font.shape();
2930 switch (shape_type) {
2931 case LyXFont::ITALIC_SHAPE:
2932 tag_open.push_back(IT);
2934 case LyXFont::SLANTED_SHAPE:
2935 tag_open.push_back(SL);
2942 if (font_old.emph() != font.emph()) {
2943 if (font.emph() == LyXFont::ON) {
2944 tag_open.push_back(EM);
2953 list < PAR_TAG > temp;
2954 while (!tag_state.empty() && tag_close) {
2955 PAR_TAG k = tag_state.top();
2957 os << "</" << tag_name(k) << ">";
2964 for(list< PAR_TAG >::const_iterator j = temp.begin();
2965 j != temp.end(); ++j) {
2967 os << "<" << tag_name(*j) << ">";
2970 for(list< PAR_TAG >::const_iterator j = tag_open.begin();
2971 j != tag_open.end(); ++j) {
2973 os << "<" << tag_name(*j) << ">";
2976 char c = par->getChar(i);
2978 if (c == Paragraph::META_INSET) {
2979 Inset * inset = par->getInset(i);
2980 inset->linuxdoc(this, os);
2985 if (style.latexparam() == "CDATA") {
2986 // "TeX"-Mode on == > SGML-Mode on.
2992 if (par->sgmlConvertChar(c, sgml_string)
2993 && !style.free_spacing && !par->isFreeSpacing())
2995 // in freespacing mode, spaces are
2996 // non-breaking characters
2997 if (desc_on) {// if char is ' ' then...
3000 sgmlLineBreak(os, char_line_count, 6);
3004 sgmlLineBreak(os, char_line_count, 1);
3009 char_line_count += sgml_string.length();
3015 while (!tag_state.empty()) {
3016 os << "</" << tag_name(tag_state.top()) << ">";
3020 // resets description flag correctly
3022 // <tag> not closed...
3023 sgmlLineBreak(os, char_line_count, 6);
3029 // Print an error message.
3030 void Buffer::sgmlError(Paragraph * par, int pos,
3031 string const & message) const
3033 // insert an error marker in text
3034 InsetError * new_inset = new InsetError(message);
3035 par->insertInset(pos, new_inset, LyXFont(LyXFont::ALL_INHERIT,
3040 void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
3042 ofstream ofs(fname.c_str());
3044 Alert::alert(_("LYX_ERROR:"), _("Cannot write file"), fname);
3048 Paragraph * par = paragraph;
3050 niceFile = nice; // this will be used by Insetincludes.
3052 LaTeXFeatures features(params);
3057 LyXTextClass const & tclass = textclasslist[params.textclass];
3058 string top_element = tclass.latexname();
3061 ofs << "<!DOCTYPE " << top_element
3062 << " PUBLIC \"-//OASIS//DTD DocBook V4.1//EN\"";
3064 string preamble = params.preamble;
3065 preamble += features.getIncludedFiles(fname);
3066 preamble += features.getLyXSGMLEntities();
3068 if (!preamble.empty()) {
3069 ofs << "\n [ " << preamble << " ]";
3074 string top = top_element;
3076 top += params.language->code();
3079 if (!params.options.empty()) {
3081 top += params.options;
3083 sgmlOpenTag(ofs, 0, top);
3085 ofs << "<!-- DocBook file was created by " << lyx_docversion
3086 << "\n See http://www.lyx.org/ for more information -->\n";
3088 vector<string> environment_stack(10);
3089 vector<string> environment_inner(10);
3090 vector<string> command_stack(10);
3092 bool command_flag = false;
3093 Paragraph::depth_type command_depth = 0;
3094 Paragraph::depth_type command_base = 0;
3095 Paragraph::depth_type cmd_depth = 0;
3096 Paragraph::depth_type depth = 0; // paragraph depth
3099 string command_name;
3105 int desc_on = 0; // description mode
3107 LyXLayout const & style = tclass[par->layout()];
3109 // environment tag closing
3110 for (; depth > par->params().depth(); --depth) {
3111 if (environment_inner[depth] != "!-- --") {
3112 item_name = "listitem";
3113 sgmlCloseTag(ofs, command_depth + depth,
3115 if (environment_inner[depth] == "varlistentry")
3116 sgmlCloseTag(ofs, depth+command_depth,
3117 environment_inner[depth]);
3119 sgmlCloseTag(ofs, depth + command_depth,
3120 environment_stack[depth]);
3121 environment_stack[depth].erase();
3122 environment_inner[depth].erase();
3125 if (depth == par->params().depth()
3126 && environment_stack[depth] != style.latexname()
3127 && !environment_stack[depth].empty()) {
3128 if (environment_inner[depth] != "!-- --") {
3129 item_name= "listitem";
3130 sgmlCloseTag(ofs, command_depth+depth,
3132 if (environment_inner[depth] == "varlistentry")
3134 depth + command_depth,
3135 environment_inner[depth]);
3138 sgmlCloseTag(ofs, depth + command_depth,
3139 environment_stack[depth]);
3141 environment_stack[depth].erase();
3142 environment_inner[depth].erase();
3145 // Write opening SGML tags.
3146 switch (style.latextype) {
3147 case LATEX_PARAGRAPH:
3148 sgmlOpenTag(ofs, depth + command_depth,
3155 _("Error : Wrong depth for "
3156 "LatexType Command.\n"));
3158 command_name = style.latexname();
3160 sgmlparam = style.latexparam();
3161 c_params = split(sgmlparam, c_depth,'|');
3163 cmd_depth = lyx::atoi(c_depth);
3166 if (cmd_depth < command_base) {
3167 for (Paragraph::depth_type j = command_depth; j >= command_base; --j)
3168 sgmlCloseTag(ofs, j, command_stack[j]);
3169 command_depth = command_base = cmd_depth;
3170 } else if (cmd_depth <= command_depth) {
3171 for (int j = command_depth; j >= int(cmd_depth); --j)
3172 sgmlCloseTag(ofs, j, command_stack[j]);
3173 command_depth = cmd_depth;
3175 command_depth = cmd_depth;
3177 command_depth = command_base = cmd_depth;
3178 command_flag = true;
3180 if (command_stack.size() == command_depth + 1)
3181 command_stack.push_back(string());
3182 command_stack[command_depth] = command_name;
3184 // treat label as a special case for
3185 // more WYSIWYM handling.
3186 // This is a hack while paragraphs can't have
3187 // attributes, like id in this case.
3188 if (par->isInset(0)) {
3189 Inset * inset = par->getInset(0);
3190 Inset::Code lyx_code = inset->lyxCode();
3191 if (lyx_code == Inset::LABEL_CODE) {
3192 command_name += " id=\"";
3193 command_name += (static_cast<InsetCommand *>(inset))->getContents();
3194 command_name += "\"";
3199 sgmlOpenTag(ofs, depth + command_depth, command_name);
3200 if (c_params.empty())
3201 item_name = "title";
3203 item_name = c_params;
3204 sgmlOpenTag(ofs, depth + 1 + command_depth, item_name);
3207 case LATEX_ENVIRONMENT:
3208 case LATEX_ITEM_ENVIRONMENT:
3209 if (depth < par->params().depth()) {
3210 depth = par->params().depth();
3211 environment_stack[depth].erase();
3214 if (environment_stack[depth] != style.latexname()) {
3215 if (environment_stack.size() == depth + 1) {
3216 environment_stack.push_back("!-- --");
3217 environment_inner.push_back("!-- --");
3219 environment_stack[depth] = style.latexname();
3220 environment_inner[depth] = "!-- --";
3221 sgmlOpenTag(ofs, depth + command_depth,
3222 environment_stack[depth]);
3224 if (environment_inner[depth] != "!-- --") {
3225 item_name= "listitem";
3227 command_depth + depth,
3229 if (environment_inner[depth] == "varlistentry")
3231 depth + command_depth,
3232 environment_inner[depth]);
3236 if (style.latextype == LATEX_ENVIRONMENT) {
3237 if (!style.latexparam().empty()) {
3238 if (style.latexparam() == "CDATA")
3241 sgmlOpenTag(ofs, depth + command_depth,
3242 style.latexparam());
3247 desc_on = (style.labeltype == LABEL_MANUAL);
3250 environment_inner[depth]= "varlistentry";
3252 environment_inner[depth]= "listitem";
3254 sgmlOpenTag(ofs, depth + 1 + command_depth,
3255 environment_inner[depth]);
3259 sgmlOpenTag(ofs, depth + 1 + command_depth,
3263 sgmlOpenTag(ofs, depth + 1 + command_depth,
3268 sgmlOpenTag(ofs, depth + command_depth,
3273 simpleDocBookOnePar(ofs, par, desc_on, depth+1+command_depth);
3277 // write closing SGML tags
3278 switch (style.latextype) {
3280 if (c_params.empty())
3284 sgmlCloseTag(ofs, depth + command_depth, end_tag);
3286 case LATEX_ENVIRONMENT:
3287 if (!style.latexparam().empty()) {
3288 if (style.latexparam() == "CDATA")
3291 sgmlCloseTag(ofs, depth + command_depth,
3292 style.latexparam());
3295 case LATEX_ITEM_ENVIRONMENT:
3296 if (desc_on == 1) break;
3298 sgmlCloseTag(ofs, depth + 1 + command_depth, end_tag);
3300 case LATEX_PARAGRAPH:
3301 sgmlCloseTag(ofs, depth + command_depth, style.latexname());
3304 sgmlCloseTag(ofs, depth + command_depth, style.latexname());
3310 for (int d = depth; d >= 0; --d) {
3311 if (!environment_stack[depth].empty()) {
3312 if (environment_inner[depth] != "!-- --") {
3313 item_name = "listitem";
3314 sgmlCloseTag(ofs, command_depth + depth,
3316 if (environment_inner[depth] == "varlistentry")
3317 sgmlCloseTag(ofs, depth + command_depth,
3318 environment_inner[depth]);
3321 sgmlCloseTag(ofs, depth + command_depth,
3322 environment_stack[depth]);
3326 for (int j = command_depth; j >= 0 ; --j)
3327 if (!command_stack[j].empty())
3328 sgmlCloseTag(ofs, j, command_stack[j]);
3331 sgmlCloseTag(ofs, 0, top_element);
3334 // How to check for successful close
3338 void Buffer::simpleDocBookOnePar(ostream & os,
3339 Paragraph * par, int & desc_on,
3340 Paragraph::depth_type depth) const
3342 bool emph_flag = false;
3344 LyXLayout const & style =
3345 textclasslist[params.textclass][par->layout()];
3347 LyXFont font_old = style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
3349 int char_line_count = depth;
3350 //if (!style.free_spacing)
3351 // os << string(depth,' ');
3353 // parsing main loop
3354 for (pos_type i = 0; i < par->size(); ++i) {
3355 LyXFont font = par->getFont(params, i);
3357 // handle <emphasis> tag
3358 if (font_old.emph() != font.emph()) {
3359 if (font.emph() == LyXFont::ON) {
3363 os << "</emphasis>";
3369 if (par->isInset(i)) {
3370 Inset * inset = par->getInset(i);
3371 // don't print the inset in position 0 if desc_on == 3 (label)
3372 if ( i || desc_on != 3) {
3373 if(style.latexparam() == "CDATA")
3375 inset->docbook(this, os);
3376 if(style.latexparam() == "CDATA")
3380 char c = par->getChar(i);
3382 par->sgmlConvertChar(c, sgml_string);
3384 if (style.pass_thru) {
3386 } else if (style.free_spacing || par->isFreeSpacing() || c != ' ') {
3388 } else if (desc_on ==1) {
3390 os << "\n</term><listitem><para>";
3400 os << "</emphasis>";
3403 // resets description flag correctly
3405 // <term> not closed...
3408 if (style.free_spacing) os << '\n';
3412 // This should be enabled when the Chktex class is implemented. (Asger)
3413 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
3414 // Other flags: -wall -v0 -x
3415 int Buffer::runChktex()
3417 if (!users->text) return 0;
3419 users->owner()->prohibitInput();
3421 // get LaTeX-Filename
3422 string const name = getLatexName();
3423 string path = filePath();
3425 string const org_path = path;
3426 if (lyxrc.use_tempdir || !IsDirWriteable(path)) {
3430 Path p(path); // path to LaTeX file
3431 users->owner()->message(_("Running chktex..."));
3433 // Remove all error insets
3434 bool const removedErrorInsets = users->removeAutoInsets();
3436 // Generate the LaTeX file if neccessary
3437 makeLaTeXFile(name, org_path, false);
3440 Chktex chktex(lyxrc.chktex_command, name, filePath());
3441 int res = chktex.run(terr); // run chktex
3444 Alert::alert(_("chktex did not work!"),
3445 _("Could not run with file:"), name);
3446 } else if (res > 0) {
3447 // Insert all errors as errors boxes
3448 users->insertErrors(terr);
3451 // if we removed error insets before we ran chktex or if we inserted
3452 // error insets after we ran chktex, this must be run:
3453 if (removedErrorInsets || res) {
3457 users->owner()->allowInput();
3463 void Buffer::validate(LaTeXFeatures & features) const
3465 Paragraph * par = paragraph;
3466 LyXTextClass const & tclass = textclasslist[params.textclass];
3468 // AMS Style is at document level
3469 if (params.use_amsmath || tclass.provides(LyXTextClass::amsmath))
3470 features.require("amsmath");
3473 // We don't use "lyxerr.debug" because of speed. (Asger)
3474 if (lyxerr.debugging(Debug::LATEX))
3475 lyxerr << "Paragraph: " << par << endl;
3477 // Now just follow the list of paragraphs and run
3478 // validate on each of them.
3479 par->validate(features);
3481 // and then the next paragraph
3485 // the bullet shapes are buffer level not paragraph level
3486 // so they are tested here
3487 for (int i = 0; i < 4; ++i) {
3488 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
3489 int const font = params.user_defined_bullets[i].getFont();
3491 int const c = params
3492 .user_defined_bullets[i]
3499 features.require("latexsym");
3501 } else if (font == 1) {
3502 features.require("amssymb");
3503 } else if ((font >= 2 && font <= 5)) {
3504 features.require("pifont");
3509 if (lyxerr.debugging(Debug::LATEX)) {
3510 features.showStruct();
3515 // This function should be in Buffer because it's a buffer's property (ale)
3516 string const Buffer::getIncludeonlyList(char delim)
3519 for (inset_iterator it = inset_iterator_begin();
3520 it != inset_iterator_end(); ++it) {
3521 if ((*it)->lyxCode() == Inset::INCLUDE_CODE) {
3522 InsetInclude * insetinc =
3523 static_cast<InsetInclude *>(*it);
3524 if (insetinc->isIncludeOnly()) {
3527 lst += insetinc->getRelFileBaseName();
3531 lyxerr[Debug::INFO] << "Includeonly(" << lst << ')' << endl;
3536 vector<string> const Buffer::getLabelList()
3538 /// if this is a child document and the parent is already loaded
3539 /// Use the parent's list instead [ale990407]
3540 if (!params.parentname.empty()
3541 && bufferlist.exists(params.parentname)) {
3542 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3544 return tmp->getLabelList();
3547 vector<string> label_list;
3548 for (inset_iterator it = inset_iterator_begin();
3549 it != inset_iterator_end(); ++it) {
3550 vector<string> const l = (*it)->getLabelList();
3551 label_list.insert(label_list.end(), l.begin(), l.end());
3557 Buffer::Lists const Buffer::getLists() const
3560 Paragraph * par = paragraph;
3562 LyXTextClass const & textclass = textclasslist[params.textclass];
3563 bool found = textclass.hasLayout("caption");
3564 string const layout("caption");
3567 char const labeltype = textclass[par->layout()].labeltype;
3569 if (labeltype >= LABEL_COUNTER_CHAPTER
3570 && labeltype <= LABEL_COUNTER_CHAPTER + params.tocdepth) {
3571 // insert this into the table of contents
3572 SingleList & item = l["TOC"];
3575 textclass.maxcounter());
3576 item.push_back(TocItem(par, depth, par->asString(this, true)));
3578 // For each paragrph, traverse its insets and look for
3582 Paragraph::inset_iterator it =
3583 par->inset_iterator_begin();
3584 Paragraph::inset_iterator end =
3585 par->inset_iterator_end();
3587 for (; it != end; ++it) {
3588 if ((*it)->lyxCode() == Inset::FLOAT_CODE) {
3590 static_cast<InsetFloat*>(*it);
3592 string const type = il->type();
3594 // Now find the caption in the float...
3595 // We now tranverse the paragraphs of
3597 Paragraph * tmp = il->inset.paragraph();
3599 if (tmp->layout() == layout) {
3600 SingleList & item = l[type];
3602 tostr(item.size()+1) + ". " + tmp->asString(this, false);
3603 item.push_back(TocItem(tmp, 0 , str));
3610 lyxerr << "caption not found" << endl;
3619 // This is also a buffer property (ale)
3620 vector<pair<string, string> > const Buffer::getBibkeyList()
3622 /// if this is a child document and the parent is already loaded
3623 /// Use the parent's list instead [ale990412]
3624 if (!params.parentname.empty() && bufferlist.exists(params.parentname)) {
3625 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3627 return tmp->getBibkeyList();
3630 vector<pair<string, string> > keys;
3631 Paragraph * par = paragraph;
3634 keys.push_back(pair<string, string>(par->bibkey->getContents(),
3635 par->asString(this, false)));
3639 // Might be either using bibtex or a child has bibliography
3641 for (inset_iterator it = inset_iterator_begin();
3642 it != inset_iterator_end(); ++it) {
3643 // Search for Bibtex or Include inset
3644 if ((*it)->lyxCode() == Inset::BIBTEX_CODE) {
3645 vector<pair<string,string> > tmp =
3646 static_cast<InsetBibtex*>(*it)->getKeys(this);
3647 keys.insert(keys.end(), tmp.begin(), tmp.end());
3648 } else if ((*it)->lyxCode() == Inset::INCLUDE_CODE) {
3649 vector<pair<string,string> > const tmp =
3650 static_cast<InsetInclude*>(*it)->getKeys();
3651 keys.insert(keys.end(), tmp.begin(), tmp.end());
3660 bool Buffer::isDepClean(string const & name) const
3662 DEPCLEAN * item = dep_clean;
3663 while (item && item->master != name)
3665 if (!item) return true;
3670 void Buffer::markDepClean(string const & name)
3673 dep_clean = new DEPCLEAN;
3674 dep_clean->clean = true;
3675 dep_clean->master = name;
3676 dep_clean->next = 0;
3678 DEPCLEAN * item = dep_clean;
3679 while (item && item->master != name)
3684 item = new DEPCLEAN;
3686 item->master = name;
3693 bool Buffer::dispatch(string const & command)
3695 // Split command string into command and argument
3697 string line = frontStrip(command);
3698 string const arg = strip(frontStrip(split(line, cmd, ' ')));
3700 return dispatch(lyxaction.LookupFunc(cmd), arg);
3704 bool Buffer::dispatch(int action, string const & argument)
3706 bool dispatched = true;
3709 Exporter::Export(this, argument, false);
3719 void Buffer::resizeInsets(BufferView * bv)
3721 /// then remove all LyXText in text-insets
3722 Paragraph * par = paragraph;
3723 for (; par; par = par->next()) {
3724 par->resizeInsetsLyXText(bv);
3729 void Buffer::redraw()
3736 void Buffer::changeLanguage(Language const * from, Language const * to)
3739 ParIterator end = par_iterator_end();
3740 for (ParIterator it = par_iterator_begin(); it != end; ++it)
3741 (*it)->changeLanguage(params, from, to);
3745 bool Buffer::isMultiLingual()
3747 ParIterator end = par_iterator_end();
3748 for (ParIterator it = par_iterator_begin(); it != end; ++it)
3749 if ((*it)->isMultiLingual(params))
3756 Buffer::inset_iterator::inset_iterator(Paragraph * paragraph, pos_type pos)
3759 it = par->InsetIterator(pos);
3760 if (it == par->inset_iterator_end()) {
3767 void Buffer::inset_iterator::setParagraph()
3770 it = par->inset_iterator_begin();
3771 if (it != par->inset_iterator_end())
3776 // We maintain an invariant that whenever par = 0 then it = 0
3780 Inset * Buffer::getInsetFromID(int id_arg) const
3782 for (inset_iterator it = inset_const_iterator_begin();
3783 it != inset_const_iterator_end(); ++it)
3785 if ((*it)->id() == id_arg)
3787 Inset * in = (*it)->getInsetFromID(id_arg);
3795 Paragraph * Buffer::getParFromID(int id) const
3797 if (id < 0) return 0;
3798 Paragraph * par = paragraph;
3800 if (par->id() == id) {
3803 Paragraph * tmp = par->getParFromID(id);
3813 ParIterator Buffer::par_iterator_begin()
3815 return ParIterator(paragraph);
3819 ParIterator Buffer::par_iterator_end()
3821 return ParIterator();