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"
117 using std::make_pair;
125 // all these externs should eventually be removed.
126 extern BufferList bufferlist;
128 extern LyXAction lyxaction;
132 const int LYX_FORMAT = 220;
136 extern int tex_code_break_column;
139 Buffer::Buffer(string const & file, bool ronly)
141 lyxerr[Debug::INFO] << "Buffer::Buffer()" << endl;
143 filepath = OnlyPath(file);
152 if (read_only || (lyxrc.use_tempdir)) {
153 tmppath = CreateBufferTmpDir();
154 } else tmppath.erase();
160 lyxerr[Debug::INFO] << "Buffer::~Buffer()" << endl;
161 // here the buffer should take care that it is
162 // saved properly, before it goes into the void.
164 // make sure that views using this buffer
169 if (!tmppath.empty()) {
170 DestroyBufferTmpDir(tmppath);
173 Paragraph * par = paragraph;
176 tmppar = par->next();
184 string const Buffer::getLatexName(bool no_path) const
186 string name = ChangeExtension(MakeLatexName(filename), ".tex");
188 return OnlyFilename(name);
194 pair<Buffer::LogType, string> const Buffer::getLogName(void) const
196 string const filename = getLatexName(false);
198 if (filename.empty())
199 return make_pair(Buffer::latexlog, string());
201 string path = OnlyPath(filename);
203 if (lyxrc.use_tempdir || (IsDirWriteable(path) < 1))
206 string const fname = AddName(path,
207 OnlyFilename(ChangeExtension(filename,
210 AddName(path, OnlyFilename(
211 ChangeExtension(filename,
212 formats.Extension("literate") + ".out")));
214 // If no Latex log or Build log is newer, show Build log
216 FileInfo const f_fi(fname);
217 FileInfo const b_fi(bname);
220 (!f_fi.exist() || f_fi.getModificationTime() < b_fi.getModificationTime())) {
221 lyxerr[Debug::FILES] << "Log name calculated as : " << bname << endl;
222 return make_pair(Buffer::buildlog, bname);
224 lyxerr[Debug::FILES] << "Log name calculated as : " << fname << endl;
225 return make_pair(Buffer::latexlog, fname);
229 void Buffer::setReadonly(bool flag)
231 if (read_only != flag) {
234 users->owner()->getDialogs()->updateBufferDependent(false);
237 WarnReadonly(filename);
242 bool Buffer::saveParamsAsDefaults() // const
244 string const fname = AddName(AddPath(user_lyxdir, "templates/"),
246 Buffer defaults = Buffer(fname);
248 // Use the current buffer's parameters as default
249 defaults.params = params;
251 // add an empty paragraph. Is this enough?
252 defaults.paragraph = new Paragraph;
254 return defaults.writeFile(defaults.filename, false);
258 /// Update window titles of all users
259 // Should work on a list
260 void Buffer::updateTitles() const
262 if (users) users->owner()->updateWindowTitle();
266 /// Reset autosave timer of all users
267 // Should work on a list
268 void Buffer::resetAutosaveTimers() const
270 if (users) users->owner()->resetAutosaveTimer();
274 void Buffer::setFileName(string const & newfile)
276 filename = MakeAbsPath(newfile);
277 filepath = OnlyPath(filename);
278 setReadonly(IsFileWriteable(filename) == 0);
283 // We'll remove this later. (Lgb)
286 string last_inset_read;
290 ErtComp() : active(false), in_tabular(false) {
297 std::stack<ErtComp> ert_stack;
306 // candidate for move to BufferView
307 // (at least some parts in the beginning of the func)
310 // changed to be public and have one parameter
311 // if par = 0 normal behavior
312 // else insert behavior
313 // Returns false if "\the_end" is not read for formats >= 2.13. (Asger)
314 bool Buffer::readLyXformat2(LyXLex & lex, Paragraph * par)
318 ert_comp.contents.erase();
319 ert_comp.active = false;
320 ert_comp.in_tabular = false;
324 Paragraph::depth_type depth = 0;
325 bool the_end_read = false;
327 Paragraph * first_par = 0;
328 LyXFont font(LyXFont::ALL_INHERIT, params.language);
329 if (file_format < 216 && params.language->lang() == "hebrew")
330 font.setLanguage(default_language);
335 // We are inserting into an existing document
336 users->text->breakParagraph(users);
337 first_par = users->text->firstParagraph();
340 // We don't want to adopt the parameters from the
341 // document we insert, so we skip until the text begins:
344 string const pretoken = lex.GetString();
345 if (pretoken == "\\layout") {
346 lex.pushToken(pretoken);
354 string const token = lex.GetString();
356 if (token.empty()) continue;
358 lyxerr[Debug::PARSER] << "Handling token: `"
359 << token << "'" << endl;
362 parseSingleLyXformat2Token(lex, par, first_par,
370 paragraph = first_par;
372 if (unknown_layouts > 0) {
373 string s = _("Couldn't set the layout for ");
374 if (unknown_layouts == 1) {
375 s += _("one paragraph");
377 s += tostr(unknown_layouts);
378 s += _(" paragraphs");
380 WriteAlert(_("Textclass Loading Error!"), s,
381 _("When reading " + fileName()));
388 void Buffer::insertErtContents(Paragraph * par, int & pos,
389 LyXFont const & font, bool set_inactive)
391 if (!ert_comp.contents.empty()) {
392 lyxerr[Debug::INSETS] << "ERT contents:\n"
393 << ert_comp.contents << endl;
394 Inset * inset = new InsetERT(ert_comp.contents, true);
395 par->insertInset(pos++, inset, font);
396 ert_comp.contents.erase();
399 ert_comp.active = false;
405 Buffer::parseSingleLyXformat2Token(LyXLex & lex, Paragraph *& par,
406 Paragraph *& first_par,
407 string const & token, int & pos,
408 Paragraph::depth_type & depth,
412 bool the_end_read = false;
413 #ifndef NO_PEXTRA_REALLY
414 // This is super temporary but is needed to get the compability
415 // mode for minipages work correctly together with new tabulars.
416 static int call_depth;
418 bool checkminipage = false;
419 static Paragraph * minipar;
420 static Paragraph * parBeforeMinipage;
423 if (token[0] != '\\') {
425 if (ert_comp.active) {
426 ert_comp.contents += token;
429 for (string::const_iterator cit = token.begin();
430 cit != token.end(); ++cit) {
431 par->insertChar(pos, (*cit), font);
434 checkminipage = true;
438 } else if (token == "\\i") {
439 Inset * inset = new InsetLatexAccent;
440 inset->read(this, lex);
441 par->insertInset(pos, inset, font);
443 } else if (token == "\\layout") {
445 ert_comp.in_tabular = false;
447 insertErtContents(par, pos, font);
450 string const layoutname = lex.GetString();
451 pair<bool, LyXTextClass::LayoutList::size_type> pp
452 = textclasslist.NumberOfLayout(params.textclass,
456 if (compare_no_case(layoutname, "latex") == 0) {
457 ert_comp.active = true;
461 // The is the compability reading of layout caption.
462 // It can be removed in LyX version 1.3.0. (Lgb)
463 if (compare_no_case(layoutname, "caption") == 0) {
464 // We expect that the par we are now working on is
465 // really inside a InsetText inside a InsetFloat.
466 // We also know that captions can only be
467 // one paragraph. (Lgb)
469 // We should now read until the next "\layout"
471 // This is probably not good enough, what if the
472 // caption is the last par in the document (Lgb)
473 istream & ist = lex.getStream();
479 if (prefixIs(line, "\\layout")) {
483 if (prefixIs(line, "\\begin_inset"))
485 if (prefixIs(line, "\\end_inset")) {
496 // Now we should have the whole layout in ss
497 // we should now be able to give this to the
499 ss << "\\end_inset\n";
501 // This seems like a bug in stringstream.
502 // We really should be able to use ss
504 istringstream is(ss.str());
506 tmplex.setStream(is);
507 Inset * inset = new InsetCaption;
508 inset->Read(this, tmplex);
509 par->InsertInset(pos, inset, font);
516 par = new Paragraph(par);
520 par->layout = pp.second;
523 // use default layout "Standard" (0)
526 string const s = _("Layout had to be changed from\n")
527 + layoutname + _(" to ")
528 + textclasslist.NameOfLayout(params.textclass, par->layout);
529 InsetError * new_inset = new InsetError(s);
530 par->insertInset(0, new_inset);
532 // Test whether the layout is obsolete.
533 LyXLayout const & layout =
534 textclasslist.Style(params.textclass,
536 if (!layout.obsoleted_by().empty())
537 par->layout = textclasslist
538 .NumberOfLayout(params.textclass,
539 layout.obsoleted_by())
541 par->params().depth(depth);
542 font = LyXFont(LyXFont::ALL_INHERIT, params.language);
543 if (file_format < 216
544 && params.language->lang() == "hebrew")
545 font.setLanguage(default_language);
550 } else if (token == "\\begin_float") {
551 // This is the compability reader. It can be removed in
552 // LyX version 1.3.0. (Lgb)
554 string const tmptok = lex.GetString();
555 //lyxerr << "old float: " << tmptok << endl;
558 stringstream old_float;
560 if (tmptok == "footnote") {
561 inset = new InsetFoot;
562 } else if (tmptok == "margin") {
563 inset = new InsetMarginal;
564 } else if (tmptok == "fig") {
565 inset = new InsetFloat("figure");
566 old_float << "placement htbp\n"
568 } else if (tmptok == "tab") {
569 inset = new InsetFloat("table");
570 old_float << "placement htbp\n"
572 } else if (tmptok == "alg") {
573 inset = new InsetFloat("algorithm");
574 old_float << "placement htbp\n"
576 } else if (tmptok == "wide-fig") {
577 inset = new InsetFloat("figure");
578 //InsetFloat * tmp = new InsetFloat("figure");
581 old_float << "placement htbp\n"
583 } else if (tmptok == "wide-tab") {
584 inset = new InsetFloat("table");
585 //InsetFloat * tmp = new InsetFloat("table");
588 old_float << "placement htbp\n"
594 return false; // no end read yet
597 old_float << "collapsed true\n";
599 // Here we need to check for \end_deeper and handle that
600 // before we do the footnote parsing.
601 // This _is_ a hack! (Lgb)
604 string const tmp = lex.GetString();
605 if (tmp == "\\end_deeper") {
606 //lyxerr << "\\end_deeper caught!" << endl;
608 lex.printError("\\end_deeper: "
609 "depth is already null");
614 old_float << tmp << ' ';
619 old_float << lex.getLongString("\\end_float")
620 << "\n\\end_inset\n";
621 //lyxerr << "Float Body:\n" << old_float.str() << endl;
622 // That this does not work seems like a bug
623 // in stringstream. (Lgb)
624 istringstream istr(old_float.str());
626 nylex.setStream(istr);
627 inset->read(this, nylex);
628 par->insertInset(pos, inset, font);
630 } else if (token == "\\begin_deeper") {
632 } else if (token == "\\end_deeper") {
634 lex.printError("\\end_deeper: "
635 "depth is already null");
639 } else if (token == "\\begin_preamble") {
640 params.readPreamble(lex);
641 } else if (token == "\\textclass") {
643 pair<bool, LyXTextClassList::size_type> pp =
644 textclasslist.NumberOfClass(lex.GetString());
646 params.textclass = pp.second;
648 WriteAlert(string(_("Textclass error")),
649 string(_("The document uses an unknown textclass \"")) +
650 lex.GetString() + string("\"."),
651 string(_("LyX will not be able to produce output correctly.")));
652 params.textclass = 0;
654 if (!textclasslist.Load(params.textclass)) {
655 // if the textclass wasn't loaded properly
656 // we need to either substitute another
657 // or stop loading the file.
658 // I can substitute but I don't see how I can
659 // stop loading... ideas?? ARRae980418
660 WriteAlert(_("Textclass Loading Error!"),
661 string(_("Can't load textclass ")) +
662 textclasslist.NameOfClass(params.textclass),
663 _("-- substituting default"));
664 params.textclass = 0;
666 } else if (token == "\\options") {
668 params.options = lex.GetString();
669 } else if (token == "\\language") {
670 params.readLanguage(lex);
671 } else if (token == "\\fontencoding") {
673 } else if (token == "\\inputencoding") {
675 params.inputenc = lex.GetString();
676 } else if (token == "\\graphics") {
677 params.readGraphicsDriver(lex);
678 } else if (token == "\\fontscheme") {
680 params.fonts = lex.GetString();
681 } else if (token == "\\noindent") {
682 par->params().noindent(true);
683 } else if (token == "\\fill_top") {
684 par->params().spaceTop(VSpace(VSpace::VFILL));
685 } else if (token == "\\fill_bottom") {
686 par->params().spaceBottom(VSpace(VSpace::VFILL));
687 } else if (token == "\\line_top") {
688 par->params().lineTop(true);
689 } else if (token == "\\line_bottom") {
690 par->params().lineBottom(true);
691 } else if (token == "\\pagebreak_top") {
692 par->params().pagebreakTop(true);
693 } else if (token == "\\pagebreak_bottom") {
694 par->params().pagebreakBottom(true);
695 } else if (token == "\\start_of_appendix") {
696 par->params().startOfAppendix(true);
697 } else if (token == "\\paragraph_separation") {
698 int tmpret = lex.FindToken(string_paragraph_separation);
699 if (tmpret == -1) ++tmpret;
700 if (tmpret != LYX_LAYOUT_DEFAULT)
701 params.paragraph_separation =
702 static_cast<BufferParams::PARSEP>(tmpret);
703 } else if (token == "\\defskip") {
705 params.defskip = VSpace(lex.GetString());
706 } else if (token == "\\epsfig") { // obsolete
707 // Indeed it is obsolete, but we HAVE to be backwards
708 // compatible until 0.14, because otherwise all figures
709 // in existing documents are irretrivably lost. (Asger)
710 params.readGraphicsDriver(lex);
711 } else if (token == "\\quotes_language") {
712 int tmpret = lex.FindToken(string_quotes_language);
713 if (tmpret == -1) ++tmpret;
714 if (tmpret != LYX_LAYOUT_DEFAULT) {
715 InsetQuotes::quote_language tmpl =
716 InsetQuotes::EnglishQ;
719 tmpl = InsetQuotes::EnglishQ;
722 tmpl = InsetQuotes::SwedishQ;
725 tmpl = InsetQuotes::GermanQ;
728 tmpl = InsetQuotes::PolishQ;
731 tmpl = InsetQuotes::FrenchQ;
734 tmpl = InsetQuotes::DanishQ;
737 params.quotes_language = tmpl;
739 } else if (token == "\\quotes_times") {
741 switch (lex.GetInteger()) {
743 params.quotes_times = InsetQuotes::SingleQ;
746 params.quotes_times = InsetQuotes::DoubleQ;
749 } else if (token == "\\papersize") {
750 int tmpret = lex.FindToken(string_papersize);
754 params.papersize2 = tmpret;
755 } else if (token == "\\paperpackage") {
756 int tmpret = lex.FindToken(string_paperpackages);
759 params.paperpackage = BufferParams::PACKAGE_NONE;
761 params.paperpackage = tmpret;
762 } else if (token == "\\use_geometry") {
764 params.use_geometry = lex.GetInteger();
765 } else if (token == "\\use_amsmath") {
767 params.use_amsmath = lex.GetInteger();
768 } else if (token == "\\use_natbib") {
770 params.use_natbib = lex.GetInteger();
771 } else if (token == "\\use_numerical_citations") {
773 params.use_numerical_citations = lex.GetInteger();
774 } else if (token == "\\paperorientation") {
775 int tmpret = lex.FindToken(string_orientation);
776 if (tmpret == -1) ++tmpret;
777 if (tmpret != LYX_LAYOUT_DEFAULT)
778 params.orientation = static_cast<BufferParams::PAPER_ORIENTATION>(tmpret);
779 } else if (token == "\\paperwidth") {
781 params.paperwidth = lex.GetString();
782 } else if (token == "\\paperheight") {
784 params.paperheight = lex.GetString();
785 } else if (token == "\\leftmargin") {
787 params.leftmargin = lex.GetString();
788 } else if (token == "\\topmargin") {
790 params.topmargin = lex.GetString();
791 } else if (token == "\\rightmargin") {
793 params.rightmargin = lex.GetString();
794 } else if (token == "\\bottommargin") {
796 params.bottommargin = lex.GetString();
797 } else if (token == "\\headheight") {
799 params.headheight = lex.GetString();
800 } else if (token == "\\headsep") {
802 params.headsep = lex.GetString();
803 } else if (token == "\\footskip") {
805 params.footskip = lex.GetString();
806 } else if (token == "\\paperfontsize") {
808 params.fontsize = strip(lex.GetString());
809 } else if (token == "\\papercolumns") {
811 params.columns = lex.GetInteger();
812 } else if (token == "\\papersides") {
814 switch (lex.GetInteger()) {
816 case 1: params.sides = LyXTextClass::OneSide; break;
817 case 2: params.sides = LyXTextClass::TwoSides; break;
819 } else if (token == "\\paperpagestyle") {
821 params.pagestyle = strip(lex.GetString());
822 } else if (token == "\\bullet") {
824 int const index = lex.GetInteger();
826 int temp_int = lex.GetInteger();
827 params.user_defined_bullets[index].setFont(temp_int);
828 params.temp_bullets[index].setFont(temp_int);
830 temp_int = lex.GetInteger();
831 params.user_defined_bullets[index].setCharacter(temp_int);
832 params.temp_bullets[index].setCharacter(temp_int);
834 temp_int = lex.GetInteger();
835 params.user_defined_bullets[index].setSize(temp_int);
836 params.temp_bullets[index].setSize(temp_int);
838 string const temp_str = lex.GetString();
839 if (temp_str != "\\end_bullet") {
840 // this element isn't really necessary for
841 // parsing but is easier for humans
842 // to understand bullets. Put it back and
843 // set a debug message?
844 lex.printError("\\end_bullet expected, got" + temp_str);
845 //how can I put it back?
847 } else if (token == "\\bulletLaTeX") {
849 int const index = lex.GetInteger();
851 string temp_str = lex.GetString();
853 while (temp_str != "\\end_bullet") {
854 // this loop structure is needed when user
855 // enters an empty string since the first
856 // thing returned will be the \\end_bullet
858 // if the LaTeX entry has spaces. Each element
859 // therefore needs to be read in turn
862 temp_str = lex.GetString();
864 params.user_defined_bullets[index].setText(sum_str);
865 params.temp_bullets[index].setText(sum_str);
866 } else if (token == "\\secnumdepth") {
868 params.secnumdepth = lex.GetInteger();
869 } else if (token == "\\tocdepth") {
871 params.tocdepth = lex.GetInteger();
872 } else if (token == "\\spacing") {
874 string const tmp = strip(lex.GetString());
875 Spacing::Space tmp_space = Spacing::Default;
877 if (tmp == "single") {
878 tmp_space = Spacing::Single;
879 } else if (tmp == "onehalf") {
880 tmp_space = Spacing::Onehalf;
881 } else if (tmp == "double") {
882 tmp_space = Spacing::Double;
883 } else if (tmp == "other") {
885 tmp_space = Spacing::Other;
886 tmp_val = lex.GetFloat();
888 lex.printError("Unknown spacing token: '$$Token'");
890 // Small hack so that files written with klyx will be
893 par->params().spacing(Spacing(tmp_space, tmp_val));
895 params.spacing.set(tmp_space, tmp_val);
897 } else if (token == "\\paragraph_spacing") {
899 string const tmp = strip(lex.GetString());
900 if (tmp == "single") {
901 par->params().spacing(Spacing(Spacing::Single));
902 } else if (tmp == "onehalf") {
903 par->params().spacing(Spacing(Spacing::Onehalf));
904 } else if (tmp == "double") {
905 par->params().spacing(Spacing(Spacing::Double));
906 } else if (tmp == "other") {
908 par->params().spacing(Spacing(Spacing::Other,
911 lex.printError("Unknown spacing token: '$$Token'");
913 } else if (token == "\\float_placement") {
915 params.float_placement = lex.GetString();
916 } else if (token == "\\family") {
918 font.setLyXFamily(lex.GetString());
919 } else if (token == "\\series") {
921 font.setLyXSeries(lex.GetString());
922 } else if (token == "\\shape") {
924 font.setLyXShape(lex.GetString());
925 } else if (token == "\\size") {
927 font.setLyXSize(lex.GetString());
930 #warning compatability hack needed
932 } else if (token == "\\latex") {
934 string const tok = lex.GetString();
935 // This is dirty, but gone with LyX3. (Asger)
936 if (tok == "no_latex")
937 font.setLatex(LyXFont::OFF);
938 else if (tok == "latex")
939 font.setLatex(LyXFont::ON);
940 else if (tok == "default")
941 font.setLatex(LyXFont::INHERIT);
943 lex.printError("Unknown LaTeX font flag "
946 } else if (token == "\\latex") {
948 string const tok = lex.GetString();
949 if (tok == "no_latex") {
951 insertErtContents(par, pos, font);
952 } else if (tok == "latex") {
953 ert_comp.active = true;
954 } else if (tok == "default") {
956 insertErtContents(par, pos, font);
958 lex.printError("Unknown LaTeX font flag "
962 } else if (token == "\\lang") {
964 string const tok = lex.GetString();
965 Language const * lang = languages.getLanguage(tok);
967 font.setLanguage(lang);
969 font.setLanguage(params.language);
970 lex.printError("Unknown language `$$Token'");
972 } else if (token == "\\numeric") {
974 font.setNumber(font.setLyXMisc(lex.GetString()));
975 } else if (token == "\\emph") {
977 font.setEmph(font.setLyXMisc(lex.GetString()));
978 } else if (token == "\\bar") {
980 string const tok = lex.GetString();
981 // This is dirty, but gone with LyX3. (Asger)
983 font.setUnderbar(LyXFont::ON);
984 else if (tok == "no")
985 font.setUnderbar(LyXFont::OFF);
986 else if (tok == "default")
987 font.setUnderbar(LyXFont::INHERIT);
989 lex.printError("Unknown bar font flag "
991 } else if (token == "\\noun") {
993 font.setNoun(font.setLyXMisc(lex.GetString()));
994 } else if (token == "\\color") {
996 font.setLyXColor(lex.GetString());
997 } else if (token == "\\align") {
998 int tmpret = lex.FindToken(string_align);
999 if (tmpret == -1) ++tmpret;
1000 if (tmpret != LYX_LAYOUT_DEFAULT) { // tmpret != 99 ???
1001 int const tmpret2 = int(pow(2.0, tmpret));
1002 //lyxerr << "Tmpret2 = " << tmpret2 << endl;
1003 par->params().align(LyXAlignment(tmpret2));
1005 } else if (token == "\\added_space_top") {
1007 par->params().spaceTop(VSpace(lex.GetString()));
1008 } else if (token == "\\added_space_bottom") {
1010 par->params().spaceBottom(VSpace(lex.GetString()));
1011 #ifndef NO_PEXTRA_REALLY
1012 } else if (token == "\\pextra_type") {
1014 par->params().pextraType(lex.GetInteger());
1015 } else if (token == "\\pextra_width") {
1017 par->params().pextraWidth(lex.GetString());
1018 } else if (token == "\\pextra_widthp") {
1020 par->params().pextraWidthp(lex.GetString());
1021 } else if (token == "\\pextra_alignment") {
1023 par->params().pextraAlignment(lex.GetInteger());
1024 } else if (token == "\\pextra_hfill") {
1026 par->params().pextraHfill(lex.GetInteger());
1027 } else if (token == "\\pextra_start_minipage") {
1029 par->params().pextraStartMinipage(lex.GetInteger());
1031 } else if (token == "\\labelwidthstring") {
1033 par->params().labelWidthString(lex.GetString());
1034 // do not delete this token, it is still needed!
1035 } else if (token == "\\end_inset") {
1036 lyxerr << "Solitary \\end_inset. Missing \\begin_inset?.\n"
1037 << "Last inset read was: " << last_inset_read
1039 // Simply ignore this. The insets do not have
1041 // But insets should read it, it is a part of
1042 // the inset isn't it? Lgb.
1043 } else if (token == "\\begin_inset") {
1045 insertErtContents(par, pos, font, false);
1046 ert_stack.push(ert_comp);
1047 ert_comp = ErtComp();
1049 readInset(lex, par, pos, font);
1051 ert_comp = ert_stack.top();
1054 } else if (token == "\\SpecialChar") {
1055 LyXLayout const & layout =
1056 textclasslist.Style(params.textclass,
1059 // Insets don't make sense in a free-spacing context! ---Kayvan
1060 if (layout.free_spacing) {
1063 string next_token = lex.GetString();
1064 if (next_token == "\\-") {
1065 par->insertChar(pos, '-', font);
1066 } else if (next_token == "\\protected_separator"
1067 || next_token == "~") {
1068 par->insertChar(pos, ' ', font);
1070 lex.printError("Token `$$Token' "
1072 "paragraph layout!");
1077 Inset * inset = new InsetSpecialChar;
1078 inset->read(this, lex);
1079 par->insertInset(pos, inset, font);
1082 } else if (token == "\\newline") {
1085 if (!ert_comp.in_tabular && ert_comp.active) {
1086 ert_comp.contents += char(Paragraph::META_NEWLINE);
1088 // Since we cannot know it this is only a regular
1089 // newline or a tabular cell delimter we have to
1090 // handle the ERT here.
1091 insertErtContents(par, pos, font, false);
1093 par->insertChar(pos, Paragraph::META_NEWLINE, font);
1097 par->insertChar(pos, Paragraph::META_NEWLINE, font);
1100 } else if (token == "\\LyXTable") {
1102 ert_comp.in_tabular = true;
1104 Inset * inset = new InsetTabular(*this);
1105 inset->read(this, lex);
1106 par->insertInset(pos, inset, font);
1108 // because of OLD_TABULAR_READ where tabulars have been
1110 checkminipage = true;
1111 } else if (token == "\\hfill") {
1112 par->insertChar(pos, Paragraph::META_HFILL, font);
1114 } else if (token == "\\protected_separator") { // obsolete
1115 // This is a backward compability thingie. (Lgb)
1116 // Remove it later some time...introduced with fileformat
1118 LyXLayout const & layout =
1119 textclasslist.Style(params.textclass,
1122 if (layout.free_spacing) {
1123 par->insertChar(pos, ' ', font);
1125 Inset * inset = new InsetSpecialChar(InsetSpecialChar::PROTECTED_SEPARATOR);
1126 par->insertInset(pos, inset, font);
1129 } else if (token == "\\bibitem") { // ale970302
1131 InsetCommandParams p("bibitem", "dummy");
1132 par->bibkey = new InsetBibKey(p);
1134 par->bibkey->read(this, lex);
1135 } else if (token == "\\backslash") {
1137 if (ert_comp.active) {
1138 ert_comp.contents += "\\";
1141 par->insertChar(pos, '\\', font);
1146 } else if (token == "\\the_end") {
1148 // If we still have some ert active here we have to insert
1149 // it so we don't loose it. (Lgb)
1150 insertErtContents(par, pos, font);
1152 the_end_read = true;
1153 minipar = parBeforeMinipage = 0;
1156 if (ert_comp.active) {
1157 ert_comp.contents += token;
1160 // This should be insurance for the future: (Asger)
1161 lex.printError("Unknown token `$$Token'. "
1162 "Inserting as text.");
1163 string::const_iterator cit = token.begin();
1164 string::const_iterator end = token.end();
1165 for (; cit != end; ++cit) {
1166 par->insertChar(pos, (*cit), font);
1173 #ifndef NO_PEXTRA_REALLY
1174 // now check if we have a minipage paragraph as at this
1175 // point we already read all the necessary data!
1176 // this cannot be done in layout because there we did
1177 // not read yet the paragraph PEXTRA-params (Jug)
1179 // BEGIN pextra_minipage compability
1180 // This should be removed in 1.3.x (Lgb)
1182 // This compability code is not perfect. In a couple
1183 // of rand cases it fails. When the minipage par is
1184 // the first par in the document, and when there are
1185 // none or only one regular paragraphs after the
1186 // minipage. Currently I am not investing any effort
1187 // in fixing those cases.
1189 //lyxerr << "Call depth: " << call_depth << endl;
1190 if (checkminipage && (call_depth == 1)) {
1191 checkminipage = false;
1192 if (minipar && (minipar != par) &&
1193 (par->params().pextraType()==Paragraph::PEXTRA_MINIPAGE))
1195 lyxerr << "minipages in a row" << endl;
1196 if (par->params().pextraStartMinipage()) {
1197 lyxerr << "start new minipage" << endl;
1198 // minipages in a row
1199 par->previous()->next(0);
1202 Paragraph * tmp = minipar;
1204 tmp->params().pextraType(0);
1205 tmp->params().pextraWidth(string());
1206 tmp->params().pextraWidthp(string());
1207 tmp->params().pextraAlignment(0);
1208 tmp->params().pextraHfill(false);
1209 tmp->params().pextraStartMinipage(false);
1212 // create a new paragraph to insert the
1213 // minipages in the following case
1214 if (par->params().pextraStartMinipage() &&
1215 !par->params().pextraHfill())
1217 Paragraph * p = new Paragraph;
1219 p->previous(parBeforeMinipage);
1220 parBeforeMinipage->next(p);
1222 p->params().depth(parBeforeMinipage->params().depth());
1223 parBeforeMinipage = p;
1225 InsetMinipage * mini = new InsetMinipage;
1226 mini->pos(static_cast<InsetMinipage::Position>(par->params().pextraAlignment()));
1227 mini->width(par->params().pextraWidth());
1228 if (!par->params().pextraWidthp().empty()) {
1229 lyxerr << "WP:" << mini->width() << endl;
1230 mini->width(tostr(par->params().pextraWidthp())+"%");
1232 mini->inset.paragraph(par);
1233 // Insert the minipage last in the
1234 // previous paragraph.
1235 if (par->params().pextraHfill()) {
1236 parBeforeMinipage->insertChar
1237 (parBeforeMinipage->size(), Paragraph::META_HFILL);
1239 parBeforeMinipage->insertInset
1240 (parBeforeMinipage->size(), mini);
1244 lyxerr << "new minipage par" << endl;
1245 //nothing to do just continue reading
1248 } else if (minipar && (minipar != par)) {
1249 lyxerr << "last minipage par read" << endl;
1250 // The last paragraph read was not part of a
1251 // minipage but the par linked list is...
1252 // So we need to remove the last par from the
1254 if (par->previous())
1255 par->previous()->next(0);
1256 par->previous(parBeforeMinipage);
1257 parBeforeMinipage->next(par);
1258 Paragraph * tmp = minipar;
1260 tmp->params().pextraType(0);
1261 tmp->params().pextraWidth(string());
1262 tmp->params().pextraWidthp(string());
1263 tmp->params().pextraAlignment(0);
1264 tmp->params().pextraHfill(false);
1265 tmp->params().pextraStartMinipage(false);
1268 depth = parBeforeMinipage->params().depth();
1269 minipar = parBeforeMinipage = 0;
1270 } else if (!minipar &&
1271 (par->params().pextraType() == Paragraph::PEXTRA_MINIPAGE))
1273 // par is the first paragraph in a minipage
1274 lyxerr << "begin minipage" << endl;
1275 // To minimize problems for
1276 // the users we will insert
1277 // the first minipage in
1278 // a sequence of minipages
1279 // in its own paragraph.
1280 Paragraph * p = new Paragraph;
1282 p->previous(par->previous());
1284 p->params().depth(depth);
1285 par->params().depth(0);
1287 if (par->previous())
1288 par->previous()->next(p);
1290 parBeforeMinipage = p;
1292 if (!first_par || (first_par == par))
1295 InsetMinipage * mini = new InsetMinipage;
1296 mini->pos(static_cast<InsetMinipage::Position>(minipar->params().pextraAlignment()));
1297 mini->width(minipar->params().pextraWidth());
1298 if (!par->params().pextraWidthp().empty()) {
1299 lyxerr << "WP:" << mini->width() << endl;
1300 mini->width(tostr(par->params().pextraWidthp())+"%");
1302 mini->inset.paragraph(minipar);
1304 // Insert the minipage last in the
1305 // previous paragraph.
1306 if (minipar->params().pextraHfill()) {
1307 parBeforeMinipage->insertChar
1308 (parBeforeMinipage->size(),Paragraph::META_HFILL);
1310 parBeforeMinipage->insertInset
1311 (parBeforeMinipage->size(), mini);
1314 // End of pextra_minipage compability
1317 return the_end_read;
1320 // needed to insert the selection
1321 void Buffer::insertStringAsLines(Paragraph *& par, Paragraph::size_type & pos,
1322 LyXFont const & font,
1323 string const & str) const
1325 LyXLayout const & layout = textclasslist.Style(params.textclass,
1327 // insert the string, don't insert doublespace
1328 bool space_inserted = true;
1329 for(string::const_iterator cit = str.begin();
1330 cit != str.end(); ++cit) {
1332 if (par->size() || layout.keepempty) {
1333 par->breakParagraph(params, pos,
1334 layout.isEnvironment());
1337 space_inserted = true;
1341 // do not insert consecutive spaces if !free_spacing
1342 } else if ((*cit == ' ' || *cit == '\t')
1343 && space_inserted && !layout.free_spacing) {
1345 } else if (*cit == '\t') {
1346 if (!layout.free_spacing) {
1347 // tabs are like spaces here
1348 par->insertChar(pos, ' ', font);
1350 space_inserted = true;
1352 const Paragraph::value_type nb = 8 - pos % 8;
1353 for (Paragraph::size_type a = 0;
1355 par->insertChar(pos, ' ', font);
1358 space_inserted = true;
1360 } else if (!IsPrintable(*cit)) {
1361 // Ignore unprintables
1364 // just insert the character
1365 par->insertChar(pos, *cit, font);
1367 space_inserted = (*cit == ' ');
1374 void Buffer::readInset(LyXLex & lex, Paragraph *& par,
1375 int & pos, LyXFont & font)
1377 // consistency check
1378 if (lex.GetString() != "\\begin_inset") {
1379 lyxerr << "Buffer::readInset: Consistency check failed."
1386 string const tmptok = lex.GetString();
1387 last_inset_read = tmptok;
1389 // test the different insets
1390 if (tmptok == "LatexCommand") {
1391 InsetCommandParams inscmd;
1394 string const cmdName = inscmd.getCmdName();
1396 // This strange command allows LyX to recognize "natbib" style
1397 // citations: citet, citep, Citet etc.
1398 if (compare_no_case(cmdName, "cite", 4) == 0) {
1399 inset = new InsetCitation(inscmd);
1400 } else if (cmdName == "bibitem") {
1401 lex.printError("Wrong place for bibitem");
1402 inset = new InsetBibKey(inscmd);
1403 } else if (cmdName == "BibTeX") {
1404 inset = new InsetBibtex(inscmd);
1405 } else if (cmdName == "index") {
1406 inset = new InsetIndex(inscmd);
1407 } else if (cmdName == "include") {
1408 inset = new InsetInclude(inscmd, *this);
1409 } else if (cmdName == "label") {
1410 inset = new InsetLabel(inscmd);
1411 } else if (cmdName == "url"
1412 || cmdName == "htmlurl") {
1413 inset = new InsetUrl(inscmd);
1414 } else if (cmdName == "ref"
1415 || cmdName == "pageref"
1416 || cmdName == "vref"
1417 || cmdName == "vpageref"
1418 || cmdName == "prettyref") {
1419 if (!inscmd.getOptions().empty()
1420 || !inscmd.getContents().empty()) {
1421 inset = new InsetRef(inscmd, *this);
1423 } else if (cmdName == "tableofcontents") {
1424 inset = new InsetTOC(inscmd);
1425 } else if (cmdName == "listofalgorithms") {
1426 inset = new InsetFloatList("algorithm");
1427 } else if (cmdName == "listoffigures") {
1428 inset = new InsetFloatList("figure");
1429 } else if (cmdName == "listoftables") {
1430 inset = new InsetFloatList("table");
1431 } else if (cmdName == "printindex") {
1432 inset = new InsetPrintIndex(inscmd);
1433 } else if (cmdName == "lyxparent") {
1434 inset = new InsetParent(inscmd, *this);
1437 bool alreadyread = false;
1438 if (tmptok == "Quotes") {
1439 inset = new InsetQuotes;
1440 } else if (tmptok == "External") {
1441 inset = new InsetExternal;
1442 } else if (tmptok == "FormulaMacro") {
1443 inset = new InsetFormulaMacro;
1444 } else if (tmptok == "Formula") {
1445 inset = new InsetFormula;
1446 } else if (tmptok == "Figure") {
1447 inset = new InsetFig(100, 100, *this);
1448 } else if (tmptok == "Info") {// backwards compatibility
1449 inset = new InsetNote(this,
1450 lex.getLongString("\\end_inset"),
1453 } else if (tmptok == "Note") {
1454 inset = new InsetNote;
1455 } else if (tmptok == "Include") {
1456 InsetCommandParams p( "Include" );
1457 inset = new InsetInclude(p, *this);
1458 } else if (tmptok == "ERT") {
1459 inset = new InsetERT;
1460 } else if (tmptok == "Tabular") {
1461 inset = new InsetTabular(*this);
1462 } else if (tmptok == "Text") {
1463 inset = new InsetText;
1464 } else if (tmptok == "Foot") {
1465 inset = new InsetFoot;
1466 } else if (tmptok == "Marginal") {
1467 inset = new InsetMarginal;
1468 } else if (tmptok == "Minipage") {
1469 inset = new InsetMinipage;
1470 } else if (tmptok == "Float") {
1472 string tmptok = lex.GetString();
1473 inset = new InsetFloat(tmptok);
1475 } else if (tmptok == "List") {
1476 inset = new InsetList;
1477 } else if (tmptok == "Theorem") {
1478 inset = new InsetList;
1480 } else if (tmptok == "Caption") {
1481 inset = new InsetCaption;
1482 } else if (tmptok == "GRAPHICS") {
1483 inset = new InsetGraphics;
1484 } else if (tmptok == "FloatList") {
1485 inset = new InsetFloatList;
1488 if (inset && !alreadyread) inset->read(this, lex);
1492 par->insertInset(pos, inset, font);
1498 bool Buffer::readFile(LyXLex & lex, Paragraph * par)
1502 string const token(lex.GetString());
1503 if (token == "\\lyxformat") { // the first token _must_ be...
1505 string tmp_format = lex.GetString();
1506 //lyxerr << "LyX Format: `" << tmp_format << "'" << endl;
1507 // if present remove ".," from string.
1508 string::size_type dot = tmp_format.find_first_of(".,");
1509 //lyxerr << " dot found at " << dot << endl;
1510 if (dot != string::npos)
1511 tmp_format.erase(dot, 1);
1512 file_format = strToInt(tmp_format);
1513 if (file_format == LYX_FORMAT) {
1515 } else if (file_format > LYX_FORMAT) {
1517 WriteAlert(_("Warning!"),
1518 _("LyX file format is newer that what"),
1519 _("is supported in this LyX version. Expect some problems."));
1521 } else if (file_format < LYX_FORMAT) {
1523 if (file_format < 200) {
1524 WriteAlert(_("ERROR!"),
1525 _("Old LyX file format found. "
1526 "Use LyX 0.10.x to read this!"));
1530 bool the_end = readLyXformat2(lex, par);
1532 // the_end was added in 213
1533 if (file_format < 213)
1537 WriteAlert(_("Warning!"),
1538 _("Reading of document is not complete"),
1539 _("Maybe the document is truncated"));
1541 } else { // "\\lyxformat" not found
1542 WriteAlert(_("ERROR!"), _("Not a LyX file!"));
1545 WriteAlert(_("ERROR!"), _("Unable to read file!"));
1550 // Should probably be moved to somewhere else: BufferView? LyXView?
1551 bool Buffer::save() const
1553 // We don't need autosaves in the immediate future. (Asger)
1554 resetAutosaveTimers();
1558 if (lyxrc.make_backup) {
1559 s = fileName() + '~';
1560 if (!lyxrc.backupdir_path.empty())
1561 s = AddName(lyxrc.backupdir_path,
1562 subst(os::slashify_path(s),'/','!'));
1564 // Rename is the wrong way of making a backup,
1565 // this is the correct way.
1566 /* truss cp fil fil2:
1567 lstat("LyXVC3.lyx", 0xEFFFF898) Err#2 ENOENT
1568 stat("LyXVC.lyx", 0xEFFFF688) = 0
1569 open("LyXVC.lyx", O_RDONLY) = 3
1570 open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
1571 fstat(4, 0xEFFFF508) = 0
1572 fstat(3, 0xEFFFF508) = 0
1573 read(3, " # T h i s f i l e w".., 8192) = 5579
1574 write(4, " # T h i s f i l e w".., 5579) = 5579
1575 read(3, 0xEFFFD4A0, 8192) = 0
1578 chmod("LyXVC3.lyx", 0100644) = 0
1579 lseek(0, 0, SEEK_CUR) = 46440
1583 // Should probably have some more error checking here.
1584 // Should be cleaned up in 0.13, at least a bit.
1585 // Doing it this way, also makes the inodes stay the same.
1586 // This is still not a very good solution, in particular we
1587 // might loose the owner of the backup.
1588 FileInfo finfo(fileName());
1589 if (finfo.exist()) {
1590 mode_t fmode = finfo.getMode();
1591 struct utimbuf times = {
1592 finfo.getAccessTime(),
1593 finfo.getModificationTime() };
1595 ifstream ifs(fileName().c_str());
1596 ofstream ofs(s.c_str(), ios::out|ios::trunc);
1601 ::chmod(s.c_str(), fmode);
1603 if (::utime(s.c_str(), ×)) {
1604 lyxerr << "utime error." << endl;
1607 lyxerr << "LyX was not able to make "
1608 "backup copy. Beware." << endl;
1613 if (writeFile(fileName(), false)) {
1615 removeAutosaveFile(fileName());
1617 // Saving failed, so backup is not backup
1618 if (lyxrc.make_backup) {
1619 lyx::rename(s, fileName());
1627 // Returns false if unsuccesful
1628 bool Buffer::writeFile(string const & fname, bool flag) const
1630 // if flag is false writeFile will not create any GUI
1631 // warnings, only cerr.
1632 // Needed for autosave in background or panic save (Matthias 120496)
1634 if (read_only && (fname == filename)) {
1635 // Here we should come with a question if we should
1636 // perform the write anyway.
1638 lyxerr << _("Error! Document is read-only: ")
1641 WriteAlert(_("Error! Document is read-only: "),
1646 FileInfo finfo(fname);
1647 if (finfo.exist() && !finfo.writable()) {
1648 // Here we should come with a question if we should
1649 // try to do the save anyway. (i.e. do a chmod first)
1651 lyxerr << _("Error! Cannot write file: ")
1654 WriteFSAlert(_("Error! Cannot write file: "),
1659 ofstream ofs(fname.c_str());
1662 lyxerr << _("Error! Cannot open file: ")
1665 WriteFSAlert(_("Error! Cannot open file: "),
1671 // Use the standard "C" locale for file output.
1672 ofs.imbue(std::locale::classic());
1675 // The top of the file should not be written by params.
1677 // write out a comment in the top of the file
1678 ofs << '#' << LYX_DOCVERSION
1679 << " created this file. For more info see http://www.lyx.org/\n"
1680 << "\\lyxformat " << LYX_FORMAT << "\n";
1682 // now write out the buffer paramters.
1683 params.writeFile(ofs);
1685 Paragraph::depth_type depth = 0;
1687 // this will write out all the paragraphs
1688 // using recursive descent.
1689 paragraph->writeFile(this, ofs, params, depth);
1691 // Write marker that shows file is complete
1692 ofs << "\n\\the_end" << endl;
1696 // how to check if close went ok?
1697 // Following is an attempt... (BE 20001011)
1699 // good() returns false if any error occured, including some
1700 // formatting error.
1701 // bad() returns true if something bad happened in the buffer,
1702 // which should include file system full errors.
1709 lyxerr << "Buffer::writeFile: BAD ERROR!" << endl;
1711 lyxerr << "Buffer::writeFile: NOT SO BAD ERROR!"
1721 string const Buffer::asciiParagraph(Paragraph const * par,
1722 unsigned int linelen) const
1724 ostringstream buffer;
1725 Paragraph::depth_type depth = 0;
1727 Paragraph::depth_type ltype_depth = 0;
1728 unsigned int currlinelen = 0;
1729 bool ref_printed = false;
1733 if (!par->previous()) {
1734 // begins or ends a deeper area ?
1735 if (depth != par->params().depth()) {
1736 if (par->params().depth() > depth) {
1737 while (par->params().depth() > depth) {
1741 while (par->params().depth() < depth) {
1747 // First write the layout
1748 string const tmp = textclasslist.NameOfLayout(params.textclass, par->layout);
1749 if (tmp == "Itemize") {
1751 ltype_depth = depth + 1;
1752 } else if (tmp == "Enumerate") {
1754 ltype_depth = depth + 1;
1755 } else if (contains(tmp, "ection")) {
1757 ltype_depth = depth + 1;
1758 } else if (contains(tmp, "aragraph")) {
1760 ltype_depth = depth + 1;
1761 } else if (tmp == "Description") {
1763 ltype_depth = depth + 1;
1764 } else if (tmp == "Abstract") {
1767 } else if (tmp == "Bibliography") {
1775 /* maybe some vertical spaces */
1777 /* the labelwidthstring used in lists */
1781 /* some pagebreaks? */
1785 /* what about the alignment */
1787 lyxerr << "Should this ever happen?" << endl;
1791 LyXFont const font1 = LyXFont(LyXFont::ALL_INHERIT, params.language);
1793 for (Paragraph::size_type i = 0; i < par->size(); ++i) {
1794 if (!i && !noparbreak) {
1797 for (Paragraph::depth_type j = 0; j < depth; ++j)
1799 currlinelen = depth * 2;
1802 case 4: // (Sub)Paragraph
1803 case 5: // Description
1807 buffer << "Abstract\n\n";
1809 buffer << "Abstract: ";
1811 case 7: // Bibliography
1814 buffer << "References\n\n";
1816 buffer << "References: ";
1821 buffer << par->params().labelString() << " ";
1824 if (ltype_depth > depth) {
1825 for (Paragraph::depth_type j = ltype_depth - 1;
1828 currlinelen += (ltype_depth-depth)*2;
1832 LyXFont const font2 = par->getFontSettings(params, i);
1833 if (font1.latex() != font2.latex()) {
1834 if (font2.latex() == LyXFont::OFF)
1843 char c = par->getUChar(params, i);
1847 case Paragraph::META_INSET:
1849 Inset const * inset = par->getInset(i);
1851 if (!inset->ascii(this, buffer)) {
1854 rsplit(buffer.str().c_str(),
1856 currlinelen += s.length();
1858 // to be sure it breaks paragraph
1859 currlinelen += linelen;
1865 case Paragraph::META_NEWLINE:
1868 for (Paragraph::depth_type j = 0;
1872 currlinelen = depth * 2;
1873 if (ltype_depth > depth) {
1874 for (Paragraph::depth_type j = ltype_depth;
1877 currlinelen += (ltype_depth - depth) * 2;
1881 case Paragraph::META_HFILL:
1890 if ((linelen > 0) && (currlinelen > (linelen - 10)) &&
1891 (c == ' ') && ((i + 2) < par->size()))
1894 for (Paragraph::depth_type j = 0;
1897 currlinelen = depth * 2;
1898 if (ltype_depth > depth) {
1899 for (Paragraph::depth_type j = ltype_depth;
1902 currlinelen += (ltype_depth-depth)*2;
1904 } else if (c != '\0')
1907 lyxerr[Debug::INFO] << "writeAsciiFile: NULL char in structure." << endl;
1912 return buffer.str().c_str();
1916 void Buffer::writeFileAscii(string const & fname, int linelen)
1918 ofstream ofs(fname.c_str());
1920 WriteFSAlert(_("Error: Cannot write file:"), fname);
1923 writeFileAscii(ofs, linelen);
1927 void Buffer::writeFileAscii(ostream & ofs, int linelen)
1929 Paragraph * par = paragraph;
1931 ofs << asciiParagraph(par, linelen);
1939 void Buffer::makeLaTeXFile(string const & fname,
1940 string const & original_path,
1941 bool nice, bool only_body)
1943 lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
1945 niceFile = nice; // this will be used by Insetincludes.
1947 tex_code_break_column = lyxrc.ascii_linelen;
1949 LyXTextClass const & tclass =
1950 textclasslist.TextClass(params.textclass);
1952 ofstream ofs(fname.c_str());
1954 WriteFSAlert(_("Error: Cannot open file: "), fname);
1958 // validate the buffer.
1959 lyxerr[Debug::LATEX] << " Validating buffer..." << endl;
1960 LaTeXFeatures features(params, tclass.numLayouts());
1962 lyxerr[Debug::LATEX] << " Buffer validation done." << endl;
1965 // The starting paragraph of the coming rows is the
1966 // first paragraph of the document. (Asger)
1967 texrow.start(paragraph, 0);
1969 if (!only_body && nice) {
1970 ofs << "%% " LYX_DOCVERSION " created this file. "
1971 "For more info, see http://www.lyx.org/.\n"
1972 "%% Do not edit unless you really know what "
1977 lyxerr[Debug::INFO] << "lyx header finished" << endl;
1978 // There are a few differences between nice LaTeX and usual files:
1979 // usual is \batchmode and has a
1980 // special input@path to allow the including of figures
1981 // with either \input or \includegraphics (what figinsets do).
1982 // batchmode is not set if there is a tex_code_break_column.
1983 // In this case somebody is interested in the generated LaTeX,
1984 // so this is OK. input@path is set when the actual parameter
1985 // original_path is set. This is done for usual tex-file, but not
1986 // for nice-latex-file. (Matthias 250696)
1989 // code for usual, NOT nice-latex-file
1990 ofs << "\\batchmode\n"; // changed
1991 // from \nonstopmode
1994 if (!original_path.empty()) {
1995 ofs << "\\makeatletter\n"
1996 << "\\def\\input@path{{"
1997 << os::external_path(original_path) << "/}}\n"
1998 << "\\makeatother\n";
2004 ofs << "\\documentclass";
2006 ostringstream options; // the document class options.
2008 if (tokenPos(tclass.opt_fontsize(),
2009 '|', params.fontsize) >= 0) {
2010 // only write if existing in list (and not default)
2011 options << params.fontsize << "pt,";
2015 if (!params.use_geometry &&
2016 (params.paperpackage == BufferParams::PACKAGE_NONE)) {
2017 switch (params.papersize) {
2018 case BufferParams::PAPER_A4PAPER:
2019 options << "a4paper,";
2021 case BufferParams::PAPER_USLETTER:
2022 options << "letterpaper,";
2024 case BufferParams::PAPER_A5PAPER:
2025 options << "a5paper,";
2027 case BufferParams::PAPER_B5PAPER:
2028 options << "b5paper,";
2030 case BufferParams::PAPER_EXECUTIVEPAPER:
2031 options << "executivepaper,";
2033 case BufferParams::PAPER_LEGALPAPER:
2034 options << "legalpaper,";
2040 if (params.sides != tclass.sides()) {
2041 switch (params.sides) {
2042 case LyXTextClass::OneSide:
2043 options << "oneside,";
2045 case LyXTextClass::TwoSides:
2046 options << "twoside,";
2052 if (params.columns != tclass.columns()) {
2053 if (params.columns == 2)
2054 options << "twocolumn,";
2056 options << "onecolumn,";
2059 if (!params.use_geometry
2060 && params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
2061 options << "landscape,";
2063 // language should be a parameter to \documentclass
2065 ostringstream language_options;
2066 if (params.language->babel() == "hebrew"
2067 && default_language->babel() != "hebrew")
2068 // This seems necessary
2069 features.UsedLanguages.insert(default_language);
2071 if (lyxrc.language_use_babel ||
2072 params.language->lang() != lyxrc.default_language ||
2073 !features.UsedLanguages.empty()) {
2075 for (LaTeXFeatures::LanguageList::const_iterator cit =
2076 features.UsedLanguages.begin();
2077 cit != features.UsedLanguages.end(); ++cit)
2078 language_options << (*cit)->babel() << ',';
2079 language_options << params.language->babel();
2080 if (lyxrc.language_global_options)
2081 options << language_options.str() << ',';
2084 // the user-defined options
2085 if (!params.options.empty()) {
2086 options << params.options << ',';
2089 string strOptions(options.str().c_str());
2090 if (!strOptions.empty()){
2091 strOptions = strip(strOptions, ',');
2092 ofs << '[' << strOptions << ']';
2096 << textclasslist.LatexnameOfClass(params.textclass)
2099 // end of \documentclass defs
2101 // font selection must be done before loading fontenc.sty
2102 // The ae package is not needed when using OT1 font encoding.
2103 if (params.fonts != "default" &&
2104 (params.fonts != "ae" || lyxrc.fontenc != "default")) {
2105 ofs << "\\usepackage{" << params.fonts << "}\n";
2107 if (params.fonts == "ae") {
2108 ofs << "\\usepackage{aecompl}\n";
2112 // this one is not per buffer
2113 if (lyxrc.fontenc != "default") {
2114 ofs << "\\usepackage[" << lyxrc.fontenc
2119 if (params.inputenc == "auto") {
2120 string const doc_encoding =
2121 params.language->encoding()->LatexName();
2123 // Create a list with all the input encodings used
2125 set<string> encodings;
2126 for (LaTeXFeatures::LanguageList::const_iterator it =
2127 features.UsedLanguages.begin();
2128 it != features.UsedLanguages.end(); ++it)
2129 if ((*it)->encoding()->LatexName() != doc_encoding)
2130 encodings.insert((*it)->encoding()->LatexName());
2132 ofs << "\\usepackage[";
2133 std::copy(encodings.begin(), encodings.end(),
2134 std::ostream_iterator<string>(ofs, ","));
2135 ofs << doc_encoding << "]{inputenc}\n";
2137 } else if (params.inputenc != "default") {
2138 ofs << "\\usepackage[" << params.inputenc
2143 // At the very beginning the text parameters.
2144 if (params.paperpackage != BufferParams::PACKAGE_NONE) {
2145 switch (params.paperpackage) {
2146 case BufferParams::PACKAGE_A4:
2147 ofs << "\\usepackage{a4}\n";
2150 case BufferParams::PACKAGE_A4WIDE:
2151 ofs << "\\usepackage{a4wide}\n";
2154 case BufferParams::PACKAGE_WIDEMARGINSA4:
2155 ofs << "\\usepackage[widemargins]{a4}\n";
2160 if (params.use_geometry) {
2161 ofs << "\\usepackage{geometry}\n";
2163 ofs << "\\geometry{verbose";
2164 if (params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
2165 ofs << ",landscape";
2166 switch (params.papersize2) {
2167 case BufferParams::VM_PAPER_CUSTOM:
2168 if (!params.paperwidth.empty())
2169 ofs << ",paperwidth="
2170 << params.paperwidth;
2171 if (!params.paperheight.empty())
2172 ofs << ",paperheight="
2173 << params.paperheight;
2175 case BufferParams::VM_PAPER_USLETTER:
2176 ofs << ",letterpaper";
2178 case BufferParams::VM_PAPER_USLEGAL:
2179 ofs << ",legalpaper";
2181 case BufferParams::VM_PAPER_USEXECUTIVE:
2182 ofs << ",executivepaper";
2184 case BufferParams::VM_PAPER_A3:
2187 case BufferParams::VM_PAPER_A4:
2190 case BufferParams::VM_PAPER_A5:
2193 case BufferParams::VM_PAPER_B3:
2196 case BufferParams::VM_PAPER_B4:
2199 case BufferParams::VM_PAPER_B5:
2203 // default papersize ie BufferParams::VM_PAPER_DEFAULT
2204 switch (lyxrc.default_papersize) {
2205 case BufferParams::PAPER_DEFAULT: // keep compiler happy
2206 case BufferParams::PAPER_USLETTER:
2207 ofs << ",letterpaper";
2209 case BufferParams::PAPER_LEGALPAPER:
2210 ofs << ",legalpaper";
2212 case BufferParams::PAPER_EXECUTIVEPAPER:
2213 ofs << ",executivepaper";
2215 case BufferParams::PAPER_A3PAPER:
2218 case BufferParams::PAPER_A4PAPER:
2221 case BufferParams::PAPER_A5PAPER:
2224 case BufferParams::PAPER_B5PAPER:
2229 if (!params.topmargin.empty())
2230 ofs << ",tmargin=" << params.topmargin;
2231 if (!params.bottommargin.empty())
2232 ofs << ",bmargin=" << params.bottommargin;
2233 if (!params.leftmargin.empty())
2234 ofs << ",lmargin=" << params.leftmargin;
2235 if (!params.rightmargin.empty())
2236 ofs << ",rmargin=" << params.rightmargin;
2237 if (!params.headheight.empty())
2238 ofs << ",headheight=" << params.headheight;
2239 if (!params.headsep.empty())
2240 ofs << ",headsep=" << params.headsep;
2241 if (!params.footskip.empty())
2242 ofs << ",footskip=" << params.footskip;
2246 if (features.amsstyle
2247 && !tclass.provides(LyXTextClass::amsmath)) {
2248 ofs << "\\usepackage{amsmath}\n";
2252 if (tokenPos(tclass.opt_pagestyle(),
2253 '|', params.pagestyle) >= 0) {
2254 if (params.pagestyle == "fancy") {
2255 ofs << "\\usepackage{fancyhdr}\n";
2258 ofs << "\\pagestyle{" << params.pagestyle << "}\n";
2262 // We try to load babel late, in case it interferes
2263 // with other packages.
2265 string tmp = lyxrc.language_package;
2266 if (!lyxrc.language_global_options
2267 && tmp == "\\usepackage{babel}")
2268 tmp = string("\\usepackage[") +
2269 language_options.str().c_str() +
2275 if (params.secnumdepth != tclass.secnumdepth()) {
2276 ofs << "\\setcounter{secnumdepth}{"
2277 << params.secnumdepth
2281 if (params.tocdepth != tclass.tocdepth()) {
2282 ofs << "\\setcounter{tocdepth}{"
2288 if (params.paragraph_separation) {
2289 switch (params.defskip.kind()) {
2290 case VSpace::SMALLSKIP:
2291 ofs << "\\setlength\\parskip{\\smallskipamount}\n";
2293 case VSpace::MEDSKIP:
2294 ofs << "\\setlength\\parskip{\\medskipamount}\n";
2296 case VSpace::BIGSKIP:
2297 ofs << "\\setlength\\parskip{\\bigskipamount}\n";
2299 case VSpace::LENGTH:
2300 ofs << "\\setlength\\parskip{"
2301 << params.defskip.length().asLatexString()
2304 default: // should never happen // Then delete it.
2305 ofs << "\\setlength\\parskip{\\medskipamount}\n";
2310 ofs << "\\setlength\\parindent{0pt}\n";
2314 // Now insert the LyX specific LaTeX commands...
2316 // The optional packages;
2317 string preamble(features.getPackages());
2319 // this might be useful...
2320 preamble += "\n\\makeatletter\n";
2322 // Some macros LyX will need
2323 string tmppreamble(features.getMacros());
2325 if (!tmppreamble.empty()) {
2326 preamble += "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2327 "LyX specific LaTeX commands.\n"
2328 + tmppreamble + '\n';
2331 // the text class specific preamble
2332 tmppreamble = features.getTClassPreamble();
2333 if (!tmppreamble.empty()) {
2334 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2335 "Textclass specific LaTeX commands.\n"
2336 + tmppreamble + '\n';
2339 /* the user-defined preamble */
2340 if (!params.preamble.empty()) {
2341 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2342 "User specified LaTeX commands.\n"
2343 + params.preamble + '\n';
2346 preamble += "\\makeatother\n";
2348 // Itemize bullet settings need to be last in case the user
2349 // defines their own bullets that use a package included
2350 // in the user-defined preamble -- ARRae
2351 // Actually it has to be done much later than that
2352 // since some packages like frenchb make modifications
2353 // at \begin{document} time -- JMarc
2355 for (int i = 0; i < 4; ++i) {
2356 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
2357 if (bullets_def.empty())
2358 bullets_def="\\AtBeginDocument{\n";
2359 bullets_def += " \\renewcommand{\\labelitemi";
2361 // `i' is one less than the item to modify
2368 bullets_def += "ii";
2374 bullets_def += "}{" +
2375 params.user_defined_bullets[i].getText()
2380 if (!bullets_def.empty())
2381 preamble += bullets_def + "}\n\n";
2383 for (int j = countChar(preamble, '\n'); j-- ;) {
2390 ofs << "\\begin{document}\n";
2393 lyxerr[Debug::INFO] << "preamble finished, now the body." << endl;
2395 if (!lyxrc.language_auto_begin) {
2396 ofs << subst(lyxrc.language_command_begin, "$$lang",
2397 params.language->babel())
2402 latexParagraphs(ofs, paragraph, 0, texrow);
2404 // add this just in case after all the paragraphs
2408 if (!lyxrc.language_auto_end) {
2409 ofs << subst(lyxrc.language_command_end, "$$lang",
2410 params.language->babel())
2416 ofs << "\\end{document}\n";
2419 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
2421 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
2425 // Just to be sure. (Asger)
2428 // tex_code_break_column's value is used to decide
2429 // if we are in batchmode or not (within mathed_write()
2430 // in math_write.C) so we must set it to a non-zero
2431 // value when we leave otherwise we save incorrect .lyx files.
2432 tex_code_break_column = lyxrc.ascii_linelen;
2436 lyxerr << "File was not closed properly." << endl;
2439 lyxerr[Debug::INFO] << "Finished making latex file." << endl;
2444 // LaTeX all paragraphs from par to endpar, if endpar == 0 then to the end
2446 void Buffer::latexParagraphs(ostream & ofs, Paragraph * par,
2447 Paragraph * endpar, TexRow & texrow) const
2449 bool was_title = false;
2450 bool already_title = false;
2453 while (par != endpar) {
2454 LyXLayout const & layout =
2455 textclasslist.Style(params.textclass,
2458 if (layout.intitle) {
2459 if (already_title) {
2460 lyxerr <<"Error in latexParagraphs: You"
2461 " should not mix title layouts"
2462 " with normal ones." << endl;
2465 } else if (was_title && !already_title) {
2466 ofs << "\\maketitle\n";
2468 already_title = true;
2472 if (layout.isEnvironment()) {
2473 par = par->TeXEnvironment(this, params, ofs, texrow);
2475 par = par->TeXOnePar(this, params, ofs, texrow, false);
2478 // It might be that we only have a title in this document
2479 if (was_title && !already_title) {
2480 ofs << "\\maketitle\n";
2486 bool Buffer::isLatex() const
2488 return textclasslist.TextClass(params.textclass).outputType() == LATEX;
2492 bool Buffer::isLinuxDoc() const
2494 return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC;
2498 bool Buffer::isLiterate() const
2500 return textclasslist.TextClass(params.textclass).outputType() == LITERATE;
2504 bool Buffer::isDocBook() const
2506 return textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2510 bool Buffer::isSGML() const
2512 return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC ||
2513 textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2517 void Buffer::sgmlOpenTag(ostream & os, Paragraph::depth_type depth,
2518 string const & latexname) const
2520 if (!latexname.empty() && latexname != "!-- --")
2521 os << "<!-- " << depth << " -->" << "<" << latexname << ">";
2522 //os << string(depth, ' ') << "<" << latexname << ">\n";
2526 void Buffer::sgmlCloseTag(ostream & os, Paragraph::depth_type depth,
2527 string const & latexname) const
2529 if (!latexname.empty() && latexname != "!-- --")
2530 os << "<!-- " << depth << " -->" << "</" << latexname << ">\n";
2531 //os << string(depth, ' ') << "</" << latexname << ">\n";
2535 void Buffer::makeLinuxDocFile(string const & fname, bool nice, bool body_only)
2537 ofstream ofs(fname.c_str());
2540 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2544 niceFile = nice; // this will be used by included files.
2546 LyXTextClass const & tclass =
2547 textclasslist.TextClass(params.textclass);
2549 LaTeXFeatures features(params, tclass.numLayouts());
2554 string top_element = textclasslist.LatexnameOfClass(params.textclass);
2557 string sgml_includedfiles=features.getIncludedFiles(fname);
2559 if (params.preamble.empty() && sgml_includedfiles.empty()) {
2560 ofs << "<!doctype linuxdoc system>\n\n";
2562 ofs << "<!doctype linuxdoc system [ "
2563 << params.preamble << sgml_includedfiles << " \n]>\n\n";
2566 if (params.options.empty())
2567 sgmlOpenTag(ofs, 0, top_element);
2569 string top = top_element;
2571 top += params.options;
2572 sgmlOpenTag(ofs, 0, top);
2576 ofs << "<!-- " << LYX_DOCVERSION
2577 << " created this file. For more info see http://www.lyx.org/"
2580 Paragraph::depth_type depth = 0; // paragraph depth
2581 Paragraph * par = paragraph;
2583 vector<string> environment_stack(5);
2586 LyXLayout const & style =
2587 textclasslist.Style(params.textclass,
2590 // treat <toc> as a special case for compatibility with old code
2591 if (par->getChar(0) == Paragraph::META_INSET) {
2592 Inset * inset = par->getInset(0);
2593 Inset::Code lyx_code = inset->lyxCode();
2594 if (lyx_code == Inset::TOC_CODE){
2595 string const temp = "toc";
2596 sgmlOpenTag(ofs, depth, temp);
2603 // environment tag closing
2604 for (; depth > par->params().depth(); --depth) {
2605 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2606 environment_stack[depth].erase();
2609 // write opening SGML tags
2610 switch (style.latextype) {
2611 case LATEX_PARAGRAPH:
2612 if (depth == par->params().depth()
2613 && !environment_stack[depth].empty()) {
2614 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2615 environment_stack[depth].erase();
2621 sgmlOpenTag(ofs, depth, style.latexname());
2626 linuxDocError(par, 0,
2627 _("Error : Wrong depth for"
2628 " LatexType Command.\n"));
2630 if (!environment_stack[depth].empty()){
2631 sgmlCloseTag(ofs, depth,
2632 environment_stack[depth]);
2636 environment_stack[depth].erase();
2637 sgmlOpenTag(ofs, depth, style.latexname());
2640 case LATEX_ENVIRONMENT:
2641 case LATEX_ITEM_ENVIRONMENT:
2642 if (depth == par->params().depth()
2643 && environment_stack[depth] != style.latexname()) {
2644 sgmlCloseTag(ofs, depth,
2645 environment_stack[depth]);
2646 environment_stack[depth].erase();
2648 if (depth < par->params().depth()) {
2649 depth = par->params().depth();
2650 environment_stack[depth].erase();
2652 if (environment_stack[depth] != style.latexname()) {
2654 sgmlOpenTag(ofs, depth, "p");
2656 sgmlOpenTag(ofs, depth, style.latexname());
2658 if (environment_stack.size() == depth + 1)
2659 environment_stack.push_back("!-- --");
2660 environment_stack[depth] = style.latexname();
2663 if (style.latexparam() == "CDATA")
2666 if (style.latextype == LATEX_ENVIRONMENT) break;
2668 if (style.labeltype == LABEL_MANUAL)
2673 sgmlOpenTag(ofs, depth + 1, item_name);
2676 sgmlOpenTag(ofs, depth, style.latexname());
2680 simpleLinuxDocOnePar(ofs, par, depth);
2685 // write closing SGML tags
2686 switch (style.latextype) {
2689 case LATEX_ENVIRONMENT:
2690 case LATEX_ITEM_ENVIRONMENT:
2691 if (style.latexparam() == "CDATA")
2695 sgmlCloseTag(ofs, depth, style.latexname());
2701 for (int i=depth; i >= 0; --i)
2702 sgmlCloseTag(ofs, depth, environment_stack[i]);
2706 sgmlCloseTag(ofs, 0, top_element);
2710 // How to check for successful close
2714 void Buffer::docBookHandleCaption(ostream & os, string & inner_tag,
2715 Paragraph::depth_type depth, int desc_on,
2718 Paragraph * tpar = par;
2720 && (tpar->layout != textclasslist.NumberOfLayout(params.textclass,
2722 tpar = tpar->next();
2725 tpar->layout == textclasslist.NumberOfLayout(params.textclass,
2726 "Caption").second) {
2727 sgmlOpenTag(os, depth + 1, inner_tag);
2729 simpleDocBookOnePar(os, extra_par, tpar,
2730 desc_on, depth + 2);
2731 sgmlCloseTag(os, depth+1, inner_tag);
2732 if (!extra_par.empty())
2738 // checks, if newcol chars should be put into this line
2739 // writes newline, if necessary.
2742 void linux_doc_line_break(ostream & os, string::size_type & colcount,
2743 string::size_type newcol)
2746 if (colcount > lyxrc.ascii_linelen) {
2748 colcount = newcol; // assume write after this call
2763 string tag_name(PAR_TAG const & pt) {
2765 case NONE: return "!-- --";
2766 case TT: return "tt";
2767 case SF: return "sf";
2768 case BF: return "bf";
2769 case IT: return "it";
2770 case SL: return "sl";
2771 case EM: return "em";
2778 void operator|=(PAR_TAG & p1, PAR_TAG const & p2)
2780 p1 = static_cast<PAR_TAG>(p1 | p2);
2785 void reset(PAR_TAG & p1, PAR_TAG const & p2)
2787 p1 = static_cast<PAR_TAG>( p1 & ~p2);
2795 // Handle internal paragraph parsing -- layout already processed.
2796 void Buffer::simpleLinuxDocOnePar(ostream & os,
2798 Paragraph::depth_type /*depth*/)
2800 LyXLayout const & style = textclasslist.Style(params.textclass,
2802 string::size_type char_line_count = 5; // Heuristic choice ;-)
2804 // gets paragraph main font
2807 if (style.labeltype == LABEL_MANUAL) {
2808 font_old = style.labelfont;
2811 font_old = style.font;
2815 LyXFont::FONT_FAMILY family_type = LyXFont::ROMAN_FAMILY;
2816 LyXFont::FONT_SERIES series_type = LyXFont::MEDIUM_SERIES;
2817 LyXFont::FONT_SHAPE shape_type = LyXFont::UP_SHAPE;
2820 stack < PAR_TAG > tag_state;
2821 // parsing main loop
2822 for (Paragraph::size_type i = 0; i < par->size(); ++i) {
2824 PAR_TAG tag_close = NONE;
2825 list < PAR_TAG > tag_open;
2827 LyXFont const font = par->getFont(params, i);
2829 if (font_old.family() != font.family()) {
2830 switch (family_type) {
2831 case LyXFont::SANS_FAMILY:
2834 case LyXFont::TYPEWRITER_FAMILY:
2841 family_type = font.family();
2843 switch (family_type) {
2844 case LyXFont::SANS_FAMILY:
2845 tag_open.push_back(SF);
2847 case LyXFont::TYPEWRITER_FAMILY:
2848 tag_open.push_back(TT);
2855 if (font_old.series() != font.series()) {
2856 switch (series_type) {
2857 case LyXFont::BOLD_SERIES:
2864 series_type = font.series();
2866 switch (series_type) {
2867 case LyXFont::BOLD_SERIES:
2868 tag_open.push_back(BF);
2876 if (font_old.shape() != font.shape()) {
2877 switch (shape_type) {
2878 case LyXFont::ITALIC_SHAPE:
2881 case LyXFont::SLANTED_SHAPE:
2888 shape_type = font.shape();
2890 switch (shape_type) {
2891 case LyXFont::ITALIC_SHAPE:
2892 tag_open.push_back(IT);
2894 case LyXFont::SLANTED_SHAPE:
2895 tag_open.push_back(SL);
2902 if (font_old.emph() != font.emph()) {
2903 if (font.emph() == LyXFont::ON) {
2904 tag_open.push_back(EM);
2913 list < PAR_TAG > temp;
2914 while(!tag_state.empty() && tag_close ) {
2915 PAR_TAG k = tag_state.top();
2917 os << "</" << tag_name(k) << ">";
2924 for(list< PAR_TAG >::const_iterator j = temp.begin();
2925 j != temp.end(); ++j) {
2927 os << "<" << tag_name(*j) << ">";
2930 for(list< PAR_TAG >::const_iterator j = tag_open.begin();
2931 j != tag_open.end(); ++j) {
2933 os << "<" << tag_name(*j) << ">";
2936 char c = par->getChar(i);
2938 if (c == Paragraph::META_INSET) {
2939 Inset * inset = par->getInset(i);
2940 inset->linuxdoc(this, os);
2947 font.latex() == LyXFont::ON ||
2949 style.latexparam() == "CDATA") {
2950 // "TeX"-Mode on == > SGML-Mode on.
2956 if (par->linuxDocConvertChar(c, sgml_string)
2957 && !style.free_spacing) {
2958 // in freespacing mode, spaces are
2959 // non-breaking characters
2960 if (desc_on) {// if char is ' ' then...
2963 linux_doc_line_break(os, char_line_count, 6);
2967 linux_doc_line_break(os, char_line_count, 1);
2972 char_line_count += sgml_string.length();
2978 while (!tag_state.empty()) {
2979 os << "</" << tag_name(tag_state.top()) << ">";
2983 // resets description flag correctly
2985 // <tag> not closed...
2986 linux_doc_line_break(os, char_line_count, 6);
2992 // Print an error message.
2993 void Buffer::linuxDocError(Paragraph * par, int pos,
2994 string const & message)
2996 // insert an error marker in text
2997 InsetError * new_inset = new InsetError(message);
2998 par->insertInset(pos, new_inset);
3002 void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
3004 ofstream ofs(fname.c_str());
3006 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
3010 Paragraph * par = paragraph;
3012 niceFile = nice; // this will be used by Insetincludes.
3014 LyXTextClass const & tclass =
3015 textclasslist.TextClass(params.textclass);
3017 LaTeXFeatures features(params, tclass.numLayouts());
3022 string top_element = textclasslist.LatexnameOfClass(params.textclass);
3025 string sgml_includedfiles = features.getIncludedFiles(fname);
3027 ofs << "<!doctype " << top_element
3028 << " public \"-//OASIS//DTD DocBook V3.1//EN\"";
3030 if (params.preamble.empty() && sgml_includedfiles.empty())
3033 ofs << "\n [ " << params.preamble
3034 << sgml_includedfiles << " \n]>\n\n";
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,
3119 linuxDocError(par, 0,
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 if (par->getChar(0) == Paragraph::META_INSET) {
3152 Inset * inset = par->getInset(0);
3153 Inset::Code lyx_code = inset->lyxCode();
3154 if (lyx_code == Inset::LABEL_CODE){
3155 command_name += " id=\"";
3156 command_name += (static_cast<InsetCommand *>(inset))->getContents();
3157 command_name += "\"";
3162 sgmlOpenTag(ofs, depth + command_depth, command_name);
3163 if (c_params.empty())
3164 item_name = "title";
3166 item_name = c_params;
3167 sgmlOpenTag(ofs, depth + 1 + command_depth, item_name);
3170 case LATEX_ENVIRONMENT:
3171 case LATEX_ITEM_ENVIRONMENT:
3172 if (depth < par->params().depth()) {
3173 depth = par->params().depth();
3174 environment_stack[depth].erase();
3177 if (environment_stack[depth] != style.latexname()) {
3178 if(environment_stack.size() == depth + 1) {
3179 environment_stack.push_back("!-- --");
3180 environment_inner.push_back("!-- --");
3182 environment_stack[depth] = style.latexname();
3183 environment_inner[depth] = "!-- --";
3184 sgmlOpenTag(ofs, depth + command_depth,
3185 environment_stack[depth]);
3187 if (environment_inner[depth] != "!-- --") {
3188 item_name= "listitem";
3190 command_depth + depth,
3192 if (environment_inner[depth] == "varlistentry")
3194 depth + command_depth,
3195 environment_inner[depth]);
3199 if (style.latextype == LATEX_ENVIRONMENT) {
3200 if (!style.latexparam().empty()) {
3201 if(style.latexparam() == "CDATA")
3204 sgmlOpenTag(ofs, depth + command_depth,
3205 style.latexparam());
3210 desc_on = (style.labeltype == LABEL_MANUAL);
3213 environment_inner[depth]= "varlistentry";
3215 environment_inner[depth]= "listitem";
3217 sgmlOpenTag(ofs, depth + 1 + command_depth,
3218 environment_inner[depth]);
3222 sgmlOpenTag(ofs, depth + 1 + command_depth,
3226 sgmlOpenTag(ofs, depth + 1 + command_depth,
3231 sgmlOpenTag(ofs, depth + command_depth,
3237 simpleDocBookOnePar(ofs, extra_par, par, desc_on,
3238 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, string & extra,
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 (Paragraph::size_type i = 0;
3320 i < par->size(); ++i) {
3321 LyXFont font = par->getFont(params, i);
3323 // handle <emphasis> tag
3324 if (font_old.emph() != font.emph()) {
3325 if (font.emph() == LyXFont::ON) {
3329 os << "</emphasis>";
3334 char c = par->getChar(i);
3336 if (c == Paragraph::META_INSET) {
3337 Inset * inset = par->getInset(i);
3339 inset->docBook(this, ost);
3340 string tmp_out = ost.str().c_str();
3343 // This code needs some explanation:
3344 // Two insets are treated specially
3345 // label if it is the first element in a command paragraph
3347 // graphics inside tables or figure floats can't go on
3348 // title (the equivalente in latex for this case is caption
3349 // and title should come first
3352 if (desc_on!= 3 || i!= 0) {
3353 if (!tmp_out.empty() && tmp_out[0] == '@') {
3355 extra += frontStrip(tmp_out, '@');
3357 os << frontStrip(tmp_out, '@');
3363 } else if (font.latex() == LyXFont::ON) {
3364 // "TeX"-Mode on ==> SGML-Mode on.
3371 if (par->linuxDocConvertChar(c, sgml_string)
3372 && !style.free_spacing) { // in freespacing
3374 // non-breaking characters
3378 os << "\n</term><listitem><para>";
3391 os << "</emphasis>";
3394 // resets description flag correctly
3396 // <term> not closed...
3399 if(style.free_spacing) os << '\n';
3403 // This should be enabled when the Chktex class is implemented. (Asger)
3404 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
3405 // Other flags: -wall -v0 -x
3406 int Buffer::runChktex()
3408 if (!users->text) return 0;
3410 users->owner()->prohibitInput();
3412 // get LaTeX-Filename
3413 string const name = getLatexName();
3414 string path = OnlyPath(filename);
3416 string const org_path = path;
3417 if (lyxrc.use_tempdir || (IsDirWriteable(path) < 1)) {
3421 Path p(path); // path to LaTeX file
3422 users->owner()->message(_("Running chktex..."));
3424 // Remove all error insets
3425 bool const removedErrorInsets = users->removeAutoInsets();
3427 // Generate the LaTeX file if neccessary
3428 makeLaTeXFile(name, org_path, false);
3431 Chktex chktex(lyxrc.chktex_command, name, filepath);
3432 int res = chktex.run(terr); // run chktex
3435 WriteAlert(_("chktex did not work!"),
3436 _("Could not run with file:"), name);
3437 } else if (res > 0) {
3438 // Insert all errors as errors boxes
3439 users->insertErrors(terr);
3442 // if we removed error insets before we ran chktex or if we inserted
3443 // error insets after we ran chktex, this must be run:
3444 if (removedErrorInsets || res){
3446 users->fitCursor(users->text);
3448 users->owner()->allowInput();
3454 void Buffer::validate(LaTeXFeatures & features) const
3456 Paragraph * par = paragraph;
3457 LyXTextClass const & tclass =
3458 textclasslist.TextClass(params.textclass);
3460 // AMS Style is at document level
3461 features.amsstyle = (params.use_amsmath ||
3462 tclass.provides(LyXTextClass::amsmath));
3465 // We don't use "lyxerr.debug" because of speed. (Asger)
3466 if (lyxerr.debugging(Debug::LATEX))
3467 lyxerr << "Paragraph: " << par << endl;
3469 // Now just follow the list of paragraphs and run
3470 // validate on each of them.
3471 par->validate(features);
3473 // and then the next paragraph
3477 // the bullet shapes are buffer level not paragraph level
3478 // so they are tested here
3479 for (int i = 0; i < 4; ++i) {
3480 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
3481 int const font = params.user_defined_bullets[i].getFont();
3483 int const c = params
3484 .user_defined_bullets[i]
3491 features.latexsym = true;
3493 } else if (font == 1) {
3494 features.amssymb = true;
3495 } else if ((font >= 2 && font <= 5)) {
3496 features.pifont = true;
3501 if (lyxerr.debugging(Debug::LATEX)) {
3502 features.showStruct();
3507 void Buffer::setPaperStuff()
3509 params.papersize = BufferParams::PAPER_DEFAULT;
3510 char const c1 = params.paperpackage;
3511 if (c1 == BufferParams::PACKAGE_NONE) {
3512 char const c2 = params.papersize2;
3513 if (c2 == BufferParams::VM_PAPER_USLETTER)
3514 params.papersize = BufferParams::PAPER_USLETTER;
3515 else if (c2 == BufferParams::VM_PAPER_USLEGAL)
3516 params.papersize = BufferParams::PAPER_LEGALPAPER;
3517 else if (c2 == BufferParams::VM_PAPER_USEXECUTIVE)
3518 params.papersize = BufferParams::PAPER_EXECUTIVEPAPER;
3519 else if (c2 == BufferParams::VM_PAPER_A3)
3520 params.papersize = BufferParams::PAPER_A3PAPER;
3521 else if (c2 == BufferParams::VM_PAPER_A4)
3522 params.papersize = BufferParams::PAPER_A4PAPER;
3523 else if (c2 == BufferParams::VM_PAPER_A5)
3524 params.papersize = BufferParams::PAPER_A5PAPER;
3525 else if ((c2 == BufferParams::VM_PAPER_B3) || (c2 == BufferParams::VM_PAPER_B4) ||
3526 (c2 == BufferParams::VM_PAPER_B5))
3527 params.papersize = BufferParams::PAPER_B5PAPER;
3528 } else if ((c1 == BufferParams::PACKAGE_A4) || (c1 == BufferParams::PACKAGE_A4WIDE) ||
3529 (c1 == BufferParams::PACKAGE_WIDEMARGINSA4))
3530 params.papersize = BufferParams::PAPER_A4PAPER;
3534 // This function should be in Buffer because it's a buffer's property (ale)
3535 string const Buffer::getIncludeonlyList(char delim)
3538 for (inset_iterator it = inset_iterator_begin();
3539 it != inset_iterator_end(); ++it) {
3540 if ((*it)->lyxCode() == Inset::INCLUDE_CODE) {
3541 InsetInclude * insetinc =
3542 static_cast<InsetInclude *>(*it);
3543 if (insetinc->isIncludeOnly()) {
3546 lst += insetinc->getRelFileBaseName();
3550 lyxerr[Debug::INFO] << "Includeonly(" << lst << ')' << endl;
3555 vector<string> const Buffer::getLabelList()
3557 /// if this is a child document and the parent is already loaded
3558 /// Use the parent's list instead [ale990407]
3559 if (!params.parentname.empty()
3560 && bufferlist.exists(params.parentname)) {
3561 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3563 return tmp->getLabelList();
3566 vector<string> label_list;
3567 for (inset_iterator it = inset_iterator_begin();
3568 it != inset_iterator_end(); ++it) {
3569 vector<string> const l = (*it)->getLabelList();
3570 label_list.insert(label_list.end(), l.begin(), l.end());
3576 Buffer::Lists const Buffer::getLists() const
3579 Paragraph * par = paragraph;
3581 LyXTextClassList::size_type cap;
3582 boost::tie(found, cap) = textclasslist
3583 .NumberOfLayout(params.textclass, "Caption");
3586 char const labeltype =
3587 textclasslist.Style(params.textclass,
3588 par->getLayout()).labeltype;
3590 if (labeltype >= LABEL_COUNTER_CHAPTER
3591 && labeltype <= LABEL_COUNTER_CHAPTER + params.tocdepth) {
3592 // insert this into the table of contents
3593 SingleList & item = l["TOC"];
3596 textclasslist.TextClass(params.textclass).maxcounter());
3597 item.push_back(TocItem(par, depth, par->asString(this, true)));
3599 // For each paragrph, traverse its insets and look for
3603 Paragraph::inset_iterator it =
3604 par->inset_iterator_begin();
3605 Paragraph::inset_iterator end =
3606 par->inset_iterator_end();
3608 for (; it != end; ++it) {
3609 if ((*it)->lyxCode() == Inset::FLOAT_CODE) {
3611 static_cast<InsetFloat*>(*it);
3613 string const type = il->type();
3615 // Now find the caption in the float...
3616 // We now tranverse the paragraphs of
3618 Paragraph * tmp = il->inset.paragraph();
3620 if (tmp->layout == cap) {
3621 SingleList & item = l[type];
3623 tostr(item.size()+1) + ". " + tmp->asString(this, false);
3624 item.push_back(TocItem(tmp, 0 , str));
3631 lyxerr << "caption not found" << endl;
3640 // This is also a buffer property (ale)
3641 vector<pair<string, string> > const Buffer::getBibkeyList()
3643 /// if this is a child document and the parent is already loaded
3644 /// Use the parent's list instead [ale990412]
3645 if (!params.parentname.empty() && bufferlist.exists(params.parentname)) {
3646 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3648 return tmp->getBibkeyList();
3651 vector<pair<string, string> > keys;
3652 Paragraph * par = paragraph;
3655 keys.push_back(pair<string, string>(par->bibkey->getContents(),
3656 par->asString(this, false)));
3660 // Might be either using bibtex or a child has bibliography
3662 for (inset_iterator it = inset_iterator_begin();
3663 it != inset_iterator_end(); ++it) {
3664 // Search for Bibtex or Include inset
3665 if ((*it)->lyxCode() == Inset::BIBTEX_CODE) {
3666 vector<pair<string,string> > tmp =
3667 static_cast<InsetBibtex*>(*it)->getKeys(this);
3668 keys.insert(keys.end(), tmp.begin(), tmp.end());
3669 } else if ((*it)->lyxCode() == Inset::INCLUDE_CODE) {
3670 vector<pair<string,string> > const tmp =
3671 static_cast<InsetInclude*>(*it)->getKeys();
3672 keys.insert(keys.end(), tmp.begin(), tmp.end());
3681 bool Buffer::isDepClean(string const & name) const
3683 DEPCLEAN * item = dep_clean;
3684 while (item && item->master != name)
3686 if (!item) return true;
3691 void Buffer::markDepClean(string const & name)
3694 dep_clean = new DEPCLEAN;
3695 dep_clean->clean = true;
3696 dep_clean->master = name;
3697 dep_clean->next = 0;
3699 DEPCLEAN * item = dep_clean;
3700 while (item && item->master != name)
3705 item = new DEPCLEAN;
3707 item->master = name;
3714 bool Buffer::dispatch(string const & command)
3716 // Split command string into command and argument
3718 string line = frontStrip(command);
3719 string const arg = strip(frontStrip(split(line, cmd, ' ')));
3721 return dispatch(lyxaction.LookupFunc(cmd), arg);
3725 bool Buffer::dispatch(int action, string const & argument)
3727 bool dispatched = true;
3730 Exporter::Export(this, argument, false);
3740 void Buffer::resizeInsets(BufferView * bv)
3742 /// then remove all LyXText in text-insets
3743 Paragraph * par = paragraph;
3744 for (; par; par = par->next()) {
3745 par->resizeInsetsLyXText(bv);
3750 void Buffer::redraw()
3753 users->fitCursor(users->text);
3757 void Buffer::changeLanguage(Language const * from, Language const * to)
3760 Paragraph * par = paragraph;
3762 par->changeLanguage(params, from, to);
3768 bool Buffer::isMultiLingual()
3770 Paragraph * par = paragraph;
3772 if (par->isMultiLingual(params))
3780 Buffer::inset_iterator::inset_iterator(Paragraph * paragraph,
3781 Paragraph::size_type pos)
3784 it = par->InsetIterator(pos);
3785 if (it == par->inset_iterator_end()) {
3792 void Buffer::inset_iterator::setParagraph()
3795 it = par->inset_iterator_begin();
3796 if (it != par->inset_iterator_end())
3801 // We maintain an invariant that whenever par = 0 then it = 0
3805 Inset * Buffer::getInsetFromID(int id_arg) const
3807 for (inset_iterator it = inset_const_iterator_begin();
3808 it != inset_const_iterator_end(); ++it)
3810 if ((*it)->id() == id_arg)
3812 Inset * in = (*it)->getInsetFromID(id_arg);
3820 Paragraph * Buffer::getParFromID(int id) const
3822 if (id < 0) return 0;
3823 Paragraph * par = paragraph;
3825 if (par->id() == id) {
3828 Paragraph * tmp = par->getParFromID(id);