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 "lyx_gui_misc.h"
25 #include "LyXAction.h"
28 #include "tex-strings.h"
30 #include "bufferview_funcs.h"
37 #include "LaTeXFeatures.h"
44 #include "converter.h"
45 #include "BufferView.h"
46 #include "ParagraphParameters.h"
47 #include "iterators.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/figinset.h"
69 #include "insets/insettext.h"
70 #include "insets/insetert.h"
71 #include "insets/insetgraphics.h"
72 #include "insets/insetfoot.h"
73 #include "insets/insetmarginal.h"
74 #include "insets/insetminipage.h"
75 #include "insets/insetfloat.h"
76 #include "insets/insettabular.h"
78 #include "insets/insettheorem.h"
79 #include "insets/insetlist.h"
81 #include "insets/insetcaption.h"
82 #include "insets/insetfloatlist.h"
84 #include "frontends/Dialogs.h"
85 #include "frontends/Alert.h"
87 #include "support/textutils.h"
88 #include "support/filetools.h"
89 #include "support/path.h"
90 #include "support/os.h"
91 #include "support/syscall.h"
92 #include "support/lyxlib.h"
93 #include "support/FileInfo.h"
94 #include "support/lyxmanip.h"
106 #include <sys/types.h>
123 using std::make_pair;
132 using lyx::layout_type;
133 using lyx::textclass_type;
135 // all these externs should eventually be removed.
136 extern BufferList bufferlist;
138 extern LyXAction lyxaction;
142 const int LYX_FORMAT = 220;
146 extern int tex_code_break_column;
149 Buffer::Buffer(string const & file, bool ronly)
151 lyxerr[Debug::INFO] << "Buffer::Buffer()" << endl;
153 filepath = OnlyPath(file);
162 if (read_only || (lyxrc.use_tempdir)) {
163 tmppath = CreateBufferTmpDir();
164 } else tmppath.erase();
170 lyxerr[Debug::INFO] << "Buffer::~Buffer()" << endl;
171 // here the buffer should take care that it is
172 // saved properly, before it goes into the void.
174 // make sure that views using this buffer
179 if (!tmppath.empty()) {
180 DestroyBufferTmpDir(tmppath);
183 Paragraph * par = paragraph;
186 tmppar = par->next();
194 string const Buffer::getLatexName(bool no_path) const
196 string const name = ChangeExtension(MakeLatexName(filename), ".tex");
198 return OnlyFilename(name);
204 pair<Buffer::LogType, string> const Buffer::getLogName(void) const
206 string const filename = getLatexName(false);
208 if (filename.empty())
209 return make_pair(Buffer::latexlog, string());
211 string path = OnlyPath(filename);
213 if (lyxrc.use_tempdir || !IsDirWriteable(path))
216 string const fname = AddName(path,
217 OnlyFilename(ChangeExtension(filename,
220 AddName(path, OnlyFilename(
221 ChangeExtension(filename,
222 formats.extension("literate") + ".out")));
224 // If no Latex log or Build log is newer, show Build log
226 FileInfo const f_fi(fname);
227 FileInfo const b_fi(bname);
230 (!f_fi.exist() || f_fi.getModificationTime() < b_fi.getModificationTime())) {
231 lyxerr[Debug::FILES] << "Log name calculated as : " << bname << endl;
232 return make_pair(Buffer::buildlog, bname);
234 lyxerr[Debug::FILES] << "Log name calculated as : " << fname << endl;
235 return make_pair(Buffer::latexlog, fname);
239 void Buffer::setReadonly(bool flag)
241 if (read_only != flag) {
244 users->owner()->getDialogs()->updateBufferDependent(false);
249 /// Update window titles of all users
250 // Should work on a list
251 void Buffer::updateTitles() const
254 users->owner()->updateWindowTitle();
258 /// Reset autosave timer of all users
259 // Should work on a list
260 void Buffer::resetAutosaveTimers() const
263 users->owner()->resetAutosaveTimer();
267 void Buffer::setFileName(string const & newfile)
269 filename = MakeAbsPath(newfile);
270 filepath = OnlyPath(filename);
271 setReadonly(IsFileWriteable(filename) == 0);
276 // We'll remove this later. (Lgb)
279 string last_inset_read;
281 #ifndef NO_COMPABILITY
284 ErtComp() : active(false), in_tabular(false) {
291 std::stack<ErtComp> ert_stack;
295 #warning And _why_ is this here? (Lgb)
302 // candidate for move to BufferView
303 // (at least some parts in the beginning of the func)
306 // changed to be public and have one parameter
307 // if par = 0 normal behavior
308 // else insert behavior
309 // Returns false if "\the_end" is not read for formats >= 2.13. (Asger)
310 bool Buffer::readLyXformat2(LyXLex & lex, Paragraph * par)
314 #ifndef NO_COMPABILITY
315 ert_comp.contents.erase();
316 ert_comp.active = false;
317 ert_comp.in_tabular = false;
320 Paragraph::depth_type depth = 0;
321 bool the_end_read = false;
323 Paragraph * first_par = 0;
324 LyXFont font(LyXFont::ALL_INHERIT, params.language);
325 if (file_format < 216 && params.language->lang() == "hebrew")
326 font.setLanguage(default_language);
331 // We are inserting into an existing document
332 users->text->breakParagraph(users);
333 first_par = users->text->firstParagraph();
336 // We don't want to adopt the parameters from the
337 // document we insert, so we skip until the text begins:
340 string const pretoken = lex.getString();
341 if (pretoken == "\\layout") {
342 lex.pushToken(pretoken);
350 string const token = lex.getString();
352 if (token.empty()) continue;
354 lyxerr[Debug::PARSER] << "Handling token: `"
355 << token << "'" << endl;
358 parseSingleLyXformat2Token(lex, par, first_par,
366 paragraph = first_par;
368 if (unknown_layouts > 0) {
369 string s = _("Couldn't set the layout for ");
370 if (unknown_layouts == 1) {
371 s += _("one paragraph");
373 s += tostr(unknown_layouts);
374 s += _(" paragraphs");
376 Alert::alert(_("Textclass Loading Error!"), s,
377 _("When reading " + fileName()));
380 if (unknown_tokens > 0) {
381 string s = _("Encountered ");
382 if (unknown_tokens == 1) {
383 s += _("one unknown token");
385 s += tostr(unknown_tokens);
386 s += _(" unknown tokens");
388 Alert::alert(_("Textclass Loading Error!"), s,
389 _("When reading " + fileName()));
396 #ifndef NO_COMPABILITY
397 void Buffer::insertErtContents(Paragraph * par, int & pos,
398 LyXFont const & f, bool set_inactive)
400 if (!ert_comp.contents.empty()) {
401 lyxerr[Debug::INSETS] << "ERT contents:\n'"
402 << ert_comp.contents << "'" << endl;
403 Inset * inset = new InsetERT(ert_comp.contents, true);
405 font.setLanguage(f.language());
406 par->insertInset(pos++, inset, font);
407 ert_comp.contents.erase();
410 ert_comp.active = false;
417 Buffer::parseSingleLyXformat2Token(LyXLex & lex, Paragraph *& par,
418 Paragraph *& first_par,
419 string const & token, int & pos,
420 Paragraph::depth_type & depth,
424 bool the_end_read = false;
425 #ifndef NO_COMPABILITY
426 #ifndef NO_PEXTRA_REALLY
427 // This is super temporary but is needed to get the compability
428 // mode for minipages work correctly together with new tabulars.
429 static int call_depth;
431 bool checkminipage = false;
432 static Paragraph * minipar;
433 static Paragraph * parBeforeMinipage;
436 if (token[0] != '\\') {
437 #ifndef NO_COMPABILITY
438 if (ert_comp.active) {
439 ert_comp.contents += token;
442 for (string::const_iterator cit = token.begin();
443 cit != token.end(); ++cit) {
444 par->insertChar(pos, (*cit), font);
447 #ifndef NO_COMPABILITY
450 } else if (token == "\\i") {
451 Inset * inset = new InsetLatexAccent;
452 inset->read(this, lex);
453 par->insertInset(pos, inset, font);
455 } else if (token == "\\layout") {
456 #ifndef NO_COMPABILITY
457 ert_comp.in_tabular = false;
459 insertErtContents(par, pos, font);
462 string const layoutname = lex.getString();
463 pair<bool, layout_type> pp
464 = textclasslist.NumberOfLayout(params.textclass, layoutname);
466 #ifndef NO_COMPABILITY
467 if (compare_no_case(layoutname, "latex") == 0) {
468 ert_comp.active = true;
472 // The is the compability reading of layout caption.
473 // It can be removed in LyX version 1.3.0. (Lgb)
474 if (compare_no_case(layoutname, "caption") == 0) {
475 // We expect that the par we are now working on is
476 // really inside a InsetText inside a InsetFloat.
477 // We also know that captions can only be
478 // one paragraph. (Lgb)
480 // We should now read until the next "\layout"
482 // This is probably not good enough, what if the
483 // caption is the last par in the document (Lgb)
484 istream & ist = lex.getStream();
490 if (prefixIs(line, "\\layout")) {
494 if (prefixIs(line, "\\begin_inset"))
496 if (prefixIs(line, "\\end_inset")) {
507 // Now we should have the whole layout in ss
508 // we should now be able to give this to the
510 ss << "\\end_inset\n";
512 // This seems like a bug in stringstream.
513 // We really should be able to use ss
515 istringstream is(ss.str());
517 tmplex.setStream(is);
518 Inset * inset = new InsetCaption;
519 inset->Read(this, tmplex);
520 par->InsertInset(pos, inset, font);
527 par = new Paragraph(par);
531 par->layout = pp.second;
532 #ifndef NO_COMPABILITY
533 } else if (ert_comp.active) {
538 // use default layout "Standard" (0)
541 string const s = _("Layout had to be changed from\n")
542 + layoutname + _(" to ")
543 + textclasslist.NameOfLayout(params.textclass, par->layout);
544 InsetError * new_inset = new InsetError(s);
545 par->insertInset(0, new_inset,
546 LyXFont(LyXFont::ALL_INHERIT,
549 // Test whether the layout is obsolete.
550 LyXLayout const & layout =
551 textclasslist.Style(params.textclass,
553 if (!layout.obsoleted_by().empty())
554 par->layout = textclasslist
555 .NumberOfLayout(params.textclass,
556 layout.obsoleted_by())
558 par->params().depth(depth);
559 font = LyXFont(LyXFont::ALL_INHERIT, params.language);
560 if (file_format < 216
561 && params.language->lang() == "hebrew")
562 font.setLanguage(default_language);
567 #ifndef NO_COMPABILITY
568 } else if (token == "\\begin_float") {
569 insertErtContents(par, pos, font);
570 //insertErtContents(par, pos, font, false);
571 //ert_stack.push(ert_comp);
572 //ert_comp = ErtComp();
574 // This is the compability reader. It can be removed in
575 // LyX version 1.3.0. (Lgb)
577 string const tmptok = lex.getString();
578 //lyxerr << "old float: " << tmptok << endl;
581 stringstream old_float;
583 if (tmptok == "footnote") {
584 inset = new InsetFoot;
585 old_float << "collapsed true\n";
586 } else if (tmptok == "margin") {
587 inset = new InsetMarginal;
588 old_float << "collapsed true\n";
589 } else if (tmptok == "fig") {
590 inset = new InsetFloat("figure");
591 old_float << "placement htbp\n"
593 << "collapsed false\n";
594 } else if (tmptok == "tab") {
595 inset = new InsetFloat("table");
596 old_float << "placement htbp\n"
598 << "collapsed false\n";
599 } else if (tmptok == "alg") {
600 inset = new InsetFloat("algorithm");
601 old_float << "placement htbp\n"
603 << "collapsed false\n";
604 } else if (tmptok == "wide-fig") {
605 inset = new InsetFloat("figure");
606 //InsetFloat * tmp = new InsetFloat("figure");
609 old_float << "placement htbp\n"
611 << "collapsed false\n";
612 } else if (tmptok == "wide-tab") {
613 inset = new InsetFloat("table");
614 //InsetFloat * tmp = new InsetFloat("table");
617 old_float << "placement htbp\n"
619 << "collapsed false\n";
623 #ifndef NO_PEXTRA_REALLY
626 return false; // no end read yet
629 // Here we need to check for \end_deeper and handle that
630 // before we do the footnote parsing.
631 // This _is_ a hack! (Lgb)
634 string const tmp = lex.getString();
635 if (tmp == "\\end_deeper") {
636 //lyxerr << "\\end_deeper caught!" << endl;
638 lex.printError("\\end_deeper: "
639 "depth is already null");
644 old_float << tmp << ' ';
649 old_float << lex.getLongString("\\end_float")
650 << "\n\\end_inset\n";
651 //lyxerr << "Float Body:\n" << old_float.str() << endl;
652 // That this does not work seems like a bug
653 // in stringstream. (Lgb)
654 istringstream istr(old_float.str());
656 nylex.setStream(istr);
657 inset->read(this, nylex);
658 par->insertInset(pos, inset, font);
660 insertErtContents(par, pos, font);
662 } else if (token == "\\begin_deeper") {
664 } else if (token == "\\end_deeper") {
666 lex.printError("\\end_deeper: "
667 "depth is already null");
671 } else if (token == "\\begin_preamble") {
672 params.readPreamble(lex);
673 } else if (token == "\\textclass") {
675 pair<bool, textclass_type> pp =
676 textclasslist.NumberOfClass(lex.getString());
678 params.textclass = pp.second;
680 Alert::alert(string(_("Textclass error")),
681 string(_("The document uses an unknown textclass \"")) +
682 lex.getString() + string("\"."),
683 string(_("LyX will not be able to produce output correctly.")));
684 params.textclass = 0;
686 if (!textclasslist.Load(params.textclass)) {
687 // if the textclass wasn't loaded properly
688 // we need to either substitute another
689 // or stop loading the file.
690 // I can substitute but I don't see how I can
691 // stop loading... ideas?? ARRae980418
692 Alert::alert(_("Textclass Loading Error!"),
693 string(_("Can't load textclass ")) +
694 textclasslist.NameOfClass(params.textclass),
695 _("-- substituting default"));
696 params.textclass = 0;
698 } else if (token == "\\options") {
700 params.options = lex.getString();
701 } else if (token == "\\language") {
702 params.readLanguage(lex);
703 } else if (token == "\\fontencoding") {
705 } else if (token == "\\inputencoding") {
707 params.inputenc = lex.getString();
708 } else if (token == "\\graphics") {
709 params.readGraphicsDriver(lex);
710 } else if (token == "\\fontscheme") {
712 params.fonts = lex.getString();
713 } else if (token == "\\noindent") {
714 par->params().noindent(true);
715 } else if (token == "\\fill_top") {
716 par->params().spaceTop(VSpace(VSpace::VFILL));
717 } else if (token == "\\fill_bottom") {
718 par->params().spaceBottom(VSpace(VSpace::VFILL));
719 } else if (token == "\\line_top") {
720 par->params().lineTop(true);
721 } else if (token == "\\line_bottom") {
722 par->params().lineBottom(true);
723 } else if (token == "\\pagebreak_top") {
724 par->params().pagebreakTop(true);
725 } else if (token == "\\pagebreak_bottom") {
726 par->params().pagebreakBottom(true);
727 } else if (token == "\\start_of_appendix") {
728 par->params().startOfAppendix(true);
729 } else if (token == "\\paragraph_separation") {
730 int tmpret = lex.findToken(string_paragraph_separation);
731 if (tmpret == -1) ++tmpret;
732 if (tmpret != LYX_LAYOUT_DEFAULT)
733 params.paragraph_separation =
734 static_cast<BufferParams::PARSEP>(tmpret);
735 } else if (token == "\\defskip") {
737 params.defskip = VSpace(lex.getString());
738 } else if (token == "\\epsfig") { // obsolete
739 // Indeed it is obsolete, but we HAVE to be backwards
740 // compatible until 0.14, because otherwise all figures
741 // in existing documents are irretrivably lost. (Asger)
742 params.readGraphicsDriver(lex);
743 } else if (token == "\\quotes_language") {
744 int tmpret = lex.findToken(string_quotes_language);
745 if (tmpret == -1) ++tmpret;
746 if (tmpret != LYX_LAYOUT_DEFAULT) {
747 InsetQuotes::quote_language tmpl =
748 InsetQuotes::EnglishQ;
751 tmpl = InsetQuotes::EnglishQ;
754 tmpl = InsetQuotes::SwedishQ;
757 tmpl = InsetQuotes::GermanQ;
760 tmpl = InsetQuotes::PolishQ;
763 tmpl = InsetQuotes::FrenchQ;
766 tmpl = InsetQuotes::DanishQ;
769 params.quotes_language = tmpl;
771 } else if (token == "\\quotes_times") {
773 switch (lex.getInteger()) {
775 params.quotes_times = InsetQuotes::SingleQ;
778 params.quotes_times = InsetQuotes::DoubleQ;
781 } else if (token == "\\papersize") {
782 int tmpret = lex.findToken(string_papersize);
786 params.papersize2 = tmpret;
787 } else if (token == "\\paperpackage") {
788 int tmpret = lex.findToken(string_paperpackages);
791 params.paperpackage = BufferParams::PACKAGE_NONE;
793 params.paperpackage = tmpret;
794 } else if (token == "\\use_geometry") {
796 params.use_geometry = lex.getInteger();
797 } else if (token == "\\use_amsmath") {
799 params.use_amsmath = lex.getInteger();
800 } else if (token == "\\use_natbib") {
802 params.use_natbib = lex.getInteger();
803 } else if (token == "\\use_numerical_citations") {
805 params.use_numerical_citations = lex.getInteger();
806 } else if (token == "\\paperorientation") {
807 int tmpret = lex.findToken(string_orientation);
808 if (tmpret == -1) ++tmpret;
809 if (tmpret != LYX_LAYOUT_DEFAULT)
810 params.orientation = static_cast<BufferParams::PAPER_ORIENTATION>(tmpret);
811 } else if (token == "\\paperwidth") {
813 params.paperwidth = lex.getString();
814 } else if (token == "\\paperheight") {
816 params.paperheight = lex.getString();
817 } else if (token == "\\leftmargin") {
819 params.leftmargin = lex.getString();
820 } else if (token == "\\topmargin") {
822 params.topmargin = lex.getString();
823 } else if (token == "\\rightmargin") {
825 params.rightmargin = lex.getString();
826 } else if (token == "\\bottommargin") {
828 params.bottommargin = lex.getString();
829 } else if (token == "\\headheight") {
831 params.headheight = lex.getString();
832 } else if (token == "\\headsep") {
834 params.headsep = lex.getString();
835 } else if (token == "\\footskip") {
837 params.footskip = lex.getString();
838 } else if (token == "\\paperfontsize") {
840 params.fontsize = strip(lex.getString());
841 } else if (token == "\\papercolumns") {
843 params.columns = lex.getInteger();
844 } else if (token == "\\papersides") {
846 switch (lex.getInteger()) {
848 case 1: params.sides = LyXTextClass::OneSide; break;
849 case 2: params.sides = LyXTextClass::TwoSides; break;
851 } else if (token == "\\paperpagestyle") {
853 params.pagestyle = strip(lex.getString());
854 } else if (token == "\\bullet") {
856 int const index = lex.getInteger();
858 int temp_int = lex.getInteger();
859 params.user_defined_bullets[index].setFont(temp_int);
860 params.temp_bullets[index].setFont(temp_int);
862 temp_int = lex.getInteger();
863 params.user_defined_bullets[index].setCharacter(temp_int);
864 params.temp_bullets[index].setCharacter(temp_int);
866 temp_int = lex.getInteger();
867 params.user_defined_bullets[index].setSize(temp_int);
868 params.temp_bullets[index].setSize(temp_int);
870 string const temp_str = lex.getString();
871 if (temp_str != "\\end_bullet") {
872 // this element isn't really necessary for
873 // parsing but is easier for humans
874 // to understand bullets. Put it back and
875 // set a debug message?
876 lex.printError("\\end_bullet expected, got" + temp_str);
877 //how can I put it back?
879 } else if (token == "\\bulletLaTeX") {
881 int const index = lex.getInteger();
883 string temp_str = lex.getString();
885 while (temp_str != "\\end_bullet") {
886 // this loop structure is needed when user
887 // enters an empty string since the first
888 // thing returned will be the \\end_bullet
890 // if the LaTeX entry has spaces. Each element
891 // therefore needs to be read in turn
894 temp_str = lex.getString();
896 params.user_defined_bullets[index].setText(sum_str);
897 params.temp_bullets[index].setText(sum_str);
898 } else if (token == "\\secnumdepth") {
900 params.secnumdepth = lex.getInteger();
901 } else if (token == "\\tocdepth") {
903 params.tocdepth = lex.getInteger();
904 } else if (token == "\\spacing") {
906 string const tmp = strip(lex.getString());
907 Spacing::Space tmp_space = Spacing::Default;
909 if (tmp == "single") {
910 tmp_space = Spacing::Single;
911 } else if (tmp == "onehalf") {
912 tmp_space = Spacing::Onehalf;
913 } else if (tmp == "double") {
914 tmp_space = Spacing::Double;
915 } else if (tmp == "other") {
917 tmp_space = Spacing::Other;
918 tmp_val = lex.getFloat();
920 lex.printError("Unknown spacing token: '$$Token'");
922 // Small hack so that files written with klyx will be
925 par->params().spacing(Spacing(tmp_space, tmp_val));
927 params.spacing.set(tmp_space, tmp_val);
929 } else if (token == "\\paragraph_spacing") {
931 string const tmp = strip(lex.getString());
932 if (tmp == "single") {
933 par->params().spacing(Spacing(Spacing::Single));
934 } else if (tmp == "onehalf") {
935 par->params().spacing(Spacing(Spacing::Onehalf));
936 } else if (tmp == "double") {
937 par->params().spacing(Spacing(Spacing::Double));
938 } else if (tmp == "other") {
940 par->params().spacing(Spacing(Spacing::Other,
943 lex.printError("Unknown spacing token: '$$Token'");
945 } else if (token == "\\float_placement") {
947 params.float_placement = lex.getString();
948 } else if (token == "\\family") {
950 font.setLyXFamily(lex.getString());
951 } else if (token == "\\series") {
953 font.setLyXSeries(lex.getString());
954 } else if (token == "\\shape") {
956 font.setLyXShape(lex.getString());
957 } else if (token == "\\size") {
959 font.setLyXSize(lex.getString());
960 #ifndef NO_COMPABILITY
961 } else if (token == "\\latex") {
963 string const tok = lex.getString();
964 if (tok == "no_latex") {
966 insertErtContents(par, pos, font);
967 } else if (tok == "latex") {
968 ert_comp.active = true;
969 } else if (tok == "default") {
971 insertErtContents(par, pos, font);
973 lex.printError("Unknown LaTeX font flag "
977 } else if (token == "\\lang") {
979 string const tok = lex.getString();
980 Language const * lang = languages.getLanguage(tok);
982 font.setLanguage(lang);
984 font.setLanguage(params.language);
985 lex.printError("Unknown language `$$Token'");
987 } else if (token == "\\numeric") {
989 font.setNumber(font.setLyXMisc(lex.getString()));
990 } else if (token == "\\emph") {
992 font.setEmph(font.setLyXMisc(lex.getString()));
993 } else if (token == "\\bar") {
995 string const tok = lex.getString();
996 // This is dirty, but gone with LyX3. (Asger)
998 font.setUnderbar(LyXFont::ON);
999 else if (tok == "no")
1000 font.setUnderbar(LyXFont::OFF);
1001 else if (tok == "default")
1002 font.setUnderbar(LyXFont::INHERIT);
1004 lex.printError("Unknown bar font flag "
1006 } else if (token == "\\noun") {
1008 font.setNoun(font.setLyXMisc(lex.getString()));
1009 } else if (token == "\\color") {
1011 font.setLyXColor(lex.getString());
1012 } else if (token == "\\align") {
1013 int tmpret = lex.findToken(string_align);
1014 if (tmpret == -1) ++tmpret;
1015 if (tmpret != LYX_LAYOUT_DEFAULT) { // tmpret != 99 ???
1016 int const tmpret2 = int(pow(2.0, tmpret));
1017 //lyxerr << "Tmpret2 = " << tmpret2 << endl;
1018 par->params().align(LyXAlignment(tmpret2));
1020 } else if (token == "\\added_space_top") {
1022 par->params().spaceTop(VSpace(lex.getString()));
1023 } else if (token == "\\added_space_bottom") {
1025 par->params().spaceBottom(VSpace(lex.getString()));
1026 #ifndef NO_COMPABILITY
1027 #ifndef NO_PEXTRA_REALLY
1028 } else if (token == "\\pextra_type") {
1030 par->params().pextraType(lex.getInteger());
1031 } else if (token == "\\pextra_width") {
1033 par->params().pextraWidth(lex.getString());
1034 } else if (token == "\\pextra_widthp") {
1036 par->params().pextraWidthp(lex.getString());
1037 } else if (token == "\\pextra_alignment") {
1039 par->params().pextraAlignment(lex.getInteger());
1040 } else if (token == "\\pextra_hfill") {
1042 par->params().pextraHfill(lex.getInteger());
1043 } else if (token == "\\pextra_start_minipage") {
1045 par->params().pextraStartMinipage(lex.getInteger());
1048 } else if (token == "\\labelwidthstring") {
1050 par->params().labelWidthString(lex.getString());
1051 // do not delete this token, it is still needed!
1052 } else if (token == "\\end_inset") {
1053 lyxerr << "Solitary \\end_inset. Missing \\begin_inset?.\n"
1054 << "Last inset read was: " << last_inset_read
1056 // Simply ignore this. The insets do not have
1058 // But insets should read it, it is a part of
1059 // the inset isn't it? Lgb.
1060 } else if (token == "\\begin_inset") {
1061 #ifndef NO_COMPABILITY
1062 insertErtContents(par, pos, font, false);
1063 ert_stack.push(ert_comp);
1064 ert_comp = ErtComp();
1066 readInset(lex, par, pos, font);
1067 #ifndef NO_COMPABILITY
1068 ert_comp = ert_stack.top();
1070 insertErtContents(par, pos, font);
1072 } else if (token == "\\SpecialChar") {
1073 LyXLayout const & layout =
1074 textclasslist.Style(params.textclass,
1077 // Insets don't make sense in a free-spacing context! ---Kayvan
1078 if (layout.free_spacing || par->isFreeSpacing()) {
1081 string next_token = lex.getString();
1082 if (next_token == "\\-") {
1083 par->insertChar(pos, '-', font);
1084 } else if (next_token == "\\protected_separator"
1085 || next_token == "~") {
1086 par->insertChar(pos, ' ', font);
1088 lex.printError("Token `$$Token' "
1090 "paragraph layout!");
1095 Inset * inset = new InsetSpecialChar;
1096 inset->read(this, lex);
1097 par->insertInset(pos, inset, font);
1100 } else if (token == "\\newline") {
1101 #ifndef NO_COMPABILITY
1102 if (!ert_comp.in_tabular && ert_comp.active) {
1103 ert_comp.contents += char(Paragraph::META_NEWLINE);
1105 // Since we cannot know it this is only a regular
1106 // newline or a tabular cell delimter we have to
1107 // handle the ERT here.
1108 insertErtContents(par, pos, font, false);
1110 par->insertChar(pos, Paragraph::META_NEWLINE, font);
1114 par->insertChar(pos, Paragraph::META_NEWLINE, font);
1117 } else if (token == "\\LyXTable") {
1118 #ifndef NO_COMPABILITY
1119 ert_comp.in_tabular = true;
1121 Inset * inset = new InsetTabular(*this);
1122 inset->read(this, lex);
1123 par->insertInset(pos, inset, font);
1125 } else if (token == "\\hfill") {
1126 par->insertChar(pos, Paragraph::META_HFILL, font);
1128 } else if (token == "\\protected_separator") { // obsolete
1129 // This is a backward compability thingie. (Lgb)
1130 // Remove it later some time...introduced with fileformat
1132 LyXLayout const & layout =
1133 textclasslist.Style(params.textclass,
1136 if (layout.free_spacing || par->isFreeSpacing()) {
1137 par->insertChar(pos, ' ', font);
1139 Inset * inset = new InsetSpecialChar(InsetSpecialChar::PROTECTED_SEPARATOR);
1140 par->insertInset(pos, inset, font);
1143 } else if (token == "\\bibitem") { // ale970302
1145 InsetCommandParams p("bibitem", "dummy");
1146 par->bibkey = new InsetBibKey(p);
1148 par->bibkey->read(this, lex);
1149 } else if (token == "\\backslash") {
1150 #ifndef NO_COMPABILITY
1151 if (ert_comp.active) {
1152 ert_comp.contents += "\\";
1155 par->insertChar(pos, '\\', font);
1157 #ifndef NO_COMPABILITY
1160 } else if (token == "\\the_end") {
1161 #ifndef NO_COMPABILITY
1162 // If we still have some ert active here we have to insert
1163 // it so we don't loose it. (Lgb)
1164 insertErtContents(par, pos, font);
1166 the_end_read = true;
1167 #ifndef NO_COMPABILITY
1168 #ifndef NO_PEXTRA_REALLY
1169 minipar = parBeforeMinipage = 0;
1173 #ifndef NO_COMPABILITY
1174 if (ert_comp.active) {
1175 ert_comp.contents += token;
1178 // This should be insurance for the future: (Asger)
1181 string const s = _("Unknown token: ") + token
1182 + " " + lex.text() + "\n";
1184 InsetError * new_inset = new InsetError(s);
1185 par->insertInset(pos, new_inset, LyXFont(LyXFont::ALL_INHERIT,
1188 #ifndef NO_COMPABILITY
1193 #ifndef NO_COMPABILITY
1194 #ifndef NO_PEXTRA_REALLY
1195 // I wonder if we could use this blanket fix for all the
1196 // checkminipage cases...
1197 // don't forget about ert paragraphs and compatibility read for'em
1198 if (par && (par->size() || !ert_comp.contents.empty())) {
1199 // It is possible that this will check to often,
1200 // but that should not be an correctness issue.
1201 // Only a speed issue.
1202 checkminipage = true;
1205 // now check if we have a minipage paragraph as at this
1206 // point we already read all the necessary data!
1207 // this cannot be done in layout because there we did
1208 // not read yet the paragraph PEXTRA-params (Jug)
1210 // BEGIN pextra_minipage compability
1211 // This should be removed in 1.3.x (Lgb)
1212 // I don't think we should remove this so fast (Jug)
1214 // This compability code is not perfect. In a couple
1215 // of rand cases it fails. When the minipage par is
1216 // the first par in the document, and when there are
1217 // none or only one regular paragraphs after the
1218 // minipage. Currently I am not investing any effort
1219 // in fixing those cases.
1221 //lyxerr << "Call depth: " << call_depth << endl;
1222 if (checkminipage && (call_depth == 1)) {
1223 checkminipage = false;
1224 if (minipar && (minipar != par) &&
1225 (par->params().pextraType()==Paragraph::PEXTRA_MINIPAGE))
1227 lyxerr << "minipages in a row" << endl;
1228 if (par->params().pextraStartMinipage()) {
1229 lyxerr << "start new minipage" << endl;
1230 // minipages in a row
1231 par->previous()->next(0);
1234 Paragraph * tmp = minipar;
1236 tmp->params().pextraType(0);
1237 tmp->params().pextraWidth(string());
1238 tmp->params().pextraWidthp(string());
1239 tmp->params().pextraAlignment(0);
1240 tmp->params().pextraHfill(false);
1241 tmp->params().pextraStartMinipage(false);
1244 // create a new paragraph to insert the
1245 // minipages in the following case
1246 if (par->params().pextraStartMinipage() &&
1247 !par->params().pextraHfill())
1249 Paragraph * p = new Paragraph;
1251 p->previous(parBeforeMinipage);
1252 parBeforeMinipage->next(p);
1254 p->params().depth(parBeforeMinipage->params().depth());
1255 parBeforeMinipage = p;
1257 InsetMinipage * mini = new InsetMinipage;
1258 mini->pos(static_cast<InsetMinipage::Position>(par->params().pextraAlignment()));
1259 mini->width(par->params().pextraWidth());
1260 if (!par->params().pextraWidthp().empty()) {
1261 lyxerr << "WP:" << mini->width() << endl;
1262 mini->width(tostr(par->params().pextraWidthp())+"%");
1264 Paragraph * op = mini->firstParagraph();
1265 mini->inset.paragraph(par);
1267 // and free the old ones!
1270 Paragraph * pp = op->next();
1274 // Insert the minipage last in the
1275 // previous paragraph.
1276 if (par->params().pextraHfill()) {
1277 parBeforeMinipage->insertChar
1278 (parBeforeMinipage->size(), Paragraph::META_HFILL);
1280 parBeforeMinipage->insertInset
1281 (parBeforeMinipage->size(), mini);
1285 lyxerr << "new minipage par" << endl;
1286 //nothing to do just continue reading
1289 } else if (minipar && (minipar != par)) {
1290 lyxerr << "last minipage par read" << endl;
1291 // The last paragraph read was not part of a
1292 // minipage but the par linked list is...
1293 // So we need to remove the last par from the
1295 if (par->previous())
1296 par->previous()->next(0);
1297 par->previous(parBeforeMinipage);
1298 parBeforeMinipage->next(par);
1299 Paragraph * tmp = minipar;
1301 tmp->params().pextraType(0);
1302 tmp->params().pextraWidth(string());
1303 tmp->params().pextraWidthp(string());
1304 tmp->params().pextraAlignment(0);
1305 tmp->params().pextraHfill(false);
1306 tmp->params().pextraStartMinipage(false);
1309 depth = parBeforeMinipage->params().depth();
1310 // and set this depth on the par as it has not been set already
1311 par->params().depth(depth);
1312 minipar = parBeforeMinipage = 0;
1313 } else if (!minipar &&
1314 (par->params().pextraType() == Paragraph::PEXTRA_MINIPAGE))
1316 // par is the first paragraph in a minipage
1317 lyxerr << "begin minipage" << endl;
1318 // To minimize problems for
1319 // the users we will insert
1320 // the first minipage in
1321 // a sequence of minipages
1322 // in its own paragraph.
1323 Paragraph * p = new Paragraph;
1325 p->previous(par->previous());
1327 p->params().depth(depth);
1328 par->params().depth(0);
1330 if (par->previous())
1331 par->previous()->next(p);
1333 parBeforeMinipage = p;
1335 if (!first_par || (first_par == par))
1338 InsetMinipage * mini = new InsetMinipage;
1339 mini->pos(static_cast<InsetMinipage::Position>(minipar->params().pextraAlignment()));
1340 mini->width(minipar->params().pextraWidth());
1341 if (!par->params().pextraWidthp().empty()) {
1342 lyxerr << "WP:" << mini->width() << endl;
1343 mini->width(tostr(par->params().pextraWidthp())+"%");
1345 mini->inset.paragraph(minipar);
1347 // Insert the minipage last in the
1348 // previous paragraph.
1349 if (minipar->params().pextraHfill()) {
1350 parBeforeMinipage->insertChar
1351 (parBeforeMinipage->size(),Paragraph::META_HFILL);
1353 parBeforeMinipage->insertInset
1354 (parBeforeMinipage->size(), mini);
1357 // End of pextra_minipage compability
1361 return the_end_read;
1364 // needed to insert the selection
1365 void Buffer::insertStringAsLines(Paragraph *& par, pos_type & pos,
1366 LyXFont const & fn,string const & str) const
1368 LyXLayout const & layout = textclasslist.Style(params.textclass,
1372 (void)par->checkInsertChar(font);
1373 // insert the string, don't insert doublespace
1374 bool space_inserted = true;
1375 for(string::const_iterator cit = str.begin();
1376 cit != str.end(); ++cit) {
1378 if (par->size() || layout.keepempty) {
1379 par->breakParagraph(params, pos,
1380 layout.isEnvironment());
1383 space_inserted = true;
1387 // do not insert consecutive spaces if !free_spacing
1388 } else if ((*cit == ' ' || *cit == '\t') &&
1389 space_inserted && !layout.free_spacing &&
1390 !par->isFreeSpacing())
1393 } else if (*cit == '\t') {
1394 if (!layout.free_spacing && !par->isFreeSpacing()) {
1395 // tabs are like spaces here
1396 par->insertChar(pos, ' ', font);
1398 space_inserted = true;
1400 const pos_type nb = 8 - pos % 8;
1401 for (pos_type a = 0; a < nb ; ++a) {
1402 par->insertChar(pos, ' ', font);
1405 space_inserted = true;
1407 } else if (!IsPrintable(*cit)) {
1408 // Ignore unprintables
1411 // just insert the character
1412 par->insertChar(pos, *cit, font);
1414 space_inserted = (*cit == ' ');
1421 void Buffer::readInset(LyXLex & lex, Paragraph *& par,
1422 int & pos, LyXFont & font)
1424 // consistency check
1425 if (lex.getString() != "\\begin_inset") {
1426 lyxerr << "Buffer::readInset: Consistency check failed."
1433 string const tmptok = lex.getString();
1434 last_inset_read = tmptok;
1436 // test the different insets
1437 if (tmptok == "LatexCommand") {
1438 InsetCommandParams inscmd;
1441 string const cmdName = inscmd.getCmdName();
1443 // This strange command allows LyX to recognize "natbib" style
1444 // citations: citet, citep, Citet etc.
1445 if (compare_no_case(cmdName, "cite", 4) == 0) {
1446 inset = new InsetCitation(inscmd);
1447 } else if (cmdName == "bibitem") {
1448 lex.printError("Wrong place for bibitem");
1449 inset = new InsetBibKey(inscmd);
1450 } else if (cmdName == "BibTeX") {
1451 inset = new InsetBibtex(inscmd);
1452 } else if (cmdName == "index") {
1453 inset = new InsetIndex(inscmd);
1454 } else if (cmdName == "include") {
1455 inset = new InsetInclude(inscmd, *this);
1456 } else if (cmdName == "label") {
1457 inset = new InsetLabel(inscmd);
1458 } else if (cmdName == "url"
1459 || cmdName == "htmlurl") {
1460 inset = new InsetUrl(inscmd);
1461 } else if (cmdName == "ref"
1462 || cmdName == "pageref"
1463 || cmdName == "vref"
1464 || cmdName == "vpageref"
1465 || cmdName == "prettyref") {
1466 if (!inscmd.getOptions().empty()
1467 || !inscmd.getContents().empty()) {
1468 inset = new InsetRef(inscmd, *this);
1470 } else if (cmdName == "tableofcontents") {
1471 inset = new InsetTOC(inscmd);
1472 } else if (cmdName == "listofalgorithms") {
1473 inset = new InsetFloatList("algorithm");
1474 } else if (cmdName == "listoffigures") {
1475 inset = new InsetFloatList("figure");
1476 } else if (cmdName == "listoftables") {
1477 inset = new InsetFloatList("table");
1478 } else if (cmdName == "printindex") {
1479 inset = new InsetPrintIndex(inscmd);
1480 } else if (cmdName == "lyxparent") {
1481 inset = new InsetParent(inscmd, *this);
1484 bool alreadyread = false;
1485 if (tmptok == "Quotes") {
1486 inset = new InsetQuotes;
1487 } else if (tmptok == "External") {
1488 inset = new InsetExternal;
1489 } else if (tmptok == "FormulaMacro") {
1490 inset = new InsetFormulaMacro;
1491 } else if (tmptok == "Formula") {
1492 inset = new InsetFormula;
1493 } else if (tmptok == "Figure") { // Backward compatibility
1494 inset = new InsetFig(100, 100, *this);
1495 //inset = new InsetGraphics;
1496 } else if (tmptok == "Graphics") {
1497 inset = new InsetGraphics;
1498 } else if (tmptok == "Info") {// backwards compatibility
1499 inset = new InsetNote(this,
1500 lex.getLongString("\\end_inset"),
1503 } else if (tmptok == "Note") {
1504 inset = new InsetNote;
1505 } else if (tmptok == "Include") {
1506 InsetCommandParams p( "Include" );
1507 inset = new InsetInclude(p, *this);
1508 } else if (tmptok == "ERT") {
1509 inset = new InsetERT;
1510 } else if (tmptok == "Tabular") {
1511 inset = new InsetTabular(*this);
1512 } else if (tmptok == "Text") {
1513 inset = new InsetText;
1514 } else if (tmptok == "Foot") {
1515 inset = new InsetFoot;
1516 } else if (tmptok == "Marginal") {
1517 inset = new InsetMarginal;
1518 } else if (tmptok == "Minipage") {
1519 inset = new InsetMinipage;
1520 } else if (tmptok == "Float") {
1522 string tmptok = lex.getString();
1523 inset = new InsetFloat(tmptok);
1525 } else if (tmptok == "List") {
1526 inset = new InsetList;
1527 } else if (tmptok == "Theorem") {
1528 inset = new InsetList;
1530 } else if (tmptok == "Caption") {
1531 inset = new InsetCaption;
1532 } else if (tmptok == "FloatList") {
1533 inset = new InsetFloatList;
1536 if (inset && !alreadyread) inset->read(this, lex);
1540 par->insertInset(pos, inset, font);
1546 bool Buffer::readFile(LyXLex & lex, Paragraph * par)
1550 string const token(lex.getString());
1551 if (token == "\\lyxformat") { // the first token _must_ be...
1553 string tmp_format = lex.getString();
1554 //lyxerr << "LyX Format: `" << tmp_format << "'" << endl;
1555 // if present remove ".," from string.
1556 string::size_type dot = tmp_format.find_first_of(".,");
1557 //lyxerr << " dot found at " << dot << endl;
1558 if (dot != string::npos)
1559 tmp_format.erase(dot, 1);
1560 file_format = strToInt(tmp_format);
1561 if (file_format == LYX_FORMAT) {
1563 } else if (file_format > LYX_FORMAT) {
1565 Alert::alert(_("Warning!"),
1566 _("LyX file format is newer that what"),
1567 _("is supported in this LyX version. Expect some problems."));
1569 } else if (file_format < LYX_FORMAT) {
1571 if (file_format < 200) {
1572 Alert::alert(_("ERROR!"),
1573 _("Old LyX file format found. "
1574 "Use LyX 0.10.x to read this!"));
1578 bool the_end = readLyXformat2(lex, par);
1579 params.setPaperStuff();
1580 // the_end was added in 213
1581 if (file_format < 213)
1585 Alert::alert(_("Warning!"),
1586 _("Reading of document is not complete"),
1587 _("Maybe the document is truncated"));
1590 } else { // "\\lyxformat" not found
1591 Alert::alert(_("ERROR!"), _("Not a LyX file!"));
1594 Alert::alert(_("ERROR!"), _("Unable to read file!"));
1599 // Should probably be moved to somewhere else: BufferView? LyXView?
1600 bool Buffer::save() const
1602 // We don't need autosaves in the immediate future. (Asger)
1603 resetAutosaveTimers();
1607 if (lyxrc.make_backup) {
1608 s = fileName() + '~';
1609 if (!lyxrc.backupdir_path.empty())
1610 s = AddName(lyxrc.backupdir_path,
1611 subst(os::slashify_path(s),'/','!'));
1613 // Rename is the wrong way of making a backup,
1614 // this is the correct way.
1615 /* truss cp fil fil2:
1616 lstat("LyXVC3.lyx", 0xEFFFF898) Err#2 ENOENT
1617 stat("LyXVC.lyx", 0xEFFFF688) = 0
1618 open("LyXVC.lyx", O_RDONLY) = 3
1619 open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
1620 fstat(4, 0xEFFFF508) = 0
1621 fstat(3, 0xEFFFF508) = 0
1622 read(3, " # T h i s f i l e w".., 8192) = 5579
1623 write(4, " # T h i s f i l e w".., 5579) = 5579
1624 read(3, 0xEFFFD4A0, 8192) = 0
1627 chmod("LyXVC3.lyx", 0100644) = 0
1628 lseek(0, 0, SEEK_CUR) = 46440
1632 // Should probably have some more error checking here.
1633 // Should be cleaned up in 0.13, at least a bit.
1634 // Doing it this way, also makes the inodes stay the same.
1635 // This is still not a very good solution, in particular we
1636 // might loose the owner of the backup.
1637 FileInfo finfo(fileName());
1638 if (finfo.exist()) {
1639 mode_t fmode = finfo.getMode();
1640 struct utimbuf times = {
1641 finfo.getAccessTime(),
1642 finfo.getModificationTime() };
1644 ifstream ifs(fileName().c_str());
1645 ofstream ofs(s.c_str(), ios::out|ios::trunc);
1650 ::chmod(s.c_str(), fmode);
1652 if (::utime(s.c_str(), ×)) {
1653 lyxerr << "utime error." << endl;
1656 lyxerr << "LyX was not able to make "
1657 "backup copy. Beware." << endl;
1662 if (writeFile(fileName(), false)) {
1664 removeAutosaveFile(fileName());
1666 // Saving failed, so backup is not backup
1667 if (lyxrc.make_backup) {
1668 lyx::rename(s, fileName());
1676 // Returns false if unsuccesful
1677 bool Buffer::writeFile(string const & fname, bool flag) const
1679 // if flag is false writeFile will not create any GUI
1680 // warnings, only cerr.
1681 // Needed for autosave in background or panic save (Matthias 120496)
1683 if (read_only && (fname == filename)) {
1684 // Here we should come with a question if we should
1685 // perform the write anyway.
1687 lyxerr << _("Error! Document is read-only: ")
1690 Alert::alert(_("Error! Document is read-only: "),
1695 FileInfo finfo(fname);
1696 if (finfo.exist() && !finfo.writable()) {
1697 // Here we should come with a question if we should
1698 // try to do the save anyway. (i.e. do a chmod first)
1700 lyxerr << _("Error! Cannot write file: ")
1703 Alert::err_alert(_("Error! Cannot write file: "),
1708 ofstream ofs(fname.c_str());
1711 lyxerr << _("Error! Cannot open file: ")
1714 Alert::err_alert(_("Error! Cannot open file: "),
1720 // Use the standard "C" locale for file output.
1721 ofs.imbue(std::locale::classic());
1724 // The top of the file should not be written by params.
1726 // write out a comment in the top of the file
1727 ofs << '#' << lyx_docversion
1728 << " created this file. For more info see http://www.lyx.org/\n"
1729 << "\\lyxformat " << LYX_FORMAT << "\n";
1731 // now write out the buffer paramters.
1732 params.writeFile(ofs);
1734 Paragraph::depth_type depth = 0;
1736 // this will write out all the paragraphs
1737 // using recursive descent.
1738 paragraph->writeFile(this, ofs, params, depth);
1740 // Write marker that shows file is complete
1741 ofs << "\n\\the_end" << endl;
1745 // how to check if close went ok?
1746 // Following is an attempt... (BE 20001011)
1748 // good() returns false if any error occured, including some
1749 // formatting error.
1750 // bad() returns true if something bad happened in the buffer,
1751 // which should include file system full errors.
1758 lyxerr << "Buffer::writeFile: BAD ERROR!" << endl;
1760 lyxerr << "Buffer::writeFile: NOT SO BAD ERROR!"
1770 string const Buffer::asciiParagraph(Paragraph const * par,
1771 unsigned int linelen) const
1773 ostringstream buffer;
1774 Paragraph::depth_type depth = 0;
1776 Paragraph::depth_type ltype_depth = 0;
1777 string::size_type currlinelen = 0;
1778 bool ref_printed = false;
1782 if (!par->previous()) {
1783 // begins or ends a deeper area ?
1784 if (depth != par->params().depth()) {
1785 if (par->params().depth() > depth) {
1786 while (par->params().depth() > depth) {
1790 while (par->params().depth() < depth) {
1796 // First write the layout
1797 string const tmp = textclasslist.NameOfLayout(params.textclass, par->layout);
1798 if (tmp == "Itemize") {
1800 ltype_depth = depth + 1;
1801 } else if (tmp == "Enumerate") {
1803 ltype_depth = depth + 1;
1804 } else if (contains(tmp, "ection")) {
1806 ltype_depth = depth + 1;
1807 } else if (contains(tmp, "aragraph")) {
1809 ltype_depth = depth + 1;
1810 } else if (tmp == "Description") {
1812 ltype_depth = depth + 1;
1813 } else if (tmp == "Abstract") {
1816 } else if (tmp == "Bibliography") {
1824 /* maybe some vertical spaces */
1826 /* the labelwidthstring used in lists */
1830 /* some pagebreaks? */
1834 /* what about the alignment */
1836 lyxerr << "Should this ever happen?" << endl;
1839 for (pos_type i = 0; i < par->size(); ++i) {
1840 if (!i && !noparbreak) {
1843 for (Paragraph::depth_type j = 0; j < depth; ++j)
1845 currlinelen = depth * 2;
1848 case 4: // (Sub)Paragraph
1849 case 5: // Description
1853 buffer << "Abstract\n\n";
1855 buffer << "Abstract: ";
1857 case 7: // Bibliography
1860 buffer << "References\n\n";
1862 buffer << "References: ";
1867 buffer << par->params().labelString() << " ";
1870 if (ltype_depth > depth) {
1871 for (Paragraph::depth_type j = ltype_depth - 1;
1874 currlinelen += (ltype_depth-depth)*2;
1878 char c = par->getUChar(params, i);
1882 case Paragraph::META_INSET:
1884 Inset const * inset = par->getInset(i);
1886 if (!inset->ascii(this, buffer)) {
1889 rsplit(buffer.str().c_str(),
1891 currlinelen += s.length();
1893 // to be sure it breaks paragraph
1894 currlinelen += linelen;
1900 case Paragraph::META_NEWLINE:
1903 for (Paragraph::depth_type j = 0;
1907 currlinelen = depth * 2;
1908 if (ltype_depth > depth) {
1909 for (Paragraph::depth_type j = ltype_depth;
1912 currlinelen += (ltype_depth - depth) * 2;
1916 case Paragraph::META_HFILL:
1921 if ((linelen > 0) && (currlinelen > (linelen - 10)) &&
1922 (c == ' ') && ((i + 2) < par->size()))
1925 for (Paragraph::depth_type j = 0;
1928 currlinelen = depth * 2;
1929 if (ltype_depth > depth) {
1930 for (Paragraph::depth_type j = ltype_depth;
1933 currlinelen += (ltype_depth-depth)*2;
1935 } else if (c != '\0') {
1939 lyxerr[Debug::INFO] << "writeAsciiFile: NULL char in structure." << endl;
1943 return buffer.str().c_str();
1947 void Buffer::writeFileAscii(string const & fname, int linelen)
1949 ofstream ofs(fname.c_str());
1951 Alert::err_alert(_("Error: Cannot write file:"), fname);
1954 writeFileAscii(ofs, linelen);
1958 void Buffer::writeFileAscii(ostream & ofs, int linelen)
1960 Paragraph * par = paragraph;
1962 ofs << asciiParagraph(par, linelen);
1970 void Buffer::makeLaTeXFile(string const & fname,
1971 string const & original_path,
1972 bool nice, bool only_body)
1974 lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
1976 niceFile = nice; // this will be used by Insetincludes.
1978 tex_code_break_column = lyxrc.ascii_linelen;
1980 LyXTextClass const & tclass =
1981 textclasslist.TextClass(params.textclass);
1983 ofstream ofs(fname.c_str());
1985 Alert::err_alert(_("Error: Cannot open file: "), fname);
1989 // validate the buffer.
1990 lyxerr[Debug::LATEX] << " Validating buffer..." << endl;
1991 LaTeXFeatures features(params, tclass.numLayouts());
1993 lyxerr[Debug::LATEX] << " Buffer validation done." << endl;
1996 // The starting paragraph of the coming rows is the
1997 // first paragraph of the document. (Asger)
1998 texrow.start(paragraph, 0);
2000 if (!only_body && nice) {
2001 ofs << "%% " << lyx_docversion << " created this file. "
2002 "For more info, see http://www.lyx.org/.\n"
2003 "%% Do not edit unless you really know what "
2008 lyxerr[Debug::INFO] << "lyx header finished" << endl;
2009 // There are a few differences between nice LaTeX and usual files:
2010 // usual is \batchmode and has a
2011 // special input@path to allow the including of figures
2012 // with either \input or \includegraphics (what figinsets do).
2013 // batchmode is not set if there is a tex_code_break_column.
2014 // In this case somebody is interested in the generated LaTeX,
2015 // so this is OK. input@path is set when the actual parameter
2016 // original_path is set. This is done for usual tex-file, but not
2017 // for nice-latex-file. (Matthias 250696)
2020 // code for usual, NOT nice-latex-file
2021 ofs << "\\batchmode\n"; // changed
2022 // from \nonstopmode
2025 if (!original_path.empty()) {
2026 ofs << "\\makeatletter\n"
2027 << "\\def\\input@path{{"
2028 << os::external_path(original_path) << "/}}\n"
2029 << "\\makeatother\n";
2035 ofs << "\\documentclass";
2037 ostringstream options; // the document class options.
2039 if (tokenPos(tclass.opt_fontsize(),
2040 '|', params.fontsize) >= 0) {
2041 // only write if existing in list (and not default)
2042 options << params.fontsize << "pt,";
2046 if (!params.use_geometry &&
2047 (params.paperpackage == BufferParams::PACKAGE_NONE)) {
2048 switch (params.papersize) {
2049 case BufferParams::PAPER_A4PAPER:
2050 options << "a4paper,";
2052 case BufferParams::PAPER_USLETTER:
2053 options << "letterpaper,";
2055 case BufferParams::PAPER_A5PAPER:
2056 options << "a5paper,";
2058 case BufferParams::PAPER_B5PAPER:
2059 options << "b5paper,";
2061 case BufferParams::PAPER_EXECUTIVEPAPER:
2062 options << "executivepaper,";
2064 case BufferParams::PAPER_LEGALPAPER:
2065 options << "legalpaper,";
2071 if (params.sides != tclass.sides()) {
2072 switch (params.sides) {
2073 case LyXTextClass::OneSide:
2074 options << "oneside,";
2076 case LyXTextClass::TwoSides:
2077 options << "twoside,";
2083 if (params.columns != tclass.columns()) {
2084 if (params.columns == 2)
2085 options << "twocolumn,";
2087 options << "onecolumn,";
2090 if (!params.use_geometry
2091 && params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
2092 options << "landscape,";
2094 // language should be a parameter to \documentclass
2096 ostringstream language_options;
2097 if (params.language->babel() == "hebrew"
2098 && default_language->babel() != "hebrew")
2099 // This seems necessary
2100 features.useLanguage(default_language);
2102 if (lyxrc.language_use_babel ||
2103 params.language->lang() != lyxrc.default_language ||
2104 !features.hasLanguages()) {
2106 language_options << features.getLanguages();
2107 language_options << params.language->babel();
2108 if (lyxrc.language_global_options)
2109 options << language_options.str() << ',';
2112 // the user-defined options
2113 if (!params.options.empty()) {
2114 options << params.options << ',';
2117 string strOptions(options.str().c_str());
2118 if (!strOptions.empty()){
2119 strOptions = strip(strOptions, ',');
2120 ofs << '[' << strOptions << ']';
2124 << textclasslist.LatexnameOfClass(params.textclass)
2127 // end of \documentclass defs
2129 // font selection must be done before loading fontenc.sty
2130 // The ae package is not needed when using OT1 font encoding.
2131 if (params.fonts != "default" &&
2132 (params.fonts != "ae" || lyxrc.fontenc != "default")) {
2133 ofs << "\\usepackage{" << params.fonts << "}\n";
2135 if (params.fonts == "ae") {
2136 ofs << "\\usepackage{aecompl}\n";
2140 // this one is not per buffer
2141 if (lyxrc.fontenc != "default") {
2142 ofs << "\\usepackage[" << lyxrc.fontenc
2147 if (params.inputenc == "auto") {
2148 string const doc_encoding =
2149 params.language->encoding()->LatexName();
2151 // Create a list with all the input encodings used
2153 set<string> encodings = features.getEncodingSet(doc_encoding);
2155 ofs << "\\usepackage[";
2156 std::copy(encodings.begin(), encodings.end(),
2157 std::ostream_iterator<string>(ofs, ","));
2158 ofs << doc_encoding << "]{inputenc}\n";
2160 } else if (params.inputenc != "default") {
2161 ofs << "\\usepackage[" << params.inputenc
2166 // At the very beginning the text parameters.
2167 if (params.paperpackage != BufferParams::PACKAGE_NONE) {
2168 switch (params.paperpackage) {
2169 case BufferParams::PACKAGE_A4:
2170 ofs << "\\usepackage{a4}\n";
2173 case BufferParams::PACKAGE_A4WIDE:
2174 ofs << "\\usepackage{a4wide}\n";
2177 case BufferParams::PACKAGE_WIDEMARGINSA4:
2178 ofs << "\\usepackage[widemargins]{a4}\n";
2183 if (params.use_geometry) {
2184 ofs << "\\usepackage{geometry}\n";
2186 ofs << "\\geometry{verbose";
2187 if (params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
2188 ofs << ",landscape";
2189 switch (params.papersize2) {
2190 case BufferParams::VM_PAPER_CUSTOM:
2191 if (!params.paperwidth.empty())
2192 ofs << ",paperwidth="
2193 << params.paperwidth;
2194 if (!params.paperheight.empty())
2195 ofs << ",paperheight="
2196 << params.paperheight;
2198 case BufferParams::VM_PAPER_USLETTER:
2199 ofs << ",letterpaper";
2201 case BufferParams::VM_PAPER_USLEGAL:
2202 ofs << ",legalpaper";
2204 case BufferParams::VM_PAPER_USEXECUTIVE:
2205 ofs << ",executivepaper";
2207 case BufferParams::VM_PAPER_A3:
2210 case BufferParams::VM_PAPER_A4:
2213 case BufferParams::VM_PAPER_A5:
2216 case BufferParams::VM_PAPER_B3:
2219 case BufferParams::VM_PAPER_B4:
2222 case BufferParams::VM_PAPER_B5:
2226 // default papersize ie BufferParams::VM_PAPER_DEFAULT
2227 switch (lyxrc.default_papersize) {
2228 case BufferParams::PAPER_DEFAULT: // keep compiler happy
2229 case BufferParams::PAPER_USLETTER:
2230 ofs << ",letterpaper";
2232 case BufferParams::PAPER_LEGALPAPER:
2233 ofs << ",legalpaper";
2235 case BufferParams::PAPER_EXECUTIVEPAPER:
2236 ofs << ",executivepaper";
2238 case BufferParams::PAPER_A3PAPER:
2241 case BufferParams::PAPER_A4PAPER:
2244 case BufferParams::PAPER_A5PAPER:
2247 case BufferParams::PAPER_B5PAPER:
2252 if (!params.topmargin.empty())
2253 ofs << ",tmargin=" << params.topmargin;
2254 if (!params.bottommargin.empty())
2255 ofs << ",bmargin=" << params.bottommargin;
2256 if (!params.leftmargin.empty())
2257 ofs << ",lmargin=" << params.leftmargin;
2258 if (!params.rightmargin.empty())
2259 ofs << ",rmargin=" << params.rightmargin;
2260 if (!params.headheight.empty())
2261 ofs << ",headheight=" << params.headheight;
2262 if (!params.headsep.empty())
2263 ofs << ",headsep=" << params.headsep;
2264 if (!params.footskip.empty())
2265 ofs << ",footskip=" << params.footskip;
2270 if (features.isRequired("amsstyle")
2271 && !tclass.provides(LyXTextClass::amsmath)) {
2272 ofs << "\\usepackage{amsmath}\n";
2276 if (tokenPos(tclass.opt_pagestyle(),
2277 '|', params.pagestyle) >= 0) {
2278 if (params.pagestyle == "fancy") {
2279 ofs << "\\usepackage{fancyhdr}\n";
2282 ofs << "\\pagestyle{" << params.pagestyle << "}\n";
2286 if (params.secnumdepth != tclass.secnumdepth()) {
2287 ofs << "\\setcounter{secnumdepth}{"
2288 << params.secnumdepth
2292 if (params.tocdepth != tclass.tocdepth()) {
2293 ofs << "\\setcounter{tocdepth}{"
2299 if (params.paragraph_separation) {
2300 switch (params.defskip.kind()) {
2301 case VSpace::SMALLSKIP:
2302 ofs << "\\setlength\\parskip{\\smallskipamount}\n";
2304 case VSpace::MEDSKIP:
2305 ofs << "\\setlength\\parskip{\\medskipamount}\n";
2307 case VSpace::BIGSKIP:
2308 ofs << "\\setlength\\parskip{\\bigskipamount}\n";
2310 case VSpace::LENGTH:
2311 ofs << "\\setlength\\parskip{"
2312 << params.defskip.length().asLatexString()
2315 default: // should never happen // Then delete it.
2316 ofs << "\\setlength\\parskip{\\medskipamount}\n";
2321 ofs << "\\setlength\\parindent{0pt}\n";
2325 // Now insert the LyX specific LaTeX commands...
2327 // The optional packages;
2328 string preamble(features.getPackages());
2330 // this might be useful...
2331 preamble += "\n\\makeatletter\n";
2333 // Some macros LyX will need
2334 string tmppreamble(features.getMacros());
2336 if (!tmppreamble.empty()) {
2337 preamble += "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2338 "LyX specific LaTeX commands.\n"
2339 + tmppreamble + '\n';
2342 // the text class specific preamble
2343 tmppreamble = features.getTClassPreamble();
2344 if (!tmppreamble.empty()) {
2345 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2346 "Textclass specific LaTeX commands.\n"
2347 + tmppreamble + '\n';
2350 /* the user-defined preamble */
2351 if (!params.preamble.empty()) {
2352 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2353 "User specified LaTeX commands.\n"
2354 + params.preamble + '\n';
2357 preamble += "\\makeatother\n";
2359 // Itemize bullet settings need to be last in case the user
2360 // defines their own bullets that use a package included
2361 // in the user-defined preamble -- ARRae
2362 // Actually it has to be done much later than that
2363 // since some packages like frenchb make modifications
2364 // at \begin{document} time -- JMarc
2366 for (int i = 0; i < 4; ++i) {
2367 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
2368 if (bullets_def.empty())
2369 bullets_def="\\AtBeginDocument{\n";
2370 bullets_def += " \\renewcommand{\\labelitemi";
2372 // `i' is one less than the item to modify
2379 bullets_def += "ii";
2385 bullets_def += "}{" +
2386 params.user_defined_bullets[i].getText()
2391 if (!bullets_def.empty())
2392 preamble += bullets_def + "}\n\n";
2394 for (int j = countChar(preamble, '\n'); j-- ;) {
2400 // We try to load babel late, in case it interferes
2401 // with other packages.
2403 string tmp = lyxrc.language_package;
2404 if (!lyxrc.language_global_options
2405 && tmp == "\\usepackage{babel}")
2406 tmp = string("\\usepackage[") +
2407 language_options.str().c_str() +
2414 ofs << "\\begin{document}\n";
2417 lyxerr[Debug::INFO] << "preamble finished, now the body." << endl;
2419 if (!lyxrc.language_auto_begin) {
2420 ofs << subst(lyxrc.language_command_begin, "$$lang",
2421 params.language->babel())
2426 latexParagraphs(ofs, paragraph, 0, texrow);
2428 // add this just in case after all the paragraphs
2432 if (!lyxrc.language_auto_end) {
2433 ofs << subst(lyxrc.language_command_end, "$$lang",
2434 params.language->babel())
2440 ofs << "\\end{document}\n";
2443 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
2445 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
2449 // Just to be sure. (Asger)
2452 // tex_code_break_column's value is used to decide
2453 // if we are in batchmode or not (within mathed_write()
2454 // in math_write.C) so we must set it to a non-zero
2455 // value when we leave otherwise we save incorrect .lyx files.
2456 tex_code_break_column = lyxrc.ascii_linelen;
2460 lyxerr << "File was not closed properly." << endl;
2463 lyxerr[Debug::INFO] << "Finished making latex file." << endl;
2464 lyxerr[Debug::INFO] << "Row count was " << texrow.rows()-1 << "." << endl;
2469 // LaTeX all paragraphs from par to endpar, if endpar == 0 then to the end
2471 void Buffer::latexParagraphs(ostream & ofs, Paragraph * par,
2472 Paragraph * endpar, TexRow & texrow) const
2474 bool was_title = false;
2475 bool already_title = false;
2478 while (par != endpar) {
2479 LyXLayout const & layout =
2480 textclasslist.Style(params.textclass,
2483 if (layout.intitle) {
2484 if (already_title) {
2485 lyxerr <<"Error in latexParagraphs: You"
2486 " should not mix title layouts"
2487 " with normal ones." << endl;
2490 } else if (was_title && !already_title) {
2491 ofs << "\\maketitle\n";
2493 already_title = true;
2497 if (layout.isEnvironment()) {
2498 par = par->TeXEnvironment(this, params, ofs, texrow);
2500 par = par->TeXOnePar(this, params, ofs, texrow, false);
2503 // It might be that we only have a title in this document
2504 if (was_title && !already_title) {
2505 ofs << "\\maketitle\n";
2511 bool Buffer::isLatex() const
2513 return textclasslist.TextClass(params.textclass).outputType() == LATEX;
2517 bool Buffer::isLinuxDoc() const
2519 return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC;
2523 bool Buffer::isLiterate() const
2525 return textclasslist.TextClass(params.textclass).outputType() == LITERATE;
2529 bool Buffer::isDocBook() const
2531 return textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2535 bool Buffer::isSGML() const
2537 return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC ||
2538 textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2542 void Buffer::sgmlOpenTag(ostream & os, Paragraph::depth_type depth,
2543 string const & latexname) const
2545 if (!latexname.empty() && latexname != "!-- --")
2546 //os << "<!-- " << depth << " -->" << "<" << latexname << ">";
2547 os << string(depth, ' ') << "<" << latexname << ">\n";
2551 void Buffer::sgmlCloseTag(ostream & os, Paragraph::depth_type depth,
2552 string const & latexname) const
2554 if (!latexname.empty() && latexname != "!-- --")
2555 //os << "<!-- " << depth << " -->" << "</" << latexname << ">\n";
2556 os << string(depth, ' ') << "</" << latexname << ">\n";
2560 void Buffer::makeLinuxDocFile(string const & fname, bool nice, bool body_only)
2562 ofstream ofs(fname.c_str());
2565 Alert::alert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2569 niceFile = nice; // this will be used by included files.
2571 LyXTextClass const & tclass =
2572 textclasslist.TextClass(params.textclass);
2574 LaTeXFeatures features(params, tclass.numLayouts());
2579 string top_element = textclasslist.LatexnameOfClass(params.textclass);
2582 ofs << "<!doctype linuxdoc system";
2584 string preamble = params.preamble;
2585 preamble += features.getIncludedFiles(fname);
2586 preamble += features.getLyXSGMLEntities();
2588 if (!preamble.empty()) {
2589 ofs << " [ " << preamble << " ]";
2593 if (params.options.empty())
2594 sgmlOpenTag(ofs, 0, top_element);
2596 string top = top_element;
2598 top += params.options;
2599 sgmlOpenTag(ofs, 0, top);
2603 ofs << "<!-- " << lyx_docversion
2604 << " created this file. For more info see http://www.lyx.org/"
2607 Paragraph::depth_type depth = 0; // paragraph depth
2608 Paragraph * par = paragraph;
2610 vector<string> environment_stack(5);
2613 LyXLayout const & style =
2614 textclasslist.Style(params.textclass,
2617 // treat <toc> as a special case for compatibility with old code
2618 if (par->isInset(0)) {
2619 Inset * inset = par->getInset(0);
2620 Inset::Code lyx_code = inset->lyxCode();
2621 if (lyx_code == Inset::TOC_CODE){
2622 string const temp = "toc";
2623 sgmlOpenTag(ofs, depth, temp);
2630 // environment tag closing
2631 for (; depth > par->params().depth(); --depth) {
2632 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2633 environment_stack[depth].erase();
2636 // write opening SGML tags
2637 switch (style.latextype) {
2638 case LATEX_PARAGRAPH:
2639 if (depth == par->params().depth()
2640 && !environment_stack[depth].empty()) {
2641 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2642 environment_stack[depth].erase();
2648 sgmlOpenTag(ofs, depth, style.latexname());
2654 _("Error : Wrong depth for"
2655 " LatexType Command.\n"));
2657 if (!environment_stack[depth].empty()){
2658 sgmlCloseTag(ofs, depth,
2659 environment_stack[depth]);
2663 environment_stack[depth].erase();
2664 sgmlOpenTag(ofs, depth, style.latexname());
2667 case LATEX_ENVIRONMENT:
2668 case LATEX_ITEM_ENVIRONMENT:
2669 if (depth == par->params().depth()
2670 && environment_stack[depth] != style.latexname()) {
2671 sgmlCloseTag(ofs, depth,
2672 environment_stack[depth]);
2673 environment_stack[depth].erase();
2675 if (depth < par->params().depth()) {
2676 depth = par->params().depth();
2677 environment_stack[depth].erase();
2679 if (environment_stack[depth] != style.latexname()) {
2681 sgmlOpenTag(ofs, depth, "p");
2683 sgmlOpenTag(ofs, depth, style.latexname());
2685 if (environment_stack.size() == depth + 1)
2686 environment_stack.push_back("!-- --");
2687 environment_stack[depth] = style.latexname();
2690 if (style.latexparam() == "CDATA")
2693 if (style.latextype == LATEX_ENVIRONMENT) break;
2695 if (style.labeltype == LABEL_MANUAL)
2700 sgmlOpenTag(ofs, depth + 1, item_name);
2703 sgmlOpenTag(ofs, depth, style.latexname());
2707 simpleLinuxDocOnePar(ofs, par, depth);
2712 // write closing SGML tags
2713 switch (style.latextype) {
2716 case LATEX_ENVIRONMENT:
2717 case LATEX_ITEM_ENVIRONMENT:
2718 if (style.latexparam() == "CDATA")
2722 sgmlCloseTag(ofs, depth, style.latexname());
2728 for (int i=depth; i >= 0; --i)
2729 sgmlCloseTag(ofs, depth, environment_stack[i]);
2733 sgmlCloseTag(ofs, 0, top_element);
2737 // How to check for successful close
2741 // checks, if newcol chars should be put into this line
2742 // writes newline, if necessary.
2745 void sgmlLineBreak(ostream & os, string::size_type & colcount,
2746 string::size_type newcol)
2749 if (colcount > lyxrc.ascii_linelen) {
2751 colcount = newcol; // assume write after this call
2766 string tag_name(PAR_TAG const & pt) {
2768 case NONE: return "!-- --";
2769 case TT: return "tt";
2770 case SF: return "sf";
2771 case BF: return "bf";
2772 case IT: return "it";
2773 case SL: return "sl";
2774 case EM: return "em";
2781 void operator|=(PAR_TAG & p1, PAR_TAG const & p2)
2783 p1 = static_cast<PAR_TAG>(p1 | p2);
2788 void reset(PAR_TAG & p1, PAR_TAG const & p2)
2790 p1 = static_cast<PAR_TAG>( p1 & ~p2);
2796 // Handle internal paragraph parsing -- layout already processed.
2797 void Buffer::simpleLinuxDocOnePar(ostream & os,
2799 Paragraph::depth_type /*depth*/)
2801 LyXLayout const & style = textclasslist.Style(params.textclass,
2803 string::size_type char_line_count = 5; // Heuristic choice ;-)
2805 // gets paragraph main font
2808 if (style.labeltype == LABEL_MANUAL) {
2809 font_old = style.labelfont;
2812 font_old = style.font;
2816 LyXFont::FONT_FAMILY family_type = LyXFont::ROMAN_FAMILY;
2817 LyXFont::FONT_SERIES series_type = LyXFont::MEDIUM_SERIES;
2818 LyXFont::FONT_SHAPE shape_type = LyXFont::UP_SHAPE;
2821 stack<PAR_TAG> tag_state;
2822 // parsing main loop
2823 for (pos_type i = 0; i < par->size(); ++i) {
2825 PAR_TAG tag_close = NONE;
2826 list < PAR_TAG > tag_open;
2828 LyXFont const font = par->getFont(params, i);
2830 if (font_old.family() != font.family()) {
2831 switch (family_type) {
2832 case LyXFont::SANS_FAMILY:
2835 case LyXFont::TYPEWRITER_FAMILY:
2842 family_type = font.family();
2844 switch (family_type) {
2845 case LyXFont::SANS_FAMILY:
2846 tag_open.push_back(SF);
2848 case LyXFont::TYPEWRITER_FAMILY:
2849 tag_open.push_back(TT);
2856 if (font_old.series() != font.series()) {
2857 switch (series_type) {
2858 case LyXFont::BOLD_SERIES:
2865 series_type = font.series();
2867 switch (series_type) {
2868 case LyXFont::BOLD_SERIES:
2869 tag_open.push_back(BF);
2877 if (font_old.shape() != font.shape()) {
2878 switch (shape_type) {
2879 case LyXFont::ITALIC_SHAPE:
2882 case LyXFont::SLANTED_SHAPE:
2889 shape_type = font.shape();
2891 switch (shape_type) {
2892 case LyXFont::ITALIC_SHAPE:
2893 tag_open.push_back(IT);
2895 case LyXFont::SLANTED_SHAPE:
2896 tag_open.push_back(SL);
2903 if (font_old.emph() != font.emph()) {
2904 if (font.emph() == LyXFont::ON) {
2905 tag_open.push_back(EM);
2914 list < PAR_TAG > temp;
2915 while (!tag_state.empty() && tag_close ) {
2916 PAR_TAG k = tag_state.top();
2918 os << "</" << tag_name(k) << ">";
2925 for(list< PAR_TAG >::const_iterator j = temp.begin();
2926 j != temp.end(); ++j) {
2928 os << "<" << tag_name(*j) << ">";
2931 for(list< PAR_TAG >::const_iterator j = tag_open.begin();
2932 j != tag_open.end(); ++j) {
2934 os << "<" << tag_name(*j) << ">";
2937 char c = par->getChar(i);
2939 if (c == Paragraph::META_INSET) {
2940 Inset * inset = par->getInset(i);
2941 inset->linuxdoc(this, os);
2946 if (style.latexparam() == "CDATA") {
2947 // "TeX"-Mode on == > SGML-Mode on.
2953 if (par->sgmlConvertChar(c, sgml_string)
2954 && !style.free_spacing && !par->isFreeSpacing())
2956 // in freespacing mode, spaces are
2957 // non-breaking characters
2958 if (desc_on) {// if char is ' ' then...
2961 sgmlLineBreak(os, char_line_count, 6);
2965 sgmlLineBreak(os, char_line_count, 1);
2970 char_line_count += sgml_string.length();
2976 while (!tag_state.empty()) {
2977 os << "</" << tag_name(tag_state.top()) << ">";
2981 // resets description flag correctly
2983 // <tag> not closed...
2984 sgmlLineBreak(os, char_line_count, 6);
2990 // Print an error message.
2991 void Buffer::sgmlError(Paragraph * par, int pos,
2992 string const & message) const
2994 // insert an error marker in text
2995 InsetError * new_inset = new InsetError(message);
2996 par->insertInset(pos, new_inset, LyXFont(LyXFont::ALL_INHERIT,
3001 void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
3003 ofstream ofs(fname.c_str());
3005 Alert::alert(_("LYX_ERROR:"), _("Cannot write file"), fname);
3009 Paragraph * par = paragraph;
3011 niceFile = nice; // this will be used by Insetincludes.
3013 LyXTextClass const & tclass =
3014 textclasslist.TextClass(params.textclass);
3016 LaTeXFeatures features(params, tclass.numLayouts());
3021 string top_element = textclasslist.LatexnameOfClass(params.textclass);
3024 ofs << "<!DOCTYPE " << top_element
3025 << " PUBLIC \"-//OASIS//DTD DocBook V4.1//EN\"";
3027 string preamble = params.preamble;
3028 preamble += features.getIncludedFiles(fname);
3029 preamble += features.getLyXSGMLEntities();
3031 if (!preamble.empty()) {
3032 ofs << "\n [ " << preamble << " ]";
3037 string top = top_element;
3039 top += params.language->code();
3042 if (!params.options.empty()) {
3044 top += params.options;
3046 sgmlOpenTag(ofs, 0, top);
3048 ofs << "<!-- DocBook file was created by " << lyx_docversion
3049 << "\n See http://www.lyx.org/ for more information -->\n";
3051 vector<string> environment_stack(10);
3052 vector<string> environment_inner(10);
3053 vector<string> command_stack(10);
3055 bool command_flag = false;
3056 Paragraph::depth_type command_depth = 0;
3057 Paragraph::depth_type command_base = 0;
3058 Paragraph::depth_type cmd_depth = 0;
3059 Paragraph::depth_type depth = 0; // paragraph depth
3062 string command_name;
3068 int desc_on = 0; // description mode
3070 LyXLayout const & style =
3071 textclasslist.Style(params.textclass,
3074 // environment tag closing
3075 for (; depth > par->params().depth(); --depth) {
3076 if (environment_inner[depth] != "!-- --") {
3077 item_name = "listitem";
3078 sgmlCloseTag(ofs, command_depth + depth,
3080 if (environment_inner[depth] == "varlistentry")
3081 sgmlCloseTag(ofs, depth+command_depth,
3082 environment_inner[depth]);
3084 sgmlCloseTag(ofs, depth + command_depth,
3085 environment_stack[depth]);
3086 environment_stack[depth].erase();
3087 environment_inner[depth].erase();
3090 if (depth == par->params().depth()
3091 && environment_stack[depth] != style.latexname()
3092 && !environment_stack[depth].empty()) {
3093 if (environment_inner[depth] != "!-- --") {
3094 item_name= "listitem";
3095 sgmlCloseTag(ofs, command_depth+depth,
3097 if (environment_inner[depth] == "varlistentry")
3099 depth + command_depth,
3100 environment_inner[depth]);
3103 sgmlCloseTag(ofs, depth + command_depth,
3104 environment_stack[depth]);
3106 environment_stack[depth].erase();
3107 environment_inner[depth].erase();
3110 // Write opening SGML tags.
3111 switch (style.latextype) {
3112 case LATEX_PARAGRAPH:
3113 sgmlOpenTag(ofs, depth + command_depth,
3120 _("Error : Wrong depth for "
3121 "LatexType Command.\n"));
3123 command_name = style.latexname();
3125 sgmlparam = style.latexparam();
3126 c_params = split(sgmlparam, c_depth,'|');
3128 cmd_depth = lyx::atoi(c_depth);
3131 if (cmd_depth < command_base) {
3132 for (Paragraph::depth_type j = command_depth; j >= command_base; --j)
3133 sgmlCloseTag(ofs, j, command_stack[j]);
3134 command_depth = command_base = cmd_depth;
3135 } else if (cmd_depth <= command_depth) {
3136 for (int j = command_depth; j >= int(cmd_depth); --j)
3137 sgmlCloseTag(ofs, j, command_stack[j]);
3138 command_depth = cmd_depth;
3140 command_depth = cmd_depth;
3142 command_depth = command_base = cmd_depth;
3143 command_flag = true;
3145 if (command_stack.size() == command_depth + 1)
3146 command_stack.push_back(string());
3147 command_stack[command_depth] = command_name;
3149 // treat label as a special case for
3150 // more WYSIWYM handling.
3151 // This is a hack while paragraphs can't have
3152 // attributes, like id in this case.
3153 if (par->isInset(0)) {
3154 Inset * inset = par->getInset(0);
3155 Inset::Code lyx_code = inset->lyxCode();
3156 if (lyx_code == Inset::LABEL_CODE){
3157 command_name += " id=\"";
3158 command_name += (static_cast<InsetCommand *>(inset))->getContents();
3159 command_name += "\"";
3164 sgmlOpenTag(ofs, depth + command_depth, command_name);
3165 if (c_params.empty())
3166 item_name = "title";
3168 item_name = c_params;
3169 sgmlOpenTag(ofs, depth + 1 + command_depth, item_name);
3172 case LATEX_ENVIRONMENT:
3173 case LATEX_ITEM_ENVIRONMENT:
3174 if (depth < par->params().depth()) {
3175 depth = par->params().depth();
3176 environment_stack[depth].erase();
3179 if (environment_stack[depth] != style.latexname()) {
3180 if(environment_stack.size() == depth + 1) {
3181 environment_stack.push_back("!-- --");
3182 environment_inner.push_back("!-- --");
3184 environment_stack[depth] = style.latexname();
3185 environment_inner[depth] = "!-- --";
3186 sgmlOpenTag(ofs, depth + command_depth,
3187 environment_stack[depth]);
3189 if (environment_inner[depth] != "!-- --") {
3190 item_name= "listitem";
3192 command_depth + depth,
3194 if (environment_inner[depth] == "varlistentry")
3196 depth + command_depth,
3197 environment_inner[depth]);
3201 if (style.latextype == LATEX_ENVIRONMENT) {
3202 if (!style.latexparam().empty()) {
3203 if(style.latexparam() == "CDATA")
3206 sgmlOpenTag(ofs, depth + command_depth,
3207 style.latexparam());
3212 desc_on = (style.labeltype == LABEL_MANUAL);
3215 environment_inner[depth]= "varlistentry";
3217 environment_inner[depth]= "listitem";
3219 sgmlOpenTag(ofs, depth + 1 + command_depth,
3220 environment_inner[depth]);
3224 sgmlOpenTag(ofs, depth + 1 + command_depth,
3228 sgmlOpenTag(ofs, depth + 1 + command_depth,
3233 sgmlOpenTag(ofs, depth + command_depth,
3238 simpleDocBookOnePar(ofs, par, desc_on, depth+1+command_depth);
3242 // write closing SGML tags
3243 switch (style.latextype) {
3245 if (c_params.empty())
3249 sgmlCloseTag(ofs, depth + command_depth, end_tag);
3251 case LATEX_ENVIRONMENT:
3252 if (!style.latexparam().empty()) {
3253 if(style.latexparam() == "CDATA")
3256 sgmlCloseTag(ofs, depth + command_depth,
3257 style.latexparam());
3260 case LATEX_ITEM_ENVIRONMENT:
3261 if (desc_on == 1) break;
3263 sgmlCloseTag(ofs, depth + 1 + command_depth, end_tag);
3265 case LATEX_PARAGRAPH:
3266 sgmlCloseTag(ofs, depth + command_depth, style.latexname());
3269 sgmlCloseTag(ofs, depth + command_depth, style.latexname());
3275 for (int d = depth; d >= 0; --d) {
3276 if (!environment_stack[depth].empty()) {
3277 if (environment_inner[depth] != "!-- --") {
3278 item_name = "listitem";
3279 sgmlCloseTag(ofs, command_depth + depth,
3281 if (environment_inner[depth] == "varlistentry")
3282 sgmlCloseTag(ofs, depth + command_depth,
3283 environment_inner[depth]);
3286 sgmlCloseTag(ofs, depth + command_depth,
3287 environment_stack[depth]);
3291 for (int j = command_depth; j >= 0 ; --j)
3292 if (!command_stack[j].empty())
3293 sgmlCloseTag(ofs, j, command_stack[j]);
3296 sgmlCloseTag(ofs, 0, top_element);
3299 // How to check for successful close
3303 void Buffer::simpleDocBookOnePar(ostream & os,
3304 Paragraph * par, int & desc_on,
3305 Paragraph::depth_type depth) const
3307 bool emph_flag = false;
3309 LyXLayout const & style = textclasslist.Style(params.textclass,
3312 LyXFont font_old = style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
3314 int char_line_count = depth;
3315 //if (!style.free_spacing)
3316 // os << string(depth,' ');
3318 // parsing main loop
3319 for (pos_type i = 0; i < par->size(); ++i) {
3320 LyXFont font = par->getFont(params, i);
3322 // handle <emphasis> tag
3323 if (font_old.emph() != font.emph()) {
3324 if (font.emph() == LyXFont::ON) {
3328 os << "</emphasis>";
3334 if ( par->isInset(i) ) {
3335 Inset * inset = par->getInset(i);
3336 // don't print the inset in position 0 if desc_on == 3 (label)
3337 if ( i || desc_on != 3)
3338 inset->docbook(this, os);
3340 char c = par->getChar(i);
3342 par->sgmlConvertChar(c, sgml_string);
3344 if (style.pass_thru) {
3346 } else if(style.free_spacing || par->isFreeSpacing() || c != ' ') {
3348 } else if (desc_on ==1) {
3350 os << "\n</term><listitem><para>";
3360 os << "</emphasis>";
3363 // resets description flag correctly
3365 // <term> not closed...
3368 if(style.free_spacing) os << '\n';
3372 // This should be enabled when the Chktex class is implemented. (Asger)
3373 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
3374 // Other flags: -wall -v0 -x
3375 int Buffer::runChktex()
3377 if (!users->text) return 0;
3379 users->owner()->prohibitInput();
3381 // get LaTeX-Filename
3382 string const name = getLatexName();
3383 string path = OnlyPath(filename);
3385 string const org_path = path;
3386 if (lyxrc.use_tempdir || !IsDirWriteable(path)) {
3390 Path p(path); // path to LaTeX file
3391 users->owner()->message(_("Running chktex..."));
3393 // Remove all error insets
3394 bool const removedErrorInsets = users->removeAutoInsets();
3396 // Generate the LaTeX file if neccessary
3397 makeLaTeXFile(name, org_path, false);
3400 Chktex chktex(lyxrc.chktex_command, name, filepath);
3401 int res = chktex.run(terr); // run chktex
3404 Alert::alert(_("chktex did not work!"),
3405 _("Could not run with file:"), name);
3406 } else if (res > 0) {
3407 // Insert all errors as errors boxes
3408 users->insertErrors(terr);
3411 // if we removed error insets before we ran chktex or if we inserted
3412 // error insets after we ran chktex, this must be run:
3413 if (removedErrorInsets || res){
3417 users->owner()->allowInput();
3423 void Buffer::validate(LaTeXFeatures & features) const
3425 Paragraph * par = paragraph;
3426 LyXTextClass const & tclass =
3427 textclasslist.TextClass(params.textclass);
3429 // AMS Style is at document level
3430 if (params.use_amsmath || tclass.provides(LyXTextClass::amsmath))
3431 features.require("amsstyle");
3434 // We don't use "lyxerr.debug" because of speed. (Asger)
3435 if (lyxerr.debugging(Debug::LATEX))
3436 lyxerr << "Paragraph: " << par << endl;
3438 // Now just follow the list of paragraphs and run
3439 // validate on each of them.
3440 par->validate(features);
3442 // and then the next paragraph
3446 // the bullet shapes are buffer level not paragraph level
3447 // so they are tested here
3448 for (int i = 0; i < 4; ++i) {
3449 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
3450 int const font = params.user_defined_bullets[i].getFont();
3452 int const c = params
3453 .user_defined_bullets[i]
3460 features.require("latexsym");
3462 } else if (font == 1) {
3463 features.require("amssymb");
3464 } else if ((font >= 2 && font <= 5)) {
3465 features.require("pifont");
3470 if (lyxerr.debugging(Debug::LATEX)) {
3471 features.showStruct();
3476 // This function should be in Buffer because it's a buffer's property (ale)
3477 string const Buffer::getIncludeonlyList(char delim)
3480 for (inset_iterator it = inset_iterator_begin();
3481 it != inset_iterator_end(); ++it) {
3482 if ((*it)->lyxCode() == Inset::INCLUDE_CODE) {
3483 InsetInclude * insetinc =
3484 static_cast<InsetInclude *>(*it);
3485 if (insetinc->isIncludeOnly()) {
3488 lst += insetinc->getRelFileBaseName();
3492 lyxerr[Debug::INFO] << "Includeonly(" << lst << ')' << endl;
3497 vector<string> const Buffer::getLabelList()
3499 /// if this is a child document and the parent is already loaded
3500 /// Use the parent's list instead [ale990407]
3501 if (!params.parentname.empty()
3502 && bufferlist.exists(params.parentname)) {
3503 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3505 return tmp->getLabelList();
3508 vector<string> label_list;
3509 for (inset_iterator it = inset_iterator_begin();
3510 it != inset_iterator_end(); ++it) {
3511 vector<string> const l = (*it)->getLabelList();
3512 label_list.insert(label_list.end(), l.begin(), l.end());
3518 Buffer::Lists const Buffer::getLists() const
3521 Paragraph * par = paragraph;
3524 std::pair<bool, textclass_type> const tmp =
3525 textclasslist.NumberOfLayout(params.textclass, "Caption");
3526 bool const found = tmp.first;
3527 textclass_type const cap = tmp.second;
3530 // This is the prefered way to to this, but boost::tie can break
3534 boost::tie(found, cap) = textclasslist
3535 .NumberOfLayout(params.textclass, "Caption");
3539 char const labeltype =
3540 textclasslist.Style(params.textclass,
3541 par->getLayout()).labeltype;
3543 if (labeltype >= LABEL_COUNTER_CHAPTER
3544 && labeltype <= LABEL_COUNTER_CHAPTER + params.tocdepth) {
3545 // insert this into the table of contents
3546 SingleList & item = l["TOC"];
3549 textclasslist.TextClass(params.textclass).maxcounter());
3550 item.push_back(TocItem(par, depth, par->asString(this, true)));
3552 // For each paragrph, traverse its insets and look for
3556 Paragraph::inset_iterator it =
3557 par->inset_iterator_begin();
3558 Paragraph::inset_iterator end =
3559 par->inset_iterator_end();
3561 for (; it != end; ++it) {
3562 if ((*it)->lyxCode() == Inset::FLOAT_CODE) {
3564 static_cast<InsetFloat*>(*it);
3566 string const type = il->type();
3568 // Now find the caption in the float...
3569 // We now tranverse the paragraphs of
3571 Paragraph * tmp = il->inset.paragraph();
3573 if (tmp->layout == cap) {
3574 SingleList & item = l[type];
3576 tostr(item.size()+1) + ". " + tmp->asString(this, false);
3577 item.push_back(TocItem(tmp, 0 , str));
3584 lyxerr << "caption not found" << endl;
3593 // This is also a buffer property (ale)
3594 vector<pair<string, string> > const Buffer::getBibkeyList()
3596 /// if this is a child document and the parent is already loaded
3597 /// Use the parent's list instead [ale990412]
3598 if (!params.parentname.empty() && bufferlist.exists(params.parentname)) {
3599 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3601 return tmp->getBibkeyList();
3604 vector<pair<string, string> > keys;
3605 Paragraph * par = paragraph;
3608 keys.push_back(pair<string, string>(par->bibkey->getContents(),
3609 par->asString(this, false)));
3613 // Might be either using bibtex or a child has bibliography
3615 for (inset_iterator it = inset_iterator_begin();
3616 it != inset_iterator_end(); ++it) {
3617 // Search for Bibtex or Include inset
3618 if ((*it)->lyxCode() == Inset::BIBTEX_CODE) {
3619 vector<pair<string,string> > tmp =
3620 static_cast<InsetBibtex*>(*it)->getKeys(this);
3621 keys.insert(keys.end(), tmp.begin(), tmp.end());
3622 } else if ((*it)->lyxCode() == Inset::INCLUDE_CODE) {
3623 vector<pair<string,string> > const tmp =
3624 static_cast<InsetInclude*>(*it)->getKeys();
3625 keys.insert(keys.end(), tmp.begin(), tmp.end());
3634 bool Buffer::isDepClean(string const & name) const
3636 DEPCLEAN * item = dep_clean;
3637 while (item && item->master != name)
3639 if (!item) return true;
3644 void Buffer::markDepClean(string const & name)
3647 dep_clean = new DEPCLEAN;
3648 dep_clean->clean = true;
3649 dep_clean->master = name;
3650 dep_clean->next = 0;
3652 DEPCLEAN * item = dep_clean;
3653 while (item && item->master != name)
3658 item = new DEPCLEAN;
3660 item->master = name;
3667 bool Buffer::dispatch(string const & command)
3669 // Split command string into command and argument
3671 string line = frontStrip(command);
3672 string const arg = strip(frontStrip(split(line, cmd, ' ')));
3674 return dispatch(lyxaction.LookupFunc(cmd), arg);
3678 bool Buffer::dispatch(int action, string const & argument)
3680 bool dispatched = true;
3683 Exporter::Export(this, argument, false);
3693 void Buffer::resizeInsets(BufferView * bv)
3695 /// then remove all LyXText in text-insets
3696 Paragraph * par = paragraph;
3697 for (; par; par = par->next()) {
3698 par->resizeInsetsLyXText(bv);
3703 void Buffer::redraw()
3710 void Buffer::changeLanguage(Language const * from, Language const * to)
3713 ParIterator end = par_iterator_end();
3714 for (ParIterator it = par_iterator_begin(); it != end; ++it)
3715 (*it)->changeLanguage(params, from, to);
3719 bool Buffer::isMultiLingual()
3721 ParIterator end = par_iterator_end();
3722 for (ParIterator it = par_iterator_begin(); it != end; ++it)
3723 if ((*it)->isMultiLingual(params))
3730 Buffer::inset_iterator::inset_iterator(Paragraph * paragraph, pos_type pos)
3733 it = par->InsetIterator(pos);
3734 if (it == par->inset_iterator_end()) {
3741 void Buffer::inset_iterator::setParagraph()
3744 it = par->inset_iterator_begin();
3745 if (it != par->inset_iterator_end())
3750 // We maintain an invariant that whenever par = 0 then it = 0
3754 Inset * Buffer::getInsetFromID(int id_arg) const
3756 for (inset_iterator it = inset_const_iterator_begin();
3757 it != inset_const_iterator_end(); ++it)
3759 if ((*it)->id() == id_arg)
3761 Inset * in = (*it)->getInsetFromID(id_arg);
3769 Paragraph * Buffer::getParFromID(int id) const
3771 if (id < 0) return 0;
3772 Paragraph * par = paragraph;
3774 if (par->id() == id) {
3777 Paragraph * tmp = par->getParFromID(id);
3787 ParIterator Buffer::par_iterator_begin()
3789 return ParIterator(paragraph);
3793 ParIterator Buffer::par_iterator_end()
3795 return ParIterator();