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 * ======================================================
26 #include <sys/types.h>
36 #pragma implementation
40 #include "bufferlist.h"
42 #include "lyx_gui_misc.h"
43 #include "LyXAction.h"
46 #include "tex-strings.h"
48 #include "bufferview_funcs.h"
51 #include "mathed/formulamacro.h"
52 #include "mathed/formula.h"
53 #include "insets/inset.h"
54 #include "insets/inseterror.h"
55 #include "insets/insetlabel.h"
56 #include "insets/insetref.h"
57 #include "insets/inseturl.h"
58 #include "insets/insetnote.h"
59 #include "insets/insetquotes.h"
60 #include "insets/insetlatexaccent.h"
61 #include "insets/insetbib.h"
62 #include "insets/insetcite.h"
63 #include "insets/insetexternal.h"
64 #include "insets/insetindex.h"
65 #include "insets/insetinclude.h"
66 #include "insets/insettoc.h"
67 #include "insets/insetparent.h"
68 #include "insets/insetspecialchar.h"
69 #include "insets/figinset.h"
70 #include "insets/insettext.h"
71 #include "insets/insetert.h"
72 #include "insets/insetgraphics.h"
73 #include "insets/insetfoot.h"
74 #include "insets/insetmarginal.h"
75 #include "insets/insetminipage.h"
76 #include "insets/insetfloat.h"
77 #include "insets/insettabular.h"
79 #include "insets/insettheorem.h"
80 #include "insets/insetlist.h"
82 #include "insets/insetcaption.h"
83 #include "insets/insetfloatlist.h"
84 #include "support/textutils.h"
85 #include "support/filetools.h"
86 #include "support/path.h"
87 #include "support/os.h"
92 #include "LaTeXFeatures.h"
93 #include "support/syscall.h"
94 #include "support/lyxlib.h"
95 #include "support/FileInfo.h"
96 #include "support/lyxmanip.h"
100 #include "lyx_gui_misc.h" // WarnReadonly()
101 #include "frontends/Dialogs.h"
102 #include "encoding.h"
103 #include "exporter.h"
104 #include "Lsstream.h"
105 #include "converter.h"
106 #include "BufferView.h"
107 #include "ParagraphParameters.h"
108 #include "iterators.h"
118 using std::make_pair;
126 // all these externs should eventually be removed.
127 extern BufferList bufferlist;
129 extern LyXAction lyxaction;
133 const int LYX_FORMAT = 220;
137 extern int tex_code_break_column;
140 Buffer::Buffer(string const & file, bool ronly)
142 lyxerr[Debug::INFO] << "Buffer::Buffer()" << endl;
144 filepath = OnlyPath(file);
153 if (read_only || (lyxrc.use_tempdir)) {
154 tmppath = CreateBufferTmpDir();
155 } else tmppath.erase();
161 lyxerr[Debug::INFO] << "Buffer::~Buffer()" << endl;
162 // here the buffer should take care that it is
163 // saved properly, before it goes into the void.
165 // make sure that views using this buffer
170 if (!tmppath.empty()) {
171 DestroyBufferTmpDir(tmppath);
174 Paragraph * par = paragraph;
177 tmppar = par->next();
185 string const Buffer::getLatexName(bool no_path) const
187 string name = ChangeExtension(MakeLatexName(filename), ".tex");
189 return OnlyFilename(name);
195 pair<Buffer::LogType, string> const Buffer::getLogName(void) const
197 string const filename = getLatexName(false);
199 if (filename.empty())
200 return make_pair(Buffer::latexlog, string());
202 string path = OnlyPath(filename);
204 if (lyxrc.use_tempdir || !IsDirWriteable(path))
207 string const fname = AddName(path,
208 OnlyFilename(ChangeExtension(filename,
211 AddName(path, OnlyFilename(
212 ChangeExtension(filename,
213 formats.extension("literate") + ".out")));
215 // If no Latex log or Build log is newer, show Build log
217 FileInfo const f_fi(fname);
218 FileInfo const b_fi(bname);
221 (!f_fi.exist() || f_fi.getModificationTime() < b_fi.getModificationTime())) {
222 lyxerr[Debug::FILES] << "Log name calculated as : " << bname << endl;
223 return make_pair(Buffer::buildlog, bname);
225 lyxerr[Debug::FILES] << "Log name calculated as : " << fname << endl;
226 return make_pair(Buffer::latexlog, fname);
230 void Buffer::setReadonly(bool flag)
232 if (read_only != flag) {
235 users->owner()->getDialogs()->updateBufferDependent(false);
238 WarnReadonly(filename);
243 /// Update window titles of all users
244 // Should work on a list
245 void Buffer::updateTitles() const
247 if (users) users->owner()->updateWindowTitle();
251 /// Reset autosave timer of all users
252 // Should work on a list
253 void Buffer::resetAutosaveTimers() const
255 if (users) users->owner()->resetAutosaveTimer();
259 void Buffer::setFileName(string const & newfile)
261 filename = MakeAbsPath(newfile);
262 filepath = OnlyPath(filename);
263 setReadonly(IsFileWriteable(filename) == 0);
268 // We'll remove this later. (Lgb)
271 string last_inset_read;
273 #ifndef NO_COMPABILITY
276 ErtComp() : active(false), in_tabular(false) {
283 std::stack<ErtComp> ert_stack;
287 #warning And _why_ is this here? (Lgb)
293 // candidate for move to BufferView
294 // (at least some parts in the beginning of the func)
297 // changed to be public and have one parameter
298 // if par = 0 normal behavior
299 // else insert behavior
300 // Returns false if "\the_end" is not read for formats >= 2.13. (Asger)
301 bool Buffer::readLyXformat2(LyXLex & lex, Paragraph * par)
304 #ifndef NO_COMPABILITY
305 ert_comp.contents.erase();
306 ert_comp.active = false;
307 ert_comp.in_tabular = false;
310 Paragraph::depth_type depth = 0;
311 bool the_end_read = false;
313 Paragraph * first_par = 0;
314 LyXFont font(LyXFont::ALL_INHERIT, params.language);
315 if (file_format < 216 && params.language->lang() == "hebrew")
316 font.setLanguage(default_language);
321 // We are inserting into an existing document
322 users->text->breakParagraph(users);
323 first_par = users->text->firstParagraph();
326 // We don't want to adopt the parameters from the
327 // document we insert, so we skip until the text begins:
330 string const pretoken = lex.getString();
331 if (pretoken == "\\layout") {
332 lex.pushToken(pretoken);
340 string const token = lex.getString();
342 if (token.empty()) continue;
344 lyxerr[Debug::PARSER] << "Handling token: `"
345 << token << "'" << endl;
348 parseSingleLyXformat2Token(lex, par, first_par,
356 paragraph = first_par;
358 if (unknown_layouts > 0) {
359 string s = _("Couldn't set the layout for ");
360 if (unknown_layouts == 1) {
361 s += _("one paragraph");
363 s += tostr(unknown_layouts);
364 s += _(" paragraphs");
366 WriteAlert(_("Textclass Loading Error!"), s,
367 _("When reading " + fileName()));
374 #ifndef NO_COMPABILITY
375 void Buffer::insertErtContents(Paragraph * par, int & pos,
376 LyXFont const & font, bool set_inactive)
378 if (!ert_comp.contents.empty()) {
379 lyxerr[Debug::INSETS] << "ERT contents:\n"
380 << ert_comp.contents << endl;
381 Inset * inset = new InsetERT(ert_comp.contents, true);
382 par->insertInset(pos++, inset, font);
383 ert_comp.contents.erase();
386 ert_comp.active = false;
393 Buffer::parseSingleLyXformat2Token(LyXLex & lex, Paragraph *& par,
394 Paragraph *& first_par,
395 string const & token, int & pos,
396 Paragraph::depth_type & depth,
400 bool the_end_read = false;
401 #ifndef NO_COMPABILITY
402 #ifndef NO_PEXTRA_REALLY
403 // This is super temporary but is needed to get the compability
404 // mode for minipages work correctly together with new tabulars.
405 static int call_depth;
407 bool checkminipage = false;
408 static Paragraph * minipar;
409 static Paragraph * parBeforeMinipage;
412 if (token[0] != '\\') {
413 #ifndef NO_COMPABILITY
414 if (ert_comp.active) {
415 ert_comp.contents += token;
418 for (string::const_iterator cit = token.begin();
419 cit != token.end(); ++cit) {
420 par->insertChar(pos, (*cit), font);
423 #ifndef NO_COMPABILITY
426 } else if (token == "\\i") {
427 Inset * inset = new InsetLatexAccent;
428 inset->read(this, lex);
429 par->insertInset(pos, inset, font);
431 } else if (token == "\\layout") {
432 #ifndef NO_COMPABILITY
433 ert_comp.in_tabular = false;
435 insertErtContents(par, pos, font);
438 string const layoutname = lex.getString();
439 pair<bool, LyXTextClass::LayoutList::size_type> pp
440 = textclasslist.NumberOfLayout(params.textclass,
443 #ifndef NO_COMPABILITY
444 if (compare_no_case(layoutname, "latex") == 0) {
445 ert_comp.active = true;
449 // The is the compability reading of layout caption.
450 // It can be removed in LyX version 1.3.0. (Lgb)
451 if (compare_no_case(layoutname, "caption") == 0) {
452 // We expect that the par we are now working on is
453 // really inside a InsetText inside a InsetFloat.
454 // We also know that captions can only be
455 // one paragraph. (Lgb)
457 // We should now read until the next "\layout"
459 // This is probably not good enough, what if the
460 // caption is the last par in the document (Lgb)
461 istream & ist = lex.getStream();
467 if (prefixIs(line, "\\layout")) {
471 if (prefixIs(line, "\\begin_inset"))
473 if (prefixIs(line, "\\end_inset")) {
484 // Now we should have the whole layout in ss
485 // we should now be able to give this to the
487 ss << "\\end_inset\n";
489 // This seems like a bug in stringstream.
490 // We really should be able to use ss
492 istringstream is(ss.str());
494 tmplex.setStream(is);
495 Inset * inset = new InsetCaption;
496 inset->Read(this, tmplex);
497 par->InsertInset(pos, inset, font);
504 par = new Paragraph(par);
508 par->layout = pp.second;
509 #ifndef NO_COMPABILITY
510 } else if (ert_comp.active) {
515 // use default layout "Standard" (0)
518 string const s = _("Layout had to be changed from\n")
519 + layoutname + _(" to ")
520 + textclasslist.NameOfLayout(params.textclass, par->layout);
521 InsetError * new_inset = new InsetError(s);
522 par->insertInset(0, new_inset);
524 // Test whether the layout is obsolete.
525 LyXLayout const & layout =
526 textclasslist.Style(params.textclass,
528 if (!layout.obsoleted_by().empty())
529 par->layout = textclasslist
530 .NumberOfLayout(params.textclass,
531 layout.obsoleted_by())
533 par->params().depth(depth);
534 font = LyXFont(LyXFont::ALL_INHERIT, params.language);
535 if (file_format < 216
536 && params.language->lang() == "hebrew")
537 font.setLanguage(default_language);
542 #ifndef NO_COMPABILITY
543 } else if (token == "\\begin_float") {
544 insertErtContents(par, pos, font);
545 //insertErtContents(par, pos, font, false);
546 //ert_stack.push(ert_comp);
547 //ert_comp = ErtComp();
549 // This is the compability reader. It can be removed in
550 // LyX version 1.3.0. (Lgb)
552 string const tmptok = lex.getString();
553 //lyxerr << "old float: " << tmptok << endl;
556 stringstream old_float;
558 if (tmptok == "footnote") {
559 inset = new InsetFoot;
560 old_float << "collapsed true\n";
561 } else if (tmptok == "margin") {
562 inset = new InsetMarginal;
563 old_float << "collapsed true\n";
564 } else if (tmptok == "fig") {
565 inset = new InsetFloat("figure");
566 old_float << "placement htbp\n"
568 << "collapsed false\n";
569 } else if (tmptok == "tab") {
570 inset = new InsetFloat("table");
571 old_float << "placement htbp\n"
573 << "collapsed false\n";
574 } else if (tmptok == "alg") {
575 inset = new InsetFloat("algorithm");
576 old_float << "placement htbp\n"
578 << "collapsed false\n";
579 } else if (tmptok == "wide-fig") {
580 inset = new InsetFloat("figure");
581 //InsetFloat * tmp = new InsetFloat("figure");
584 old_float << "placement htbp\n"
586 << "collapsed false\n";
587 } else if (tmptok == "wide-tab") {
588 inset = new InsetFloat("table");
589 //InsetFloat * tmp = new InsetFloat("table");
592 old_float << "placement htbp\n"
594 << "collapsed false\n";
598 #ifndef NO_PEXTRA_REALLY
601 return false; // no end read yet
604 // Here we need to check for \end_deeper and handle that
605 // before we do the footnote parsing.
606 // This _is_ a hack! (Lgb)
609 string const tmp = lex.getString();
610 if (tmp == "\\end_deeper") {
611 //lyxerr << "\\end_deeper caught!" << endl;
613 lex.printError("\\end_deeper: "
614 "depth is already null");
619 old_float << tmp << ' ';
624 old_float << lex.getLongString("\\end_float")
625 << "\n\\end_inset\n";
626 //lyxerr << "Float Body:\n" << old_float.str() << endl;
627 // That this does not work seems like a bug
628 // in stringstream. (Lgb)
629 istringstream istr(old_float.str());
631 nylex.setStream(istr);
632 inset->read(this, nylex);
633 par->insertInset(pos, inset, font);
635 insertErtContents(par, pos, font);
637 } else if (token == "\\begin_deeper") {
639 } else if (token == "\\end_deeper") {
641 lex.printError("\\end_deeper: "
642 "depth is already null");
646 } else if (token == "\\begin_preamble") {
647 params.readPreamble(lex);
648 } else if (token == "\\textclass") {
650 pair<bool, LyXTextClassList::size_type> pp =
651 textclasslist.NumberOfClass(lex.getString());
653 params.textclass = pp.second;
655 WriteAlert(string(_("Textclass error")),
656 string(_("The document uses an unknown textclass \"")) +
657 lex.getString() + string("\"."),
658 string(_("LyX will not be able to produce output correctly.")));
659 params.textclass = 0;
661 if (!textclasslist.Load(params.textclass)) {
662 // if the textclass wasn't loaded properly
663 // we need to either substitute another
664 // or stop loading the file.
665 // I can substitute but I don't see how I can
666 // stop loading... ideas?? ARRae980418
667 WriteAlert(_("Textclass Loading Error!"),
668 string(_("Can't load textclass ")) +
669 textclasslist.NameOfClass(params.textclass),
670 _("-- substituting default"));
671 params.textclass = 0;
673 } else if (token == "\\options") {
675 params.options = lex.getString();
676 } else if (token == "\\language") {
677 params.readLanguage(lex);
678 } else if (token == "\\fontencoding") {
680 } else if (token == "\\inputencoding") {
682 params.inputenc = lex.getString();
683 } else if (token == "\\graphics") {
684 params.readGraphicsDriver(lex);
685 } else if (token == "\\fontscheme") {
687 params.fonts = lex.getString();
688 } else if (token == "\\noindent") {
689 par->params().noindent(true);
690 } else if (token == "\\fill_top") {
691 par->params().spaceTop(VSpace(VSpace::VFILL));
692 } else if (token == "\\fill_bottom") {
693 par->params().spaceBottom(VSpace(VSpace::VFILL));
694 } else if (token == "\\line_top") {
695 par->params().lineTop(true);
696 } else if (token == "\\line_bottom") {
697 par->params().lineBottom(true);
698 } else if (token == "\\pagebreak_top") {
699 par->params().pagebreakTop(true);
700 } else if (token == "\\pagebreak_bottom") {
701 par->params().pagebreakBottom(true);
702 } else if (token == "\\start_of_appendix") {
703 par->params().startOfAppendix(true);
704 } else if (token == "\\paragraph_separation") {
705 int tmpret = lex.findToken(string_paragraph_separation);
706 if (tmpret == -1) ++tmpret;
707 if (tmpret != LYX_LAYOUT_DEFAULT)
708 params.paragraph_separation =
709 static_cast<BufferParams::PARSEP>(tmpret);
710 } else if (token == "\\defskip") {
712 params.defskip = VSpace(lex.getString());
713 } else if (token == "\\epsfig") { // obsolete
714 // Indeed it is obsolete, but we HAVE to be backwards
715 // compatible until 0.14, because otherwise all figures
716 // in existing documents are irretrivably lost. (Asger)
717 params.readGraphicsDriver(lex);
718 } else if (token == "\\quotes_language") {
719 int tmpret = lex.findToken(string_quotes_language);
720 if (tmpret == -1) ++tmpret;
721 if (tmpret != LYX_LAYOUT_DEFAULT) {
722 InsetQuotes::quote_language tmpl =
723 InsetQuotes::EnglishQ;
726 tmpl = InsetQuotes::EnglishQ;
729 tmpl = InsetQuotes::SwedishQ;
732 tmpl = InsetQuotes::GermanQ;
735 tmpl = InsetQuotes::PolishQ;
738 tmpl = InsetQuotes::FrenchQ;
741 tmpl = InsetQuotes::DanishQ;
744 params.quotes_language = tmpl;
746 } else if (token == "\\quotes_times") {
748 switch (lex.getInteger()) {
750 params.quotes_times = InsetQuotes::SingleQ;
753 params.quotes_times = InsetQuotes::DoubleQ;
756 } else if (token == "\\papersize") {
757 int tmpret = lex.findToken(string_papersize);
761 params.papersize2 = tmpret;
762 } else if (token == "\\paperpackage") {
763 int tmpret = lex.findToken(string_paperpackages);
766 params.paperpackage = BufferParams::PACKAGE_NONE;
768 params.paperpackage = tmpret;
769 } else if (token == "\\use_geometry") {
771 params.use_geometry = lex.getInteger();
772 } else if (token == "\\use_amsmath") {
774 params.use_amsmath = lex.getInteger();
775 } else if (token == "\\use_natbib") {
777 params.use_natbib = lex.getInteger();
778 } else if (token == "\\use_numerical_citations") {
780 params.use_numerical_citations = lex.getInteger();
781 } else if (token == "\\paperorientation") {
782 int tmpret = lex.findToken(string_orientation);
783 if (tmpret == -1) ++tmpret;
784 if (tmpret != LYX_LAYOUT_DEFAULT)
785 params.orientation = static_cast<BufferParams::PAPER_ORIENTATION>(tmpret);
786 } else if (token == "\\paperwidth") {
788 params.paperwidth = lex.getString();
789 } else if (token == "\\paperheight") {
791 params.paperheight = lex.getString();
792 } else if (token == "\\leftmargin") {
794 params.leftmargin = lex.getString();
795 } else if (token == "\\topmargin") {
797 params.topmargin = lex.getString();
798 } else if (token == "\\rightmargin") {
800 params.rightmargin = lex.getString();
801 } else if (token == "\\bottommargin") {
803 params.bottommargin = lex.getString();
804 } else if (token == "\\headheight") {
806 params.headheight = lex.getString();
807 } else if (token == "\\headsep") {
809 params.headsep = lex.getString();
810 } else if (token == "\\footskip") {
812 params.footskip = lex.getString();
813 } else if (token == "\\paperfontsize") {
815 params.fontsize = strip(lex.getString());
816 } else if (token == "\\papercolumns") {
818 params.columns = lex.getInteger();
819 } else if (token == "\\papersides") {
821 switch (lex.getInteger()) {
823 case 1: params.sides = LyXTextClass::OneSide; break;
824 case 2: params.sides = LyXTextClass::TwoSides; break;
826 } else if (token == "\\paperpagestyle") {
828 params.pagestyle = strip(lex.getString());
829 } else if (token == "\\bullet") {
831 int const index = lex.getInteger();
833 int temp_int = lex.getInteger();
834 params.user_defined_bullets[index].setFont(temp_int);
835 params.temp_bullets[index].setFont(temp_int);
837 temp_int = lex.getInteger();
838 params.user_defined_bullets[index].setCharacter(temp_int);
839 params.temp_bullets[index].setCharacter(temp_int);
841 temp_int = lex.getInteger();
842 params.user_defined_bullets[index].setSize(temp_int);
843 params.temp_bullets[index].setSize(temp_int);
845 string const temp_str = lex.getString();
846 if (temp_str != "\\end_bullet") {
847 // this element isn't really necessary for
848 // parsing but is easier for humans
849 // to understand bullets. Put it back and
850 // set a debug message?
851 lex.printError("\\end_bullet expected, got" + temp_str);
852 //how can I put it back?
854 } else if (token == "\\bulletLaTeX") {
856 int const index = lex.getInteger();
858 string temp_str = lex.getString();
860 while (temp_str != "\\end_bullet") {
861 // this loop structure is needed when user
862 // enters an empty string since the first
863 // thing returned will be the \\end_bullet
865 // if the LaTeX entry has spaces. Each element
866 // therefore needs to be read in turn
869 temp_str = lex.getString();
871 params.user_defined_bullets[index].setText(sum_str);
872 params.temp_bullets[index].setText(sum_str);
873 } else if (token == "\\secnumdepth") {
875 params.secnumdepth = lex.getInteger();
876 } else if (token == "\\tocdepth") {
878 params.tocdepth = lex.getInteger();
879 } else if (token == "\\spacing") {
881 string const tmp = strip(lex.getString());
882 Spacing::Space tmp_space = Spacing::Default;
884 if (tmp == "single") {
885 tmp_space = Spacing::Single;
886 } else if (tmp == "onehalf") {
887 tmp_space = Spacing::Onehalf;
888 } else if (tmp == "double") {
889 tmp_space = Spacing::Double;
890 } else if (tmp == "other") {
892 tmp_space = Spacing::Other;
893 tmp_val = lex.getFloat();
895 lex.printError("Unknown spacing token: '$$Token'");
897 // Small hack so that files written with klyx will be
900 par->params().spacing(Spacing(tmp_space, tmp_val));
902 params.spacing.set(tmp_space, tmp_val);
904 } else if (token == "\\paragraph_spacing") {
906 string const tmp = strip(lex.getString());
907 if (tmp == "single") {
908 par->params().spacing(Spacing(Spacing::Single));
909 } else if (tmp == "onehalf") {
910 par->params().spacing(Spacing(Spacing::Onehalf));
911 } else if (tmp == "double") {
912 par->params().spacing(Spacing(Spacing::Double));
913 } else if (tmp == "other") {
915 par->params().spacing(Spacing(Spacing::Other,
918 lex.printError("Unknown spacing token: '$$Token'");
920 } else if (token == "\\float_placement") {
922 params.float_placement = lex.getString();
923 } else if (token == "\\family") {
925 font.setLyXFamily(lex.getString());
926 } else if (token == "\\series") {
928 font.setLyXSeries(lex.getString());
929 } else if (token == "\\shape") {
931 font.setLyXShape(lex.getString());
932 } else if (token == "\\size") {
934 font.setLyXSize(lex.getString());
935 #ifndef NO_COMPABILITY
936 } else if (token == "\\latex") {
938 string const tok = lex.getString();
939 if (tok == "no_latex") {
941 insertErtContents(par, pos, font);
942 } else if (tok == "latex") {
943 ert_comp.active = true;
944 } else if (tok == "default") {
946 insertErtContents(par, pos, font);
948 lex.printError("Unknown LaTeX font flag "
952 } else if (token == "\\lang") {
954 string const tok = lex.getString();
955 Language const * lang = languages.getLanguage(tok);
957 font.setLanguage(lang);
959 font.setLanguage(params.language);
960 lex.printError("Unknown language `$$Token'");
962 } else if (token == "\\numeric") {
964 font.setNumber(font.setLyXMisc(lex.getString()));
965 } else if (token == "\\emph") {
967 font.setEmph(font.setLyXMisc(lex.getString()));
968 } else if (token == "\\bar") {
970 string const tok = lex.getString();
971 // This is dirty, but gone with LyX3. (Asger)
973 font.setUnderbar(LyXFont::ON);
974 else if (tok == "no")
975 font.setUnderbar(LyXFont::OFF);
976 else if (tok == "default")
977 font.setUnderbar(LyXFont::INHERIT);
979 lex.printError("Unknown bar font flag "
981 } else if (token == "\\noun") {
983 font.setNoun(font.setLyXMisc(lex.getString()));
984 } else if (token == "\\color") {
986 font.setLyXColor(lex.getString());
987 } else if (token == "\\align") {
988 int tmpret = lex.findToken(string_align);
989 if (tmpret == -1) ++tmpret;
990 if (tmpret != LYX_LAYOUT_DEFAULT) { // tmpret != 99 ???
991 int const tmpret2 = int(pow(2.0, tmpret));
992 //lyxerr << "Tmpret2 = " << tmpret2 << endl;
993 par->params().align(LyXAlignment(tmpret2));
995 } else if (token == "\\added_space_top") {
997 par->params().spaceTop(VSpace(lex.getString()));
998 } else if (token == "\\added_space_bottom") {
1000 par->params().spaceBottom(VSpace(lex.getString()));
1001 #ifndef NO_COMPABILITY
1002 #ifndef NO_PEXTRA_REALLY
1003 } else if (token == "\\pextra_type") {
1005 par->params().pextraType(lex.getInteger());
1006 } else if (token == "\\pextra_width") {
1008 par->params().pextraWidth(lex.getString());
1009 } else if (token == "\\pextra_widthp") {
1011 par->params().pextraWidthp(lex.getString());
1012 } else if (token == "\\pextra_alignment") {
1014 par->params().pextraAlignment(lex.getInteger());
1015 } else if (token == "\\pextra_hfill") {
1017 par->params().pextraHfill(lex.getInteger());
1018 } else if (token == "\\pextra_start_minipage") {
1020 par->params().pextraStartMinipage(lex.getInteger());
1023 } else if (token == "\\labelwidthstring") {
1025 par->params().labelWidthString(lex.getString());
1026 // do not delete this token, it is still needed!
1027 } else if (token == "\\end_inset") {
1028 lyxerr << "Solitary \\end_inset. Missing \\begin_inset?.\n"
1029 << "Last inset read was: " << last_inset_read
1031 // Simply ignore this. The insets do not have
1033 // But insets should read it, it is a part of
1034 // the inset isn't it? Lgb.
1035 } else if (token == "\\begin_inset") {
1036 #ifndef NO_COMPABILITY
1037 insertErtContents(par, pos, font, false);
1038 ert_stack.push(ert_comp);
1039 ert_comp = ErtComp();
1041 readInset(lex, par, pos, font);
1042 #ifndef NO_COMPABILITY
1043 ert_comp = ert_stack.top();
1045 insertErtContents(par, pos, font);
1047 } else if (token == "\\SpecialChar") {
1048 LyXLayout const & layout =
1049 textclasslist.Style(params.textclass,
1052 // Insets don't make sense in a free-spacing context! ---Kayvan
1053 if (layout.free_spacing) {
1056 string next_token = lex.getString();
1057 if (next_token == "\\-") {
1058 par->insertChar(pos, '-', font);
1059 } else if (next_token == "\\protected_separator"
1060 || next_token == "~") {
1061 par->insertChar(pos, ' ', font);
1063 lex.printError("Token `$$Token' "
1065 "paragraph layout!");
1070 Inset * inset = new InsetSpecialChar;
1071 inset->read(this, lex);
1072 par->insertInset(pos, inset, font);
1075 } else if (token == "\\newline") {
1076 #ifndef NO_COMPABILITY
1077 if (!ert_comp.in_tabular && ert_comp.active) {
1078 ert_comp.contents += char(Paragraph::META_NEWLINE);
1080 // Since we cannot know it this is only a regular
1081 // newline or a tabular cell delimter we have to
1082 // handle the ERT here.
1083 insertErtContents(par, pos, font, false);
1085 par->insertChar(pos, Paragraph::META_NEWLINE, font);
1089 par->insertChar(pos, Paragraph::META_NEWLINE, font);
1092 } else if (token == "\\LyXTable") {
1093 #ifndef NO_COMPABILITY
1094 ert_comp.in_tabular = true;
1096 Inset * inset = new InsetTabular(*this);
1097 inset->read(this, lex);
1098 par->insertInset(pos, inset, font);
1100 } else if (token == "\\hfill") {
1101 par->insertChar(pos, Paragraph::META_HFILL, font);
1103 } else if (token == "\\protected_separator") { // obsolete
1104 // This is a backward compability thingie. (Lgb)
1105 // Remove it later some time...introduced with fileformat
1107 LyXLayout const & layout =
1108 textclasslist.Style(params.textclass,
1111 if (layout.free_spacing) {
1112 par->insertChar(pos, ' ', font);
1114 Inset * inset = new InsetSpecialChar(InsetSpecialChar::PROTECTED_SEPARATOR);
1115 par->insertInset(pos, inset, font);
1118 } else if (token == "\\bibitem") { // ale970302
1120 InsetCommandParams p("bibitem", "dummy");
1121 par->bibkey = new InsetBibKey(p);
1123 par->bibkey->read(this, lex);
1124 } else if (token == "\\backslash") {
1125 #ifndef NO_COMPABILITY
1126 if (ert_comp.active) {
1127 ert_comp.contents += "\\";
1130 par->insertChar(pos, '\\', font);
1132 #ifndef NO_COMPABILITY
1135 } else if (token == "\\the_end") {
1136 #ifndef NO_COMPABILITY
1137 // If we still have some ert active here we have to insert
1138 // it so we don't loose it. (Lgb)
1139 insertErtContents(par, pos, font);
1141 the_end_read = true;
1142 #ifndef NO_COMPABILITY
1143 #ifndef NO_PEXTRA_REALLY
1144 minipar = parBeforeMinipage = 0;
1148 #ifndef NO_COMPABILITY
1149 if (ert_comp.active) {
1150 ert_comp.contents += token;
1153 // This should be insurance for the future: (Asger)
1154 lex.printError("Unknown token `$$Token'. "
1155 "Inserting as text.");
1156 string::const_iterator cit = token.begin();
1157 string::const_iterator end = token.end();
1158 for (; cit != end; ++cit) {
1159 par->insertChar(pos, (*cit), font);
1162 #ifndef NO_COMPABILITY
1167 #ifndef NO_COMPABILITY
1168 #ifndef NO_PEXTRA_REALLY
1169 // I wonder if we could use this blanket fix for all the
1170 // checkminipage cases...
1171 if (par && par->size()) {
1172 // It is possible that this will check to often,
1173 // but that should not be an correctness issue.
1174 // Only a speed issue.
1175 checkminipage = true;
1178 // now check if we have a minipage paragraph as at this
1179 // point we already read all the necessary data!
1180 // this cannot be done in layout because there we did
1181 // not read yet the paragraph PEXTRA-params (Jug)
1183 // BEGIN pextra_minipage compability
1184 // This should be removed in 1.3.x (Lgb)
1186 // This compability code is not perfect. In a couple
1187 // of rand cases it fails. When the minipage par is
1188 // the first par in the document, and when there are
1189 // none or only one regular paragraphs after the
1190 // minipage. Currently I am not investing any effort
1191 // in fixing those cases.
1193 //lyxerr << "Call depth: " << call_depth << endl;
1194 if (checkminipage && (call_depth == 1)) {
1195 checkminipage = false;
1196 if (minipar && (minipar != par) &&
1197 (par->params().pextraType()==Paragraph::PEXTRA_MINIPAGE))
1199 lyxerr << "minipages in a row" << endl;
1200 if (par->params().pextraStartMinipage()) {
1201 lyxerr << "start new minipage" << endl;
1202 // minipages in a row
1203 par->previous()->next(0);
1206 Paragraph * tmp = minipar;
1208 tmp->params().pextraType(0);
1209 tmp->params().pextraWidth(string());
1210 tmp->params().pextraWidthp(string());
1211 tmp->params().pextraAlignment(0);
1212 tmp->params().pextraHfill(false);
1213 tmp->params().pextraStartMinipage(false);
1216 // create a new paragraph to insert the
1217 // minipages in the following case
1218 if (par->params().pextraStartMinipage() &&
1219 !par->params().pextraHfill())
1221 Paragraph * p = new Paragraph;
1223 p->previous(parBeforeMinipage);
1224 parBeforeMinipage->next(p);
1226 p->params().depth(parBeforeMinipage->params().depth());
1227 parBeforeMinipage = p;
1229 InsetMinipage * mini = new InsetMinipage;
1230 mini->pos(static_cast<InsetMinipage::Position>(par->params().pextraAlignment()));
1231 mini->width(par->params().pextraWidth());
1232 if (!par->params().pextraWidthp().empty()) {
1233 lyxerr << "WP:" << mini->width() << endl;
1234 mini->width(tostr(par->params().pextraWidthp())+"%");
1236 mini->inset.paragraph(par);
1237 // Insert the minipage last in the
1238 // previous paragraph.
1239 if (par->params().pextraHfill()) {
1240 parBeforeMinipage->insertChar
1241 (parBeforeMinipage->size(), Paragraph::META_HFILL);
1243 parBeforeMinipage->insertInset
1244 (parBeforeMinipage->size(), mini);
1248 lyxerr << "new minipage par" << endl;
1249 //nothing to do just continue reading
1252 } else if (minipar && (minipar != par)) {
1253 lyxerr << "last minipage par read" << endl;
1254 // The last paragraph read was not part of a
1255 // minipage but the par linked list is...
1256 // So we need to remove the last par from the
1258 if (par->previous())
1259 par->previous()->next(0);
1260 par->previous(parBeforeMinipage);
1261 parBeforeMinipage->next(par);
1262 Paragraph * tmp = minipar;
1264 tmp->params().pextraType(0);
1265 tmp->params().pextraWidth(string());
1266 tmp->params().pextraWidthp(string());
1267 tmp->params().pextraAlignment(0);
1268 tmp->params().pextraHfill(false);
1269 tmp->params().pextraStartMinipage(false);
1272 depth = parBeforeMinipage->params().depth();
1273 minipar = parBeforeMinipage = 0;
1274 } else if (!minipar &&
1275 (par->params().pextraType() == Paragraph::PEXTRA_MINIPAGE))
1277 // par is the first paragraph in a minipage
1278 lyxerr << "begin minipage" << endl;
1279 // To minimize problems for
1280 // the users we will insert
1281 // the first minipage in
1282 // a sequence of minipages
1283 // in its own paragraph.
1284 Paragraph * p = new Paragraph;
1286 p->previous(par->previous());
1288 p->params().depth(depth);
1289 par->params().depth(0);
1291 if (par->previous())
1292 par->previous()->next(p);
1294 parBeforeMinipage = p;
1296 if (!first_par || (first_par == par))
1299 InsetMinipage * mini = new InsetMinipage;
1300 mini->pos(static_cast<InsetMinipage::Position>(minipar->params().pextraAlignment()));
1301 mini->width(minipar->params().pextraWidth());
1302 if (!par->params().pextraWidthp().empty()) {
1303 lyxerr << "WP:" << mini->width() << endl;
1304 mini->width(tostr(par->params().pextraWidthp())+"%");
1306 mini->inset.paragraph(minipar);
1308 // Insert the minipage last in the
1309 // previous paragraph.
1310 if (minipar->params().pextraHfill()) {
1311 parBeforeMinipage->insertChar
1312 (parBeforeMinipage->size(),Paragraph::META_HFILL);
1314 parBeforeMinipage->insertInset
1315 (parBeforeMinipage->size(), mini);
1318 // End of pextra_minipage compability
1322 return the_end_read;
1325 // needed to insert the selection
1326 void Buffer::insertStringAsLines(Paragraph *& par, Paragraph::size_type & pos,
1327 LyXFont const & fn,string const & str) const
1329 LyXLayout const & layout = textclasslist.Style(params.textclass,
1333 (void)par->checkInsertChar(font);
1334 // insert the string, don't insert doublespace
1335 bool space_inserted = true;
1336 for(string::const_iterator cit = str.begin();
1337 cit != str.end(); ++cit) {
1339 if (par->size() || layout.keepempty) {
1340 par->breakParagraph(params, pos,
1341 layout.isEnvironment());
1344 space_inserted = true;
1348 // do not insert consecutive spaces if !free_spacing
1349 } else if ((*cit == ' ' || *cit == '\t') &&
1350 space_inserted && !layout.free_spacing)
1353 } else if (*cit == '\t') {
1354 if (!layout.free_spacing) {
1355 // tabs are like spaces here
1356 par->insertChar(pos, ' ', font);
1358 space_inserted = true;
1360 const Paragraph::size_type nb = 8 - pos % 8;
1361 for (Paragraph::size_type a = 0;
1363 par->insertChar(pos, ' ', font);
1366 space_inserted = true;
1368 } else if (!IsPrintable(*cit)) {
1369 // Ignore unprintables
1372 // just insert the character
1373 par->insertChar(pos, *cit, font);
1375 space_inserted = (*cit == ' ');
1382 void Buffer::readInset(LyXLex & lex, Paragraph *& par,
1383 int & pos, LyXFont & font)
1385 // consistency check
1386 if (lex.getString() != "\\begin_inset") {
1387 lyxerr << "Buffer::readInset: Consistency check failed."
1394 string const tmptok = lex.getString();
1395 last_inset_read = tmptok;
1397 // test the different insets
1398 if (tmptok == "LatexCommand") {
1399 InsetCommandParams inscmd;
1402 string const cmdName = inscmd.getCmdName();
1404 // This strange command allows LyX to recognize "natbib" style
1405 // citations: citet, citep, Citet etc.
1406 if (compare_no_case(cmdName, "cite", 4) == 0) {
1407 inset = new InsetCitation(inscmd);
1408 } else if (cmdName == "bibitem") {
1409 lex.printError("Wrong place for bibitem");
1410 inset = new InsetBibKey(inscmd);
1411 } else if (cmdName == "BibTeX") {
1412 inset = new InsetBibtex(inscmd);
1413 } else if (cmdName == "index") {
1414 inset = new InsetIndex(inscmd);
1415 } else if (cmdName == "include") {
1416 inset = new InsetInclude(inscmd, *this);
1417 } else if (cmdName == "label") {
1418 inset = new InsetLabel(inscmd);
1419 } else if (cmdName == "url"
1420 || cmdName == "htmlurl") {
1421 inset = new InsetUrl(inscmd);
1422 } else if (cmdName == "ref"
1423 || cmdName == "pageref"
1424 || cmdName == "vref"
1425 || cmdName == "vpageref"
1426 || cmdName == "prettyref") {
1427 if (!inscmd.getOptions().empty()
1428 || !inscmd.getContents().empty()) {
1429 inset = new InsetRef(inscmd, *this);
1431 } else if (cmdName == "tableofcontents") {
1432 inset = new InsetTOC(inscmd);
1433 } else if (cmdName == "listofalgorithms") {
1434 inset = new InsetFloatList("algorithm");
1435 } else if (cmdName == "listoffigures") {
1436 inset = new InsetFloatList("figure");
1437 } else if (cmdName == "listoftables") {
1438 inset = new InsetFloatList("table");
1439 } else if (cmdName == "printindex") {
1440 inset = new InsetPrintIndex(inscmd);
1441 } else if (cmdName == "lyxparent") {
1442 inset = new InsetParent(inscmd, *this);
1445 bool alreadyread = false;
1446 if (tmptok == "Quotes") {
1447 inset = new InsetQuotes;
1448 } else if (tmptok == "External") {
1449 inset = new InsetExternal;
1450 } else if (tmptok == "FormulaMacro") {
1451 inset = new InsetFormulaMacro;
1452 } else if (tmptok == "Formula") {
1453 inset = new InsetFormula;
1454 } else if (tmptok == "Figure") { // Backward compatibility
1455 inset = new InsetFig(100, 100, *this);
1456 //inset = new InsetGraphics;
1457 } else if (tmptok == "Graphics") {
1458 inset = new InsetGraphics;
1459 } else if (tmptok == "Info") {// backwards compatibility
1460 inset = new InsetNote(this,
1461 lex.getLongString("\\end_inset"),
1464 } else if (tmptok == "Note") {
1465 inset = new InsetNote;
1466 } else if (tmptok == "Include") {
1467 InsetCommandParams p( "Include" );
1468 inset = new InsetInclude(p, *this);
1469 } else if (tmptok == "ERT") {
1470 inset = new InsetERT;
1471 } else if (tmptok == "Tabular") {
1472 inset = new InsetTabular(*this);
1473 } else if (tmptok == "Text") {
1474 inset = new InsetText;
1475 } else if (tmptok == "Foot") {
1476 inset = new InsetFoot;
1477 } else if (tmptok == "Marginal") {
1478 inset = new InsetMarginal;
1479 } else if (tmptok == "Minipage") {
1480 inset = new InsetMinipage;
1481 } else if (tmptok == "Float") {
1483 string tmptok = lex.getString();
1484 inset = new InsetFloat(tmptok);
1486 } else if (tmptok == "List") {
1487 inset = new InsetList;
1488 } else if (tmptok == "Theorem") {
1489 inset = new InsetList;
1491 } else if (tmptok == "Caption") {
1492 inset = new InsetCaption;
1493 } else if (tmptok == "FloatList") {
1494 inset = new InsetFloatList;
1497 if (inset && !alreadyread) inset->read(this, lex);
1501 par->insertInset(pos, inset, font);
1507 bool Buffer::readFile(LyXLex & lex, Paragraph * par)
1511 string const token(lex.getString());
1512 if (token == "\\lyxformat") { // the first token _must_ be...
1514 string tmp_format = lex.getString();
1515 //lyxerr << "LyX Format: `" << tmp_format << "'" << endl;
1516 // if present remove ".," from string.
1517 string::size_type dot = tmp_format.find_first_of(".,");
1518 //lyxerr << " dot found at " << dot << endl;
1519 if (dot != string::npos)
1520 tmp_format.erase(dot, 1);
1521 file_format = strToInt(tmp_format);
1522 if (file_format == LYX_FORMAT) {
1524 } else if (file_format > LYX_FORMAT) {
1526 WriteAlert(_("Warning!"),
1527 _("LyX file format is newer that what"),
1528 _("is supported in this LyX version. Expect some problems."));
1530 } else if (file_format < LYX_FORMAT) {
1532 if (file_format < 200) {
1533 WriteAlert(_("ERROR!"),
1534 _("Old LyX file format found. "
1535 "Use LyX 0.10.x to read this!"));
1539 bool the_end = readLyXformat2(lex, par);
1540 params.setPaperStuff();
1541 // the_end was added in 213
1542 if (file_format < 213)
1546 WriteAlert(_("Warning!"),
1547 _("Reading of document is not complete"),
1548 _("Maybe the document is truncated"));
1550 } else { // "\\lyxformat" not found
1551 WriteAlert(_("ERROR!"), _("Not a LyX file!"));
1554 WriteAlert(_("ERROR!"), _("Unable to read file!"));
1559 // Should probably be moved to somewhere else: BufferView? LyXView?
1560 bool Buffer::save() const
1562 // We don't need autosaves in the immediate future. (Asger)
1563 resetAutosaveTimers();
1567 if (lyxrc.make_backup) {
1568 s = fileName() + '~';
1569 if (!lyxrc.backupdir_path.empty())
1570 s = AddName(lyxrc.backupdir_path,
1571 subst(os::slashify_path(s),'/','!'));
1573 // Rename is the wrong way of making a backup,
1574 // this is the correct way.
1575 /* truss cp fil fil2:
1576 lstat("LyXVC3.lyx", 0xEFFFF898) Err#2 ENOENT
1577 stat("LyXVC.lyx", 0xEFFFF688) = 0
1578 open("LyXVC.lyx", O_RDONLY) = 3
1579 open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
1580 fstat(4, 0xEFFFF508) = 0
1581 fstat(3, 0xEFFFF508) = 0
1582 read(3, " # T h i s f i l e w".., 8192) = 5579
1583 write(4, " # T h i s f i l e w".., 5579) = 5579
1584 read(3, 0xEFFFD4A0, 8192) = 0
1587 chmod("LyXVC3.lyx", 0100644) = 0
1588 lseek(0, 0, SEEK_CUR) = 46440
1592 // Should probably have some more error checking here.
1593 // Should be cleaned up in 0.13, at least a bit.
1594 // Doing it this way, also makes the inodes stay the same.
1595 // This is still not a very good solution, in particular we
1596 // might loose the owner of the backup.
1597 FileInfo finfo(fileName());
1598 if (finfo.exist()) {
1599 mode_t fmode = finfo.getMode();
1600 struct utimbuf times = {
1601 finfo.getAccessTime(),
1602 finfo.getModificationTime() };
1604 ifstream ifs(fileName().c_str());
1605 ofstream ofs(s.c_str(), ios::out|ios::trunc);
1610 ::chmod(s.c_str(), fmode);
1612 if (::utime(s.c_str(), ×)) {
1613 lyxerr << "utime error." << endl;
1616 lyxerr << "LyX was not able to make "
1617 "backup copy. Beware." << endl;
1622 if (writeFile(fileName(), false)) {
1624 removeAutosaveFile(fileName());
1626 // Saving failed, so backup is not backup
1627 if (lyxrc.make_backup) {
1628 lyx::rename(s, fileName());
1636 // Returns false if unsuccesful
1637 bool Buffer::writeFile(string const & fname, bool flag) const
1639 // if flag is false writeFile will not create any GUI
1640 // warnings, only cerr.
1641 // Needed for autosave in background or panic save (Matthias 120496)
1643 if (read_only && (fname == filename)) {
1644 // Here we should come with a question if we should
1645 // perform the write anyway.
1647 lyxerr << _("Error! Document is read-only: ")
1650 WriteAlert(_("Error! Document is read-only: "),
1655 FileInfo finfo(fname);
1656 if (finfo.exist() && !finfo.writable()) {
1657 // Here we should come with a question if we should
1658 // try to do the save anyway. (i.e. do a chmod first)
1660 lyxerr << _("Error! Cannot write file: ")
1663 WriteFSAlert(_("Error! Cannot write file: "),
1668 ofstream ofs(fname.c_str());
1671 lyxerr << _("Error! Cannot open file: ")
1674 WriteFSAlert(_("Error! Cannot open file: "),
1680 // Use the standard "C" locale for file output.
1681 ofs.imbue(std::locale::classic());
1684 // The top of the file should not be written by params.
1686 // write out a comment in the top of the file
1687 ofs << '#' << lyx_docversion
1688 << " created this file. For more info see http://www.lyx.org/\n"
1689 << "\\lyxformat " << LYX_FORMAT << "\n";
1691 // now write out the buffer paramters.
1692 params.writeFile(ofs);
1694 Paragraph::depth_type depth = 0;
1696 // this will write out all the paragraphs
1697 // using recursive descent.
1698 paragraph->writeFile(this, ofs, params, depth);
1700 // Write marker that shows file is complete
1701 ofs << "\n\\the_end" << endl;
1705 // how to check if close went ok?
1706 // Following is an attempt... (BE 20001011)
1708 // good() returns false if any error occured, including some
1709 // formatting error.
1710 // bad() returns true if something bad happened in the buffer,
1711 // which should include file system full errors.
1718 lyxerr << "Buffer::writeFile: BAD ERROR!" << endl;
1720 lyxerr << "Buffer::writeFile: NOT SO BAD ERROR!"
1730 string const Buffer::asciiParagraph(Paragraph const * par,
1731 unsigned int linelen) const
1733 ostringstream buffer;
1734 Paragraph::depth_type depth = 0;
1736 Paragraph::depth_type ltype_depth = 0;
1737 string::size_type currlinelen = 0;
1738 bool ref_printed = false;
1742 if (!par->previous()) {
1743 // begins or ends a deeper area ?
1744 if (depth != par->params().depth()) {
1745 if (par->params().depth() > depth) {
1746 while (par->params().depth() > depth) {
1750 while (par->params().depth() < depth) {
1756 // First write the layout
1757 string const tmp = textclasslist.NameOfLayout(params.textclass, par->layout);
1758 if (tmp == "Itemize") {
1760 ltype_depth = depth + 1;
1761 } else if (tmp == "Enumerate") {
1763 ltype_depth = depth + 1;
1764 } else if (contains(tmp, "ection")) {
1766 ltype_depth = depth + 1;
1767 } else if (contains(tmp, "aragraph")) {
1769 ltype_depth = depth + 1;
1770 } else if (tmp == "Description") {
1772 ltype_depth = depth + 1;
1773 } else if (tmp == "Abstract") {
1776 } else if (tmp == "Bibliography") {
1784 /* maybe some vertical spaces */
1786 /* the labelwidthstring used in lists */
1790 /* some pagebreaks? */
1794 /* what about the alignment */
1796 lyxerr << "Should this ever happen?" << endl;
1799 for (Paragraph::size_type i = 0; i < par->size(); ++i) {
1800 if (!i && !noparbreak) {
1803 for (Paragraph::depth_type j = 0; j < depth; ++j)
1805 currlinelen = depth * 2;
1808 case 4: // (Sub)Paragraph
1809 case 5: // Description
1813 buffer << "Abstract\n\n";
1815 buffer << "Abstract: ";
1817 case 7: // Bibliography
1820 buffer << "References\n\n";
1822 buffer << "References: ";
1827 buffer << par->params().labelString() << " ";
1830 if (ltype_depth > depth) {
1831 for (Paragraph::depth_type j = ltype_depth - 1;
1834 currlinelen += (ltype_depth-depth)*2;
1838 char c = par->getUChar(params, i);
1842 case Paragraph::META_INSET:
1844 Inset const * inset = par->getInset(i);
1846 if (!inset->ascii(this, buffer)) {
1849 rsplit(buffer.str().c_str(),
1851 currlinelen += s.length();
1853 // to be sure it breaks paragraph
1854 currlinelen += linelen;
1860 case Paragraph::META_NEWLINE:
1863 for (Paragraph::depth_type j = 0;
1867 currlinelen = depth * 2;
1868 if (ltype_depth > depth) {
1869 for (Paragraph::depth_type j = ltype_depth;
1872 currlinelen += (ltype_depth - depth) * 2;
1876 case Paragraph::META_HFILL:
1881 if ((linelen > 0) && (currlinelen > (linelen - 10)) &&
1882 (c == ' ') && ((i + 2) < par->size()))
1885 for (Paragraph::depth_type j = 0;
1888 currlinelen = depth * 2;
1889 if (ltype_depth > depth) {
1890 for (Paragraph::depth_type j = ltype_depth;
1893 currlinelen += (ltype_depth-depth)*2;
1895 } else if (c != '\0') {
1899 lyxerr[Debug::INFO] << "writeAsciiFile: NULL char in structure." << endl;
1903 return buffer.str().c_str();
1907 void Buffer::writeFileAscii(string const & fname, int linelen)
1909 ofstream ofs(fname.c_str());
1911 WriteFSAlert(_("Error: Cannot write file:"), fname);
1914 writeFileAscii(ofs, linelen);
1918 void Buffer::writeFileAscii(ostream & ofs, int linelen)
1920 Paragraph * par = paragraph;
1922 ofs << asciiParagraph(par, linelen);
1930 void Buffer::makeLaTeXFile(string const & fname,
1931 string const & original_path,
1932 bool nice, bool only_body)
1934 lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
1936 niceFile = nice; // this will be used by Insetincludes.
1938 tex_code_break_column = lyxrc.ascii_linelen;
1940 LyXTextClass const & tclass =
1941 textclasslist.TextClass(params.textclass);
1943 ofstream ofs(fname.c_str());
1945 WriteFSAlert(_("Error: Cannot open file: "), fname);
1949 // validate the buffer.
1950 lyxerr[Debug::LATEX] << " Validating buffer..." << endl;
1951 LaTeXFeatures features(params, tclass.numLayouts());
1953 lyxerr[Debug::LATEX] << " Buffer validation done." << endl;
1956 // The starting paragraph of the coming rows is the
1957 // first paragraph of the document. (Asger)
1958 texrow.start(paragraph, 0);
1960 if (!only_body && nice) {
1961 ofs << "%% " << lyx_docversion << " created this file. "
1962 "For more info, see http://www.lyx.org/.\n"
1963 "%% Do not edit unless you really know what "
1968 lyxerr[Debug::INFO] << "lyx header finished" << endl;
1969 // There are a few differences between nice LaTeX and usual files:
1970 // usual is \batchmode and has a
1971 // special input@path to allow the including of figures
1972 // with either \input or \includegraphics (what figinsets do).
1973 // batchmode is not set if there is a tex_code_break_column.
1974 // In this case somebody is interested in the generated LaTeX,
1975 // so this is OK. input@path is set when the actual parameter
1976 // original_path is set. This is done for usual tex-file, but not
1977 // for nice-latex-file. (Matthias 250696)
1980 // code for usual, NOT nice-latex-file
1981 ofs << "\\batchmode\n"; // changed
1982 // from \nonstopmode
1985 if (!original_path.empty()) {
1986 ofs << "\\makeatletter\n"
1987 << "\\def\\input@path{{"
1988 << os::external_path(original_path) << "/}}\n"
1989 << "\\makeatother\n";
1995 ofs << "\\documentclass";
1997 ostringstream options; // the document class options.
1999 if (tokenPos(tclass.opt_fontsize(),
2000 '|', params.fontsize) >= 0) {
2001 // only write if existing in list (and not default)
2002 options << params.fontsize << "pt,";
2006 if (!params.use_geometry &&
2007 (params.paperpackage == BufferParams::PACKAGE_NONE)) {
2008 switch (params.papersize) {
2009 case BufferParams::PAPER_A4PAPER:
2010 options << "a4paper,";
2012 case BufferParams::PAPER_USLETTER:
2013 options << "letterpaper,";
2015 case BufferParams::PAPER_A5PAPER:
2016 options << "a5paper,";
2018 case BufferParams::PAPER_B5PAPER:
2019 options << "b5paper,";
2021 case BufferParams::PAPER_EXECUTIVEPAPER:
2022 options << "executivepaper,";
2024 case BufferParams::PAPER_LEGALPAPER:
2025 options << "legalpaper,";
2031 if (params.sides != tclass.sides()) {
2032 switch (params.sides) {
2033 case LyXTextClass::OneSide:
2034 options << "oneside,";
2036 case LyXTextClass::TwoSides:
2037 options << "twoside,";
2043 if (params.columns != tclass.columns()) {
2044 if (params.columns == 2)
2045 options << "twocolumn,";
2047 options << "onecolumn,";
2050 if (!params.use_geometry
2051 && params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
2052 options << "landscape,";
2054 // language should be a parameter to \documentclass
2056 ostringstream language_options;
2057 if (params.language->babel() == "hebrew"
2058 && default_language->babel() != "hebrew")
2059 // This seems necessary
2060 features.useLanguage(default_language);
2062 if (lyxrc.language_use_babel ||
2063 params.language->lang() != lyxrc.default_language ||
2064 !features.hasLanguages()) {
2066 language_options << features.getLanguages();
2067 language_options << params.language->babel();
2068 if (lyxrc.language_global_options)
2069 options << language_options.str() << ',';
2072 // the user-defined options
2073 if (!params.options.empty()) {
2074 options << params.options << ',';
2077 string strOptions(options.str().c_str());
2078 if (!strOptions.empty()){
2079 strOptions = strip(strOptions, ',');
2080 ofs << '[' << strOptions << ']';
2084 << textclasslist.LatexnameOfClass(params.textclass)
2087 // end of \documentclass defs
2089 // font selection must be done before loading fontenc.sty
2090 // The ae package is not needed when using OT1 font encoding.
2091 if (params.fonts != "default" &&
2092 (params.fonts != "ae" || lyxrc.fontenc != "default")) {
2093 ofs << "\\usepackage{" << params.fonts << "}\n";
2095 if (params.fonts == "ae") {
2096 ofs << "\\usepackage{aecompl}\n";
2100 // this one is not per buffer
2101 if (lyxrc.fontenc != "default") {
2102 ofs << "\\usepackage[" << lyxrc.fontenc
2107 if (params.inputenc == "auto") {
2108 string const doc_encoding =
2109 params.language->encoding()->LatexName();
2111 // Create a list with all the input encodings used
2113 set<string> encodings = features.getEncodingSet(doc_encoding);
2115 ofs << "\\usepackage[";
2116 std::copy(encodings.begin(), encodings.end(),
2117 std::ostream_iterator<string>(ofs, ","));
2118 ofs << doc_encoding << "]{inputenc}\n";
2120 } else if (params.inputenc != "default") {
2121 ofs << "\\usepackage[" << params.inputenc
2126 // At the very beginning the text parameters.
2127 if (params.paperpackage != BufferParams::PACKAGE_NONE) {
2128 switch (params.paperpackage) {
2129 case BufferParams::PACKAGE_A4:
2130 ofs << "\\usepackage{a4}\n";
2133 case BufferParams::PACKAGE_A4WIDE:
2134 ofs << "\\usepackage{a4wide}\n";
2137 case BufferParams::PACKAGE_WIDEMARGINSA4:
2138 ofs << "\\usepackage[widemargins]{a4}\n";
2143 if (params.use_geometry) {
2144 ofs << "\\usepackage{geometry}\n";
2146 ofs << "\\geometry{verbose";
2147 if (params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
2148 ofs << ",landscape";
2149 switch (params.papersize2) {
2150 case BufferParams::VM_PAPER_CUSTOM:
2151 if (!params.paperwidth.empty())
2152 ofs << ",paperwidth="
2153 << params.paperwidth;
2154 if (!params.paperheight.empty())
2155 ofs << ",paperheight="
2156 << params.paperheight;
2158 case BufferParams::VM_PAPER_USLETTER:
2159 ofs << ",letterpaper";
2161 case BufferParams::VM_PAPER_USLEGAL:
2162 ofs << ",legalpaper";
2164 case BufferParams::VM_PAPER_USEXECUTIVE:
2165 ofs << ",executivepaper";
2167 case BufferParams::VM_PAPER_A3:
2170 case BufferParams::VM_PAPER_A4:
2173 case BufferParams::VM_PAPER_A5:
2176 case BufferParams::VM_PAPER_B3:
2179 case BufferParams::VM_PAPER_B4:
2182 case BufferParams::VM_PAPER_B5:
2186 // default papersize ie BufferParams::VM_PAPER_DEFAULT
2187 switch (lyxrc.default_papersize) {
2188 case BufferParams::PAPER_DEFAULT: // keep compiler happy
2189 case BufferParams::PAPER_USLETTER:
2190 ofs << ",letterpaper";
2192 case BufferParams::PAPER_LEGALPAPER:
2193 ofs << ",legalpaper";
2195 case BufferParams::PAPER_EXECUTIVEPAPER:
2196 ofs << ",executivepaper";
2198 case BufferParams::PAPER_A3PAPER:
2201 case BufferParams::PAPER_A4PAPER:
2204 case BufferParams::PAPER_A5PAPER:
2207 case BufferParams::PAPER_B5PAPER:
2212 if (!params.topmargin.empty())
2213 ofs << ",tmargin=" << params.topmargin;
2214 if (!params.bottommargin.empty())
2215 ofs << ",bmargin=" << params.bottommargin;
2216 if (!params.leftmargin.empty())
2217 ofs << ",lmargin=" << params.leftmargin;
2218 if (!params.rightmargin.empty())
2219 ofs << ",rmargin=" << params.rightmargin;
2220 if (!params.headheight.empty())
2221 ofs << ",headheight=" << params.headheight;
2222 if (!params.headsep.empty())
2223 ofs << ",headsep=" << params.headsep;
2224 if (!params.footskip.empty())
2225 ofs << ",footskip=" << params.footskip;
2230 if (features.isRequired("amsstyle")
2231 && !tclass.provides(LyXTextClass::amsmath)) {
2232 ofs << "\\usepackage{amsmath}\n";
2236 if (tokenPos(tclass.opt_pagestyle(),
2237 '|', params.pagestyle) >= 0) {
2238 if (params.pagestyle == "fancy") {
2239 ofs << "\\usepackage{fancyhdr}\n";
2242 ofs << "\\pagestyle{" << params.pagestyle << "}\n";
2246 if (params.secnumdepth != tclass.secnumdepth()) {
2247 ofs << "\\setcounter{secnumdepth}{"
2248 << params.secnumdepth
2252 if (params.tocdepth != tclass.tocdepth()) {
2253 ofs << "\\setcounter{tocdepth}{"
2259 if (params.paragraph_separation) {
2260 switch (params.defskip.kind()) {
2261 case VSpace::SMALLSKIP:
2262 ofs << "\\setlength\\parskip{\\smallskipamount}\n";
2264 case VSpace::MEDSKIP:
2265 ofs << "\\setlength\\parskip{\\medskipamount}\n";
2267 case VSpace::BIGSKIP:
2268 ofs << "\\setlength\\parskip{\\bigskipamount}\n";
2270 case VSpace::LENGTH:
2271 ofs << "\\setlength\\parskip{"
2272 << params.defskip.length().asLatexString()
2275 default: // should never happen // Then delete it.
2276 ofs << "\\setlength\\parskip{\\medskipamount}\n";
2281 ofs << "\\setlength\\parindent{0pt}\n";
2285 // Now insert the LyX specific LaTeX commands...
2287 // The optional packages;
2288 string preamble(features.getPackages());
2290 // this might be useful...
2291 preamble += "\n\\makeatletter\n";
2293 // Some macros LyX will need
2294 string tmppreamble(features.getMacros());
2296 if (!tmppreamble.empty()) {
2297 preamble += "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2298 "LyX specific LaTeX commands.\n"
2299 + tmppreamble + '\n';
2302 // the text class specific preamble
2303 tmppreamble = features.getTClassPreamble();
2304 if (!tmppreamble.empty()) {
2305 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2306 "Textclass specific LaTeX commands.\n"
2307 + tmppreamble + '\n';
2310 /* the user-defined preamble */
2311 if (!params.preamble.empty()) {
2312 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2313 "User specified LaTeX commands.\n"
2314 + params.preamble + '\n';
2317 preamble += "\\makeatother\n";
2319 // Itemize bullet settings need to be last in case the user
2320 // defines their own bullets that use a package included
2321 // in the user-defined preamble -- ARRae
2322 // Actually it has to be done much later than that
2323 // since some packages like frenchb make modifications
2324 // at \begin{document} time -- JMarc
2326 for (int i = 0; i < 4; ++i) {
2327 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
2328 if (bullets_def.empty())
2329 bullets_def="\\AtBeginDocument{\n";
2330 bullets_def += " \\renewcommand{\\labelitemi";
2332 // `i' is one less than the item to modify
2339 bullets_def += "ii";
2345 bullets_def += "}{" +
2346 params.user_defined_bullets[i].getText()
2351 if (!bullets_def.empty())
2352 preamble += bullets_def + "}\n\n";
2354 for (int j = countChar(preamble, '\n'); j-- ;) {
2360 // We try to load babel late, in case it interferes
2361 // with other packages.
2363 string tmp = lyxrc.language_package;
2364 if (!lyxrc.language_global_options
2365 && tmp == "\\usepackage{babel}")
2366 tmp = string("\\usepackage[") +
2367 language_options.str().c_str() +
2374 ofs << "\\begin{document}\n";
2377 lyxerr[Debug::INFO] << "preamble finished, now the body." << endl;
2379 if (!lyxrc.language_auto_begin) {
2380 ofs << subst(lyxrc.language_command_begin, "$$lang",
2381 params.language->babel())
2386 latexParagraphs(ofs, paragraph, 0, texrow);
2388 // add this just in case after all the paragraphs
2392 if (!lyxrc.language_auto_end) {
2393 ofs << subst(lyxrc.language_command_end, "$$lang",
2394 params.language->babel())
2400 ofs << "\\end{document}\n";
2403 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
2405 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
2409 // Just to be sure. (Asger)
2412 // tex_code_break_column's value is used to decide
2413 // if we are in batchmode or not (within mathed_write()
2414 // in math_write.C) so we must set it to a non-zero
2415 // value when we leave otherwise we save incorrect .lyx files.
2416 tex_code_break_column = lyxrc.ascii_linelen;
2420 lyxerr << "File was not closed properly." << endl;
2423 lyxerr[Debug::INFO] << "Finished making latex file." << endl;
2428 // LaTeX all paragraphs from par to endpar, if endpar == 0 then to the end
2430 void Buffer::latexParagraphs(ostream & ofs, Paragraph * par,
2431 Paragraph * endpar, TexRow & texrow) const
2433 bool was_title = false;
2434 bool already_title = false;
2437 while (par != endpar) {
2438 LyXLayout const & layout =
2439 textclasslist.Style(params.textclass,
2442 if (layout.intitle) {
2443 if (already_title) {
2444 lyxerr <<"Error in latexParagraphs: You"
2445 " should not mix title layouts"
2446 " with normal ones." << endl;
2449 } else if (was_title && !already_title) {
2450 ofs << "\\maketitle\n";
2452 already_title = true;
2456 if (layout.isEnvironment()) {
2457 par = par->TeXEnvironment(this, params, ofs, texrow);
2459 par = par->TeXOnePar(this, params, ofs, texrow, false);
2462 // It might be that we only have a title in this document
2463 if (was_title && !already_title) {
2464 ofs << "\\maketitle\n";
2470 bool Buffer::isLatex() const
2472 return textclasslist.TextClass(params.textclass).outputType() == LATEX;
2476 bool Buffer::isLinuxDoc() const
2478 return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC;
2482 bool Buffer::isLiterate() const
2484 return textclasslist.TextClass(params.textclass).outputType() == LITERATE;
2488 bool Buffer::isDocBook() const
2490 return textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2494 bool Buffer::isSGML() const
2496 return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC ||
2497 textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2501 void Buffer::sgmlOpenTag(ostream & os, Paragraph::depth_type depth,
2502 string const & latexname) const
2504 if (!latexname.empty() && latexname != "!-- --")
2505 //os << "<!-- " << depth << " -->" << "<" << latexname << ">";
2506 os << string(depth, ' ') << "<" << latexname << ">\n";
2510 void Buffer::sgmlCloseTag(ostream & os, Paragraph::depth_type depth,
2511 string const & latexname) const
2513 if (!latexname.empty() && latexname != "!-- --")
2514 //os << "<!-- " << depth << " -->" << "</" << latexname << ">\n";
2515 os << string(depth, ' ') << "</" << latexname << ">\n";
2519 void Buffer::makeLinuxDocFile(string const & fname, bool nice, bool body_only)
2521 ofstream ofs(fname.c_str());
2524 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2528 niceFile = nice; // this will be used by included files.
2530 LyXTextClass const & tclass =
2531 textclasslist.TextClass(params.textclass);
2533 LaTeXFeatures features(params, tclass.numLayouts());
2538 string top_element = textclasslist.LatexnameOfClass(params.textclass);
2541 ofs << "<!doctype linuxdoc system";
2543 string preamble = params.preamble;
2544 preamble += features.getIncludedFiles(fname);
2545 preamble += features.getLyXSGMLEntities();
2547 if (!preamble.empty()) {
2548 ofs << " [ " << preamble << " ]";
2552 if (params.options.empty())
2553 sgmlOpenTag(ofs, 0, top_element);
2555 string top = top_element;
2557 top += params.options;
2558 sgmlOpenTag(ofs, 0, top);
2562 ofs << "<!-- " << lyx_docversion
2563 << " created this file. For more info see http://www.lyx.org/"
2566 Paragraph::depth_type depth = 0; // paragraph depth
2567 Paragraph * par = paragraph;
2569 vector<string> environment_stack(5);
2572 LyXLayout const & style =
2573 textclasslist.Style(params.textclass,
2576 // treat <toc> as a special case for compatibility with old code
2577 if (par->getChar(0) == Paragraph::META_INSET) {
2578 Inset * inset = par->getInset(0);
2579 Inset::Code lyx_code = inset->lyxCode();
2580 if (lyx_code == Inset::TOC_CODE){
2581 string const temp = "toc";
2582 sgmlOpenTag(ofs, depth, temp);
2589 // environment tag closing
2590 for (; depth > par->params().depth(); --depth) {
2591 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2592 environment_stack[depth].erase();
2595 // write opening SGML tags
2596 switch (style.latextype) {
2597 case LATEX_PARAGRAPH:
2598 if (depth == par->params().depth()
2599 && !environment_stack[depth].empty()) {
2600 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2601 environment_stack[depth].erase();
2607 sgmlOpenTag(ofs, depth, style.latexname());
2613 _("Error : Wrong depth for"
2614 " LatexType Command.\n"));
2616 if (!environment_stack[depth].empty()){
2617 sgmlCloseTag(ofs, depth,
2618 environment_stack[depth]);
2622 environment_stack[depth].erase();
2623 sgmlOpenTag(ofs, depth, style.latexname());
2626 case LATEX_ENVIRONMENT:
2627 case LATEX_ITEM_ENVIRONMENT:
2628 if (depth == par->params().depth()
2629 && environment_stack[depth] != style.latexname()) {
2630 sgmlCloseTag(ofs, depth,
2631 environment_stack[depth]);
2632 environment_stack[depth].erase();
2634 if (depth < par->params().depth()) {
2635 depth = par->params().depth();
2636 environment_stack[depth].erase();
2638 if (environment_stack[depth] != style.latexname()) {
2640 sgmlOpenTag(ofs, depth, "p");
2642 sgmlOpenTag(ofs, depth, style.latexname());
2644 if (environment_stack.size() == depth + 1)
2645 environment_stack.push_back("!-- --");
2646 environment_stack[depth] = style.latexname();
2649 if (style.latexparam() == "CDATA")
2652 if (style.latextype == LATEX_ENVIRONMENT) break;
2654 if (style.labeltype == LABEL_MANUAL)
2659 sgmlOpenTag(ofs, depth + 1, item_name);
2662 sgmlOpenTag(ofs, depth, style.latexname());
2666 simpleLinuxDocOnePar(ofs, par, depth);
2671 // write closing SGML tags
2672 switch (style.latextype) {
2675 case LATEX_ENVIRONMENT:
2676 case LATEX_ITEM_ENVIRONMENT:
2677 if (style.latexparam() == "CDATA")
2681 sgmlCloseTag(ofs, depth, style.latexname());
2687 for (int i=depth; i >= 0; --i)
2688 sgmlCloseTag(ofs, depth, environment_stack[i]);
2692 sgmlCloseTag(ofs, 0, top_element);
2696 // How to check for successful close
2700 // checks, if newcol chars should be put into this line
2701 // writes newline, if necessary.
2704 void sgmlLineBreak(ostream & os, string::size_type & colcount,
2705 string::size_type newcol)
2708 if (colcount > lyxrc.ascii_linelen) {
2710 colcount = newcol; // assume write after this call
2725 string tag_name(PAR_TAG const & pt) {
2727 case NONE: return "!-- --";
2728 case TT: return "tt";
2729 case SF: return "sf";
2730 case BF: return "bf";
2731 case IT: return "it";
2732 case SL: return "sl";
2733 case EM: return "em";
2740 void operator|=(PAR_TAG & p1, PAR_TAG const & p2)
2742 p1 = static_cast<PAR_TAG>(p1 | p2);
2747 void reset(PAR_TAG & p1, PAR_TAG const & p2)
2749 p1 = static_cast<PAR_TAG>( p1 & ~p2);
2755 // Handle internal paragraph parsing -- layout already processed.
2756 void Buffer::simpleLinuxDocOnePar(ostream & os,
2758 Paragraph::depth_type /*depth*/)
2760 LyXLayout const & style = textclasslist.Style(params.textclass,
2762 string::size_type char_line_count = 5; // Heuristic choice ;-)
2764 // gets paragraph main font
2767 if (style.labeltype == LABEL_MANUAL) {
2768 font_old = style.labelfont;
2771 font_old = style.font;
2775 LyXFont::FONT_FAMILY family_type = LyXFont::ROMAN_FAMILY;
2776 LyXFont::FONT_SERIES series_type = LyXFont::MEDIUM_SERIES;
2777 LyXFont::FONT_SHAPE shape_type = LyXFont::UP_SHAPE;
2780 stack<PAR_TAG> tag_state;
2781 // parsing main loop
2782 for (Paragraph::size_type i = 0; i < par->size(); ++i) {
2784 PAR_TAG tag_close = NONE;
2785 list < PAR_TAG > tag_open;
2787 LyXFont const font = par->getFont(params, i);
2789 if (font_old.family() != font.family()) {
2790 switch (family_type) {
2791 case LyXFont::SANS_FAMILY:
2794 case LyXFont::TYPEWRITER_FAMILY:
2801 family_type = font.family();
2803 switch (family_type) {
2804 case LyXFont::SANS_FAMILY:
2805 tag_open.push_back(SF);
2807 case LyXFont::TYPEWRITER_FAMILY:
2808 tag_open.push_back(TT);
2815 if (font_old.series() != font.series()) {
2816 switch (series_type) {
2817 case LyXFont::BOLD_SERIES:
2824 series_type = font.series();
2826 switch (series_type) {
2827 case LyXFont::BOLD_SERIES:
2828 tag_open.push_back(BF);
2836 if (font_old.shape() != font.shape()) {
2837 switch (shape_type) {
2838 case LyXFont::ITALIC_SHAPE:
2841 case LyXFont::SLANTED_SHAPE:
2848 shape_type = font.shape();
2850 switch (shape_type) {
2851 case LyXFont::ITALIC_SHAPE:
2852 tag_open.push_back(IT);
2854 case LyXFont::SLANTED_SHAPE:
2855 tag_open.push_back(SL);
2862 if (font_old.emph() != font.emph()) {
2863 if (font.emph() == LyXFont::ON) {
2864 tag_open.push_back(EM);
2873 list < PAR_TAG > temp;
2874 while(!tag_state.empty() && tag_close ) {
2875 PAR_TAG k = tag_state.top();
2877 os << "</" << tag_name(k) << ">";
2884 for(list< PAR_TAG >::const_iterator j = temp.begin();
2885 j != temp.end(); ++j) {
2887 os << "<" << tag_name(*j) << ">";
2890 for(list< PAR_TAG >::const_iterator j = tag_open.begin();
2891 j != tag_open.end(); ++j) {
2893 os << "<" << tag_name(*j) << ">";
2896 char c = par->getChar(i);
2898 if (c == Paragraph::META_INSET) {
2899 Inset * inset = par->getInset(i);
2900 inset->linuxdoc(this, os);
2905 if (style.latexparam() == "CDATA") {
2906 // "TeX"-Mode on == > SGML-Mode on.
2912 if (par->sgmlConvertChar(c, sgml_string)
2913 && !style.free_spacing) {
2914 // in freespacing mode, spaces are
2915 // non-breaking characters
2916 if (desc_on) {// if char is ' ' then...
2919 sgmlLineBreak(os, char_line_count, 6);
2923 sgmlLineBreak(os, char_line_count, 1);
2928 char_line_count += sgml_string.length();
2934 while (!tag_state.empty()) {
2935 os << "</" << tag_name(tag_state.top()) << ">";
2939 // resets description flag correctly
2941 // <tag> not closed...
2942 sgmlLineBreak(os, char_line_count, 6);
2948 // Print an error message.
2949 void Buffer::sgmlError(Paragraph * par, int pos,
2950 string const & message) const
2952 // insert an error marker in text
2953 InsetError * new_inset = new InsetError(message);
2954 par->insertInset(pos, new_inset);
2958 void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
2960 ofstream ofs(fname.c_str());
2962 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2966 Paragraph * par = paragraph;
2968 niceFile = nice; // this will be used by Insetincludes.
2970 LyXTextClass const & tclass =
2971 textclasslist.TextClass(params.textclass);
2973 LaTeXFeatures features(params, tclass.numLayouts());
2978 string top_element = textclasslist.LatexnameOfClass(params.textclass);
2981 ofs << "<!DOCTYPE " << top_element
2982 << " PUBLIC \"-//OASIS//DTD DocBook V4.1//EN\"";
2984 string preamble = params.preamble;
2985 preamble += features.getIncludedFiles(fname);
2986 preamble += features.getLyXSGMLEntities();
2988 if (!preamble.empty()) {
2989 ofs << "\n [ " << preamble << " ]";
2994 string top = top_element;
2996 top += params.language->code();
2999 if (!params.options.empty()) {
3001 top += params.options;
3003 sgmlOpenTag(ofs, 0, top);
3005 ofs << "<!-- DocBook file was created by " << lyx_docversion
3006 << "\n See http://www.lyx.org/ for more information -->\n";
3008 vector<string> environment_stack(10);
3009 vector<string> environment_inner(10);
3010 vector<string> command_stack(10);
3012 bool command_flag = false;
3013 Paragraph::depth_type command_depth = 0;
3014 Paragraph::depth_type command_base = 0;
3015 Paragraph::depth_type cmd_depth = 0;
3016 Paragraph::depth_type depth = 0; // paragraph depth
3019 string command_name;
3025 int desc_on = 0; // description mode
3027 LyXLayout const & style =
3028 textclasslist.Style(params.textclass,
3031 // environment tag closing
3032 for (; depth > par->params().depth(); --depth) {
3033 if (environment_inner[depth] != "!-- --") {
3034 item_name = "listitem";
3035 sgmlCloseTag(ofs, command_depth + depth,
3037 if (environment_inner[depth] == "varlistentry")
3038 sgmlCloseTag(ofs, depth+command_depth,
3039 environment_inner[depth]);
3041 sgmlCloseTag(ofs, depth + command_depth,
3042 environment_stack[depth]);
3043 environment_stack[depth].erase();
3044 environment_inner[depth].erase();
3047 if (depth == par->params().depth()
3048 && environment_stack[depth] != style.latexname()
3049 && !environment_stack[depth].empty()) {
3050 if (environment_inner[depth] != "!-- --") {
3051 item_name= "listitem";
3052 sgmlCloseTag(ofs, command_depth+depth,
3054 if (environment_inner[depth] == "varlistentry")
3056 depth + command_depth,
3057 environment_inner[depth]);
3060 sgmlCloseTag(ofs, depth + command_depth,
3061 environment_stack[depth]);
3063 environment_stack[depth].erase();
3064 environment_inner[depth].erase();
3067 // Write opening SGML tags.
3068 switch (style.latextype) {
3069 case LATEX_PARAGRAPH:
3070 sgmlOpenTag(ofs, depth + command_depth,
3077 _("Error : Wrong depth for "
3078 "LatexType Command.\n"));
3080 command_name = style.latexname();
3082 sgmlparam = style.latexparam();
3083 c_params = split(sgmlparam, c_depth,'|');
3085 cmd_depth = lyx::atoi(c_depth);
3088 if (cmd_depth < command_base) {
3089 for (Paragraph::depth_type j = command_depth; j >= command_base; --j)
3090 sgmlCloseTag(ofs, j, command_stack[j]);
3091 command_depth = command_base = cmd_depth;
3092 } else if (cmd_depth <= command_depth) {
3093 for (int j = command_depth; j >= int(cmd_depth); --j)
3094 sgmlCloseTag(ofs, j, command_stack[j]);
3095 command_depth = cmd_depth;
3097 command_depth = cmd_depth;
3099 command_depth = command_base = cmd_depth;
3100 command_flag = true;
3102 if (command_stack.size() == command_depth + 1)
3103 command_stack.push_back(string());
3104 command_stack[command_depth] = command_name;
3106 // treat label as a special case for
3107 // more WYSIWYM handling.
3108 if (par->getChar(0) == Paragraph::META_INSET) {
3109 Inset * inset = par->getInset(0);
3110 Inset::Code lyx_code = inset->lyxCode();
3111 if (lyx_code == Inset::LABEL_CODE){
3112 command_name += " id=\"";
3113 command_name += (static_cast<InsetCommand *>(inset))->getContents();
3114 command_name += "\"";
3119 sgmlOpenTag(ofs, depth + command_depth, command_name);
3120 if (c_params.empty())
3121 item_name = "title";
3123 item_name = c_params;
3124 sgmlOpenTag(ofs, depth + 1 + command_depth, item_name);
3127 case LATEX_ENVIRONMENT:
3128 case LATEX_ITEM_ENVIRONMENT:
3129 if (depth < par->params().depth()) {
3130 depth = par->params().depth();
3131 environment_stack[depth].erase();
3134 if (environment_stack[depth] != style.latexname()) {
3135 if(environment_stack.size() == depth + 1) {
3136 environment_stack.push_back("!-- --");
3137 environment_inner.push_back("!-- --");
3139 environment_stack[depth] = style.latexname();
3140 environment_inner[depth] = "!-- --";
3141 sgmlOpenTag(ofs, depth + command_depth,
3142 environment_stack[depth]);
3144 if (environment_inner[depth] != "!-- --") {
3145 item_name= "listitem";
3147 command_depth + depth,
3149 if (environment_inner[depth] == "varlistentry")
3151 depth + command_depth,
3152 environment_inner[depth]);
3156 if (style.latextype == LATEX_ENVIRONMENT) {
3157 if (!style.latexparam().empty()) {
3158 if(style.latexparam() == "CDATA")
3161 sgmlOpenTag(ofs, depth + command_depth,
3162 style.latexparam());
3167 desc_on = (style.labeltype == LABEL_MANUAL);
3170 environment_inner[depth]= "varlistentry";
3172 environment_inner[depth]= "listitem";
3174 sgmlOpenTag(ofs, depth + 1 + command_depth,
3175 environment_inner[depth]);
3179 sgmlOpenTag(ofs, depth + 1 + command_depth,
3183 sgmlOpenTag(ofs, depth + 1 + command_depth,
3188 sgmlOpenTag(ofs, depth + command_depth,
3193 simpleDocBookOnePar(ofs, par, desc_on, depth+1+command_depth);
3197 // write closing SGML tags
3198 switch (style.latextype) {
3200 if (c_params.empty())
3204 sgmlCloseTag(ofs, depth + command_depth, end_tag);
3206 case LATEX_ENVIRONMENT:
3207 if (!style.latexparam().empty()) {
3208 if(style.latexparam() == "CDATA")
3211 sgmlCloseTag(ofs, depth + command_depth,
3212 style.latexparam());
3215 case LATEX_ITEM_ENVIRONMENT:
3216 if (desc_on == 1) break;
3218 sgmlCloseTag(ofs, depth + 1 + command_depth, end_tag);
3220 case LATEX_PARAGRAPH:
3221 sgmlCloseTag(ofs, depth + command_depth, style.latexname());
3224 sgmlCloseTag(ofs, depth + command_depth, style.latexname());
3230 for (int d = depth; d >= 0; --d) {
3231 if (!environment_stack[depth].empty()) {
3232 if (environment_inner[depth] != "!-- --") {
3233 item_name = "listitem";
3234 sgmlCloseTag(ofs, command_depth + depth,
3236 if (environment_inner[depth] == "varlistentry")
3237 sgmlCloseTag(ofs, depth + command_depth,
3238 environment_inner[depth]);
3241 sgmlCloseTag(ofs, depth + command_depth,
3242 environment_stack[depth]);
3246 for (int j = command_depth; j >= 0 ; --j)
3247 if (!command_stack[j].empty())
3248 sgmlCloseTag(ofs, j, command_stack[j]);
3251 sgmlCloseTag(ofs, 0, top_element);
3254 // How to check for successful close
3258 void Buffer::simpleDocBookOnePar(ostream & os,
3259 Paragraph * par, int & desc_on,
3260 Paragraph::depth_type depth) const
3262 bool emph_flag = false;
3264 LyXLayout const & style = textclasslist.Style(params.textclass,
3267 LyXFont font_old = style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
3269 int char_line_count = depth;
3270 //if (!style.free_spacing)
3271 // os << string(depth,' ');
3273 // parsing main loop
3274 for (Paragraph::size_type i = 0;
3275 i < par->size(); ++i) {
3276 LyXFont font = par->getFont(params, i);
3278 // handle <emphasis> tag
3279 if (font_old.emph() != font.emph()) {
3280 if (font.emph() == LyXFont::ON) {
3284 os << "</emphasis>";
3289 char c = par->getChar(i);
3291 if (c == Paragraph::META_INSET) {
3292 Inset * inset = par->getInset(i);
3293 inset->docbook(this, os);
3296 par->sgmlConvertChar(c, sgml_string);
3298 if (style.pass_thru) {
3300 } else if(style.free_spacing || c != ' ') {
3302 } else if (desc_on ==1) {
3304 os << "\n</term><listitem><para>";
3314 os << "</emphasis>";
3317 // resets description flag correctly
3319 // <term> not closed...
3322 if(style.free_spacing) os << '\n';
3326 // This should be enabled when the Chktex class is implemented. (Asger)
3327 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
3328 // Other flags: -wall -v0 -x
3329 int Buffer::runChktex()
3331 if (!users->text) return 0;
3333 users->owner()->prohibitInput();
3335 // get LaTeX-Filename
3336 string const name = getLatexName();
3337 string path = OnlyPath(filename);
3339 string const org_path = path;
3340 if (lyxrc.use_tempdir || !IsDirWriteable(path)) {
3344 Path p(path); // path to LaTeX file
3345 users->owner()->message(_("Running chktex..."));
3347 // Remove all error insets
3348 bool const removedErrorInsets = users->removeAutoInsets();
3350 // Generate the LaTeX file if neccessary
3351 makeLaTeXFile(name, org_path, false);
3354 Chktex chktex(lyxrc.chktex_command, name, filepath);
3355 int res = chktex.run(terr); // run chktex
3358 WriteAlert(_("chktex did not work!"),
3359 _("Could not run with file:"), name);
3360 } else if (res > 0) {
3361 // Insert all errors as errors boxes
3362 users->insertErrors(terr);
3365 // if we removed error insets before we ran chktex or if we inserted
3366 // error insets after we ran chktex, this must be run:
3367 if (removedErrorInsets || res){
3371 users->owner()->allowInput();
3377 void Buffer::validate(LaTeXFeatures & features) const
3379 Paragraph * par = paragraph;
3380 LyXTextClass const & tclass =
3381 textclasslist.TextClass(params.textclass);
3383 // AMS Style is at document level
3384 if (params.use_amsmath || tclass.provides(LyXTextClass::amsmath))
3385 features.require("amsstyle");
3388 // We don't use "lyxerr.debug" because of speed. (Asger)
3389 if (lyxerr.debugging(Debug::LATEX))
3390 lyxerr << "Paragraph: " << par << endl;
3392 // Now just follow the list of paragraphs and run
3393 // validate on each of them.
3394 par->validate(features);
3396 // and then the next paragraph
3400 // the bullet shapes are buffer level not paragraph level
3401 // so they are tested here
3402 for (int i = 0; i < 4; ++i) {
3403 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
3404 int const font = params.user_defined_bullets[i].getFont();
3406 int const c = params
3407 .user_defined_bullets[i]
3414 features.require("latexsym");
3416 } else if (font == 1) {
3417 features.require("amssymb");
3418 } else if ((font >= 2 && font <= 5)) {
3419 features.require("pifont");
3424 if (lyxerr.debugging(Debug::LATEX)) {
3425 features.showStruct();
3430 // This function should be in Buffer because it's a buffer's property (ale)
3431 string const Buffer::getIncludeonlyList(char delim)
3434 for (inset_iterator it = inset_iterator_begin();
3435 it != inset_iterator_end(); ++it) {
3436 if ((*it)->lyxCode() == Inset::INCLUDE_CODE) {
3437 InsetInclude * insetinc =
3438 static_cast<InsetInclude *>(*it);
3439 if (insetinc->isIncludeOnly()) {
3442 lst += insetinc->getRelFileBaseName();
3446 lyxerr[Debug::INFO] << "Includeonly(" << lst << ')' << endl;
3451 vector<string> const Buffer::getLabelList()
3453 /// if this is a child document and the parent is already loaded
3454 /// Use the parent's list instead [ale990407]
3455 if (!params.parentname.empty()
3456 && bufferlist.exists(params.parentname)) {
3457 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3459 return tmp->getLabelList();
3462 vector<string> label_list;
3463 for (inset_iterator it = inset_iterator_begin();
3464 it != inset_iterator_end(); ++it) {
3465 vector<string> const l = (*it)->getLabelList();
3466 label_list.insert(label_list.end(), l.begin(), l.end());
3472 Buffer::Lists const Buffer::getLists() const
3475 Paragraph * par = paragraph;
3478 std::pair<bool, LyXTextClassList::size_type> const tmp =
3479 textclasslist.NumberOfLayout(params.textclass, "Caption");
3480 bool const found = tmp.first;
3481 LyXTextClassList::size_type const cap = tmp.second;
3484 // This is the prefered way to to this, but boost::tie can break
3487 LyXTextClassList::size_type cap;
3488 boost::tie(found, cap) = textclasslist
3489 .NumberOfLayout(params.textclass, "Caption");
3493 char const labeltype =
3494 textclasslist.Style(params.textclass,
3495 par->getLayout()).labeltype;
3497 if (labeltype >= LABEL_COUNTER_CHAPTER
3498 && labeltype <= LABEL_COUNTER_CHAPTER + params.tocdepth) {
3499 // insert this into the table of contents
3500 SingleList & item = l["TOC"];
3503 textclasslist.TextClass(params.textclass).maxcounter());
3504 item.push_back(TocItem(par, depth, par->asString(this, true)));
3506 // For each paragrph, traverse its insets and look for
3510 Paragraph::inset_iterator it =
3511 par->inset_iterator_begin();
3512 Paragraph::inset_iterator end =
3513 par->inset_iterator_end();
3515 for (; it != end; ++it) {
3516 if ((*it)->lyxCode() == Inset::FLOAT_CODE) {
3518 static_cast<InsetFloat*>(*it);
3520 string const type = il->type();
3522 // Now find the caption in the float...
3523 // We now tranverse the paragraphs of
3525 Paragraph * tmp = il->inset.paragraph();
3527 if (tmp->layout == cap) {
3528 SingleList & item = l[type];
3530 tostr(item.size()+1) + ". " + tmp->asString(this, false);
3531 item.push_back(TocItem(tmp, 0 , str));
3538 lyxerr << "caption not found" << endl;
3547 // This is also a buffer property (ale)
3548 vector<pair<string, string> > const Buffer::getBibkeyList()
3550 /// if this is a child document and the parent is already loaded
3551 /// Use the parent's list instead [ale990412]
3552 if (!params.parentname.empty() && bufferlist.exists(params.parentname)) {
3553 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3555 return tmp->getBibkeyList();
3558 vector<pair<string, string> > keys;
3559 Paragraph * par = paragraph;
3562 keys.push_back(pair<string, string>(par->bibkey->getContents(),
3563 par->asString(this, false)));
3567 // Might be either using bibtex or a child has bibliography
3569 for (inset_iterator it = inset_iterator_begin();
3570 it != inset_iterator_end(); ++it) {
3571 // Search for Bibtex or Include inset
3572 if ((*it)->lyxCode() == Inset::BIBTEX_CODE) {
3573 vector<pair<string,string> > tmp =
3574 static_cast<InsetBibtex*>(*it)->getKeys(this);
3575 keys.insert(keys.end(), tmp.begin(), tmp.end());
3576 } else if ((*it)->lyxCode() == Inset::INCLUDE_CODE) {
3577 vector<pair<string,string> > const tmp =
3578 static_cast<InsetInclude*>(*it)->getKeys();
3579 keys.insert(keys.end(), tmp.begin(), tmp.end());
3588 bool Buffer::isDepClean(string const & name) const
3590 DEPCLEAN * item = dep_clean;
3591 while (item && item->master != name)
3593 if (!item) return true;
3598 void Buffer::markDepClean(string const & name)
3601 dep_clean = new DEPCLEAN;
3602 dep_clean->clean = true;
3603 dep_clean->master = name;
3604 dep_clean->next = 0;
3606 DEPCLEAN * item = dep_clean;
3607 while (item && item->master != name)
3612 item = new DEPCLEAN;
3614 item->master = name;
3621 bool Buffer::dispatch(string const & command)
3623 // Split command string into command and argument
3625 string line = frontStrip(command);
3626 string const arg = strip(frontStrip(split(line, cmd, ' ')));
3628 return dispatch(lyxaction.LookupFunc(cmd), arg);
3632 bool Buffer::dispatch(int action, string const & argument)
3634 bool dispatched = true;
3637 Exporter::Export(this, argument, false);
3647 void Buffer::resizeInsets(BufferView * bv)
3649 /// then remove all LyXText in text-insets
3650 Paragraph * par = paragraph;
3651 for (; par; par = par->next()) {
3652 par->resizeInsetsLyXText(bv);
3657 void Buffer::redraw()
3664 void Buffer::changeLanguage(Language const * from, Language const * to)
3667 ParIterator end = par_iterator_end();
3668 for (ParIterator it = par_iterator_begin(); it != end; ++it)
3669 (*it)->changeLanguage(params, from, to);
3673 bool Buffer::isMultiLingual()
3675 ParIterator end = par_iterator_end();
3676 for (ParIterator it = par_iterator_begin(); it != end; ++it)
3677 if ((*it)->isMultiLingual(params))
3684 Buffer::inset_iterator::inset_iterator(Paragraph * paragraph,
3685 Paragraph::size_type pos)
3688 it = par->InsetIterator(pos);
3689 if (it == par->inset_iterator_end()) {
3696 void Buffer::inset_iterator::setParagraph()
3699 it = par->inset_iterator_begin();
3700 if (it != par->inset_iterator_end())
3705 // We maintain an invariant that whenever par = 0 then it = 0
3709 Inset * Buffer::getInsetFromID(int id_arg) const
3711 for (inset_iterator it = inset_const_iterator_begin();
3712 it != inset_const_iterator_end(); ++it)
3714 if ((*it)->id() == id_arg)
3716 Inset * in = (*it)->getInsetFromID(id_arg);
3724 Paragraph * Buffer::getParFromID(int id) const
3726 if (id < 0) return 0;
3727 Paragraph * par = paragraph;
3729 if (par->id() == id) {
3732 Paragraph * tmp = par->getParFromID(id);
3742 ParIterator Buffer::par_iterator_begin()
3744 return ParIterator(paragraph);
3748 ParIterator Buffer::par_iterator_end()
3750 return ParIterator();